diff options
| author | 8cy <[email protected]> | 2020-04-03 02:48:28 -0700 |
|---|---|---|
| committer | 8cy <[email protected]> | 2020-04-03 02:48:28 -0700 |
| commit | f9159ea2d994e14180fb02ab562f0119513e67cf (patch) | |
| tree | 09d14cdf05456567156738b681379d4bccd64e5c /node_modules/node-addon-api | |
| parent | 2020/04/03, 02:42, V1.2.1 (diff) | |
| download | s5nical-f9159ea2d994e14180fb02ab562f0119513e67cf.tar.xz s5nical-f9159ea2d994e14180fb02ab562f0119513e67cf.zip | |
2020/04/03, 02:47, V1.2.2
Diffstat (limited to 'node_modules/node-addon-api')
76 files changed, 0 insertions, 21961 deletions
diff --git a/node_modules/node-addon-api/.editorconfig b/node_modules/node-addon-api/.editorconfig deleted file mode 100644 index 5e9b7bf..0000000 --- a/node_modules/node-addon-api/.editorconfig +++ /dev/null @@ -1,8 +0,0 @@ -root = true - -[*] -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -indent_style = space -indent_size = 2 diff --git a/node_modules/node-addon-api/.travis.yml b/node_modules/node-addon-api/.travis.yml deleted file mode 100644 index 008e9ed..0000000 --- a/node_modules/node-addon-api/.travis.yml +++ /dev/null @@ -1,62 +0,0 @@ -language: c++ -compiler: - - clang - - gcc -# For Linux, use an Ubuntu 14 image -dist: trusty -os: - - linux - - osx -env: - global: - # https://github.com/jasongin/nvs/blob/master/doc/CI.md - - NVS_VERSION=1.4.2 - matrix: - - NODEJS_VERSION=node/6 - - NODEJS_VERSION=node/8 - - NODEJS_VERSION=node/10 - - NODEJS_VERSION=node/12 - - NODEJS_VERSION=node/13 - - NODEJS_VERSION=nightly -matrix: - fast_finish: true - allow_failures: - - env: NODEJS_VERSION=nightly - - env: NODEJS_VERSION=node/6 -sudo: false -cache: - directories: - - node_modules - - $HOME/.npm -addons: - apt: - sources: - - ubuntu-toolchain-r-test - packages: - - g++-4.9 -before_install: - # coveralls - - pip2 install --user cpp-coveralls - # compilers - - if [ "$CXX" = "g++" -a "$TRAVIS_OS_NAME" = "linux" ]; then export CXX="g++-4.9" CC="gcc-4.9" AR="gcc-ar-4.9" RANLIB="gcc-ranlib-4.9" NM="gcc-nm-4.9" ; fi - - if [ "$CXX" = "clang++" ]; then export NPMOPT=--clang=1 ; fi - - export CFLAGS="$CFLAGS -O3 --coverage" LDFLAGS="$LDFLAGS --coverage" - - echo "CFLAGS=\"$CFLAGS\" LDFLAGS=\"$LDFLAGS\"" - # nvs - - git clone --branch v$NVS_VERSION --depth 1 https://github.com/jasongin/nvs ~/.nvs - - . ~/.nvs/nvs.sh - - nvs --version - # node.js - - nvs add $NODEJS_VERSION - - nvs use $NODEJS_VERSION - - node --version - - npm --version -install: - - npm install $NPMOPT -script: - # Travis CI sets NVM_NODEJS_ORG_MIRROR, but it makes node-gyp fail to download headers for nightly builds. - - unset NVM_NODEJS_ORG_MIRROR - - - npm test -after_success: - - cpp-coveralls --gcov-options '\-lp' --build-root test/build --exclude test diff --git a/node_modules/node-addon-api/CHANGELOG.md b/node_modules/node-addon-api/CHANGELOG.md deleted file mode 100644 index 8a2a6d1..0000000 --- a/node_modules/node-addon-api/CHANGELOG.md +++ /dev/null @@ -1,376 +0,0 @@ -# node-addon-api Changelog - -## 2019-11-21 Version 2.0.0, @NickNaso - -### Notable changes: - -#### API - -- Added `Napi::AsyncProgressWorker` api. -- Added error checking on `Napi::ThreadSafeFunction::GetContext`. -- Added copy constructor to `Napi::ThreadSafeFunction`. -- Added `Napi::ThreadSafeFunction::Ref` and `Napi::ThreadSafeFunction::Unref` to `Napi::ThreadSafeFunction`. -- Added `Napi::Object::AddFinalizer` method. -- Use `napi_add_finalizer()` to attach data when building against N-API 5. -- Added `Napi::Date` api. -- Added `Napi::ObjectWrap::Finalize` method. - -#### Documentation - -- Added documentation for `Napi::AsyncProgressWorker`. -- Improve `Napi::AsyncWorker` documentation. -- Added documentation for `Napi::Object::AddFinalizer` method. -- Improved documentation for `Napi::ThreadSafeFunction`. -- Improved documentation about the usage of CMake as build tool. -- Some minor corrections all over the documentation. - -#### TEST - -- Added test cases for `Napi::AsyncProgressWorker` api. -- Added test cases for `Napi::Date` api. -- Added test cases for new features added to `Napi::ThreadSafeFunction`. - -### Commmits - -* [[`c881168d49`](https://github.com/nodejs/node-addon-api/commit/c881168d49)] - **tsfn**: add error checking on GetContext (#583) (Kevin Eady) [#583](https://github.com/nodejs/node-addon-api/pull/583) -* [[`24d75dd82f`](https://github.com/nodejs/node-addon-api/commit/24d75dd82f)] - Merge pull request #588 from NickNaso/add-asyncprogress-worker-readme (Nicola Del Gobbo) -* [[`aa79e37b62`](https://github.com/nodejs/node-addon-api/commit/aa79e37b62)] - Merge pull request #587 from timrach/patch-1 (Nicola Del Gobbo) -* [[`df75e08c2b`](https://github.com/nodejs/node-addon-api/commit/df75e08c2b)] - **tsfn**: support direct calls to underlying napi\_tsfn (Kevin Eady) [#58](https://github.com/nodejs/node-addon-api/pull/58) -* [[`2298dfae58`](https://github.com/nodejs/node-addon-api/commit/2298dfae58)] - **doc**: Added AsyncProgressWorker to readme (NickNaso) -* [[`b3609d33b6`](https://github.com/nodejs/node-addon-api/commit/b3609d33b6)] - Fix return type and declaration of setter callback (Tim Rach) -* [[`295e560f55`](https://github.com/nodejs/node-addon-api/commit/295e560f55)] - **test**: improve guards for experimental features (legendecas) -* [[`2e71842f63`](https://github.com/nodejs/node-addon-api/commit/2e71842f63)] - **tsfn**: Implement copy constructor (Kevin Eady) [#546](https://github.com/nodejs/node-addon-api/pull/546) -* [[`650562cab9`](https://github.com/nodejs/node-addon-api/commit/650562cab9)] - **src**: implement AsyncProgressWorker (legendecas) [#529](https://github.com/nodejs/node-addon-api/pull/529) -* [[`bdfd14101f`](https://github.com/nodejs/node-addon-api/commit/bdfd14101f)] - **src**: attach data with napi\_add\_finalizer (Gabriel Schulhof) [#577](https://github.com/nodejs/node-addon-api/pull/577) -* [[`9e955a802b`](https://github.com/nodejs/node-addon-api/commit/9e955a802b)] - **doc**: change node.js to Node.js per guideline (#579) (Tobias Nießen) [#579](https://github.com/nodejs/node-addon-api/pull/579) -* [[`b42e21e3a9`](https://github.com/nodejs/node-addon-api/commit/b42e21e3a9)] - **build**: move node/6 to travis allowed failures and add node/13 (#573) (Gabriel Schulhof) -* [[`8d6132f609`](https://github.com/nodejs/node-addon-api/commit/8d6132f609)] - **doc**: improve AsyncWorker docs (#571) (legendecas) [#571](https://github.com/nodejs/node-addon-api/pull/571) -* [[`bc8fc23627`](https://github.com/nodejs/node-addon-api/commit/bc8fc23627)] - **test**: do not run TSFN tests on NAPI\_VERSION \< 4 (legendecas) [#576](https://github.com/nodejs/node-addon-api/pull/576) -* [[`bcc1d58fc4`](https://github.com/nodejs/node-addon-api/commit/bcc1d58fc4)] - implement Object::AddFinalizer (Gabriel Schulhof) -* [[`e9a4bcd52a`](https://github.com/nodejs/node-addon-api/commit/e9a4bcd52a)] - **doc**: updates Make.js doc to current best practices (Jim Schlight) [#558](https://github.com/nodejs/node-addon-api/pull/558) -* [[`b513d1aa7a`](https://github.com/nodejs/node-addon-api/commit/b513d1aa7a)] - **doc**: fix return type of ArrayBuffer::Data (Tobias Nießen) [#552](https://github.com/nodejs/node-addon-api/pull/552) -* [[`34c11cf0a4`](https://github.com/nodejs/node-addon-api/commit/34c11cf0a4)] - **src**: disallow copying, double close of scopes (legendecas) [#566](https://github.com/nodejs/node-addon-api/pull/566) -* [[`ce139a05e8`](https://github.com/nodejs/node-addon-api/commit/ce139a05e8)] - **src**: make failure of closing scopes fatal (legendecas) [#566](https://github.com/nodejs/node-addon-api/pull/566) -* [[`740c79823e`](https://github.com/nodejs/node-addon-api/commit/740c79823e)] - **src**: add Env() to AsyncContext (Rolf Timmermans) [#568](https://github.com/nodejs/node-addon-api/pull/568) -* [[`ea9ce1c801`](https://github.com/nodejs/node-addon-api/commit/ea9ce1c801)] - **tsfn**: add wrappers for Ref and Unref (Kevin Eady) [#561](https://github.com/nodejs/node-addon-api/pull/561) -* [[`2e1769e1a3`](https://github.com/nodejs/node-addon-api/commit/2e1769e1a3)] - **error**: remove unnecessary if condition (legendecas) [#562](https://github.com/nodejs/node-addon-api/pull/562) -* [[`828f223a87`](https://github.com/nodejs/node-addon-api/commit/828f223a87)] - **doc**: fix spelling in ObjectWrap doc (#563) (Tobias Nießen) [#563](https://github.com/nodejs/node-addon-api/pull/563) -* [[`dd9fa8a4a8`](https://github.com/nodejs/node-addon-api/commit/dd9fa8a4a8)] - **doc**: move Arunesh and Taylor to Emeritus (#540) (Michael Dawson) [#540](https://github.com/nodejs/node-addon-api/pull/540) -* [[`cf8b8415df`](https://github.com/nodejs/node-addon-api/commit/cf8b8415df)] - **doc**: add Kevin to the list of collaborators (#539) (Michael Dawson) [#539](https://github.com/nodejs/node-addon-api/pull/539) -* [[`5d6aeae7b5`](https://github.com/nodejs/node-addon-api/commit/5d6aeae7b5)] - **build**: enable travis for fast PR check (legendecas) -* [[`6192e705cd`](https://github.com/nodejs/node-addon-api/commit/6192e705cd)] - **src**: add napi\_date (Mathias Küsel) [#497](https://github.com/nodejs/node-addon-api/pull/497) -* [[`7b1ee96d52`](https://github.com/nodejs/node-addon-api/commit/7b1ee96d52)] - **doc**: update prebuild\_tools.md (Nurbol Alpysbayev) [#527](https://github.com/nodejs/node-addon-api/pull/527) -* [[`0b4f3a5b8c`](https://github.com/nodejs/node-addon-api/commit/0b4f3a5b8c)] - **tsfn**: fix crash on releasing tsfn (legendecas) [#532](https://github.com/nodejs/node-addon-api/pull/532) -* [[`c3c8814d2f`](https://github.com/nodejs/node-addon-api/commit/c3c8814d2f)] - implement virutal ObjectWrap::Finalize (Michael Price) [#515](https://github.com/nodejs/node-addon-api/pull/515) - -## 2019-07-23 Version 1.7.1, @NickNaso - -### Notable changes: - -#### API - -- Fixed compilation problems that happen on Node.js with N-API version less than 4. - -### Commmits - -* [[`c20bcbd069`](https://github.com/nodejs/node-addon-api/commit/c20bcbd069)] - Merge pull request #518 from NickNaso/master (Nicola Del Gobbo) -* [[`6720d57253`](https://github.com/nodejs/node-addon-api/commit/6720d57253)] - Create the native threadsafe\_function for test only for N-API greater than 3. (NickNaso) -* [[`37b6c185ad`](https://github.com/nodejs/node-addon-api/commit/37b6c185ad)] - Fix compilation breakage on 1.7.0 (NickNaso) - -## 2019-07-23 Version 1.7.0, @NickNaso - -### Notable changes: - -#### API - -- Added `Napi::ThreadSafeFunction` api. -- Added `Napi::AsyncWorker::GetResult()` method to `Napi::AsyncWorker`. -- Added `Napi::AsyncWorker::Destroy()()` method to `Napi::AsyncWorker`. -- Use full namespace on macros that create the errors. - -#### Documentation - -- Added documentation about contribution philosophy. -- Added documentation for `Napi::ThreadSafeFunction`. -- Some minor corrections all over the documentation. - -#### TEST - -- Added test case for bool operator. -- Fixed test case for `Napi::ObjectWrap`. - -### Commmits - -* [[`717c9ab163`](https://github.com/nodejs/node-addon-api/commit/717c9ab163)] - **AsyncWorker**: add GetResult() method (Kevin Eady) [#512](https://github.com/nodejs/node-addon-api/pull/512) -* [[`d9d991bbc9`](https://github.com/nodejs/node-addon-api/commit/d9d991bbc9)] - **doc**: add ThreadSafeFunction to main README (#513) (Kevin Eady) [#513](https://github.com/nodejs/node-addon-api/pull/513) -* [[`ac6000d0fd`](https://github.com/nodejs/node-addon-api/commit/ac6000d0fd)] - **doc**: fix minor typo (Yohei Kishimoto) [#510](https://github.com/nodejs/node-addon-api/pull/510) -* [[`e9fa1eaa86`](https://github.com/nodejs/node-addon-api/commit/e9fa1eaa86)] - **doc**: document ThreadSafeFunction (#494) (Kevin Eady) [#494](https://github.com/nodejs/node-addon-api/pull/494) -* [[`cab3b1e2a2`](https://github.com/nodejs/node-addon-api/commit/cab3b1e2a2)] - **doc**: ClassPropertyDescriptor example (Ross Weir) [#507](https://github.com/nodejs/node-addon-api/pull/507) -* [[`c32d7dbdcf`](https://github.com/nodejs/node-addon-api/commit/c32d7dbdcf)] - **macros**: create errors fully namespaced (Gabriel Schulhof) [#506](https://github.com/nodejs/node-addon-api/pull/506) -* [[`0a90df2fcb`](https://github.com/nodejs/node-addon-api/commit/0a90df2fcb)] - Implement ThreadSafeFunction class (Jinho Bang) -* [[`1fb540eeb5`](https://github.com/nodejs/node-addon-api/commit/1fb540eeb5)] - Use curly brackets to include node\_api.h (NickNaso) [#493](https://github.com/nodejs/node-addon-api/pull/493) -* [[`b2b08122ea`](https://github.com/nodejs/node-addon-api/commit/b2b08122ea)] - **AsyncWorker**: make callback optional (Kevin Eady) [#489](https://github.com/nodejs/node-addon-api/pull/489) -* [[`a0cac77c82`](https://github.com/nodejs/node-addon-api/commit/a0cac77c82)] - Added test for bool operator (NickNaso) [#490](https://github.com/nodejs/node-addon-api/pull/490) -* [[`ab7d8fcc48`](https://github.com/nodejs/node-addon-api/commit/ab7d8fcc48)] - **src**: fix objectwrap test case (Michael Dawson) [#495](https://github.com/nodejs/node-addon-api/pull/495) -* [[`3b6b9eb88a`](https://github.com/nodejs/node-addon-api/commit/3b6b9eb88a)] - **AsyncWorker**: introduce Destroy() method (Gabriel Schulhof) [#488](https://github.com/nodejs/node-addon-api/pull/488) -* [[`f633fbd95d`](https://github.com/nodejs/node-addon-api/commit/f633fbd95d)] - string.md: Document existing New(env, value, length) APIs (Tux3) [#486](https://github.com/nodejs/node-addon-api/pull/486) -* [[`aaea55eda9`](https://github.com/nodejs/node-addon-api/commit/aaea55eda9)] - Little fix on code example (Nicola Del Gobbo) [#470](https://github.com/nodejs/node-addon-api/pull/470) -* [[`e1cf9a35a1`](https://github.com/nodejs/node-addon-api/commit/e1cf9a35a1)] - Use `Value::IsEmpty` to check for empty value (NickNaso) [#478](https://github.com/nodejs/node-addon-api/pull/478) -* [[`3ad5dfc7d9`](https://github.com/nodejs/node-addon-api/commit/3ad5dfc7d9)] - Fix link (Alba Mendez) [#481](https://github.com/nodejs/node-addon-api/pull/481) -* [[`a3b4d99c45`](https://github.com/nodejs/node-addon-api/commit/a3b4d99c45)] - **doc**: Add contribution philosophy doc (Hitesh Kanwathirtha) -* [[`36863f087b`](https://github.com/nodejs/node-addon-api/commit/36863f087b)] - **doc**: refer to TypedArray and ArrayBuffer from Array (Gabriel "_|Nix|_" Schulhof) [#465](https://github.com/nodejs/node-addon-api/pull/465) - -## 2019-04-03 Version 1.6.3, @NickNaso - -### Notable changes: - -#### API - -- Added `SuppressDestruct` method to `Napi::AsyncWorker`. -- Added new build targets for debug. -- Exposed macros that throw errors. -- Fixed memory leaks caused by callback data when a napi error occurs. -- Fixed missing `void *data` usage in `Napi::PropertyDescriptors`. - -#### Documentation - -- Some minor corrections all over the documentation. - -### Commmits - -* [[`83b41c2fe4`](https://github.com/nodejs/node-addon-api/commit/83b41c2fe4)] - Document adding -fvisibility=hidden flag for macOS users (Nicola Del Gobbo) [#460](https://github.com/nodejs/node-addon-api/pull/460) -* [[`1ed7ad8769`](https://github.com/nodejs/node-addon-api/commit/1ed7ad8769)] - **doc**: correct return type of Int32Value to int32\_t (Bill Gallafent) [#459](https://github.com/nodejs/node-addon-api/pull/459) -* [[`b0f6b601aa`](https://github.com/nodejs/node-addon-api/commit/b0f6b601aa)] - **src**: add AsyncWorker destruction suppression (Gabriel Schulhof) [#407](https://github.com/nodejs/node-addon-api/pull/407) -* [[`72b1975cff`](https://github.com/nodejs/node-addon-api/commit/72b1975cff)] - **doc**: fix links to the Property Descriptor docs (Ryuichi Okumura) [#458](https://github.com/nodejs/node-addon-api/pull/458) -* [[`fcfc612728`](https://github.com/nodejs/node-addon-api/commit/fcfc612728)] - **build**: new build targets for debug purposes (Jinho Bang) [#186](https://github.com/nodejs/node-addon-api/pull/186) -* [[`c629553cd7`](https://github.com/nodejs/node-addon-api/commit/c629553cd7)] - **doc**: minor doc corrections and clarifications (Bruce A. MacNaughton) [#426](https://github.com/nodejs/node-addon-api/pull/426) -* [[`7b87e0b999`](https://github.com/nodejs/node-addon-api/commit/7b87e0b999)] - **doc**: update number.md (Bernardo Heynemann) [#436](https://github.com/nodejs/node-addon-api/pull/436) -* [[`fcf173d2a1`](https://github.com/nodejs/node-addon-api/commit/fcf173d2a1)] - **src**: expose macros that throw errors (Gabriel Schulhof) [#448](https://github.com/nodejs/node-addon-api/pull/448) -* [[`b409a2f987`](https://github.com/nodejs/node-addon-api/commit/b409a2f987)] - **package**: add npm search keywords (Sam Roberts) [#452](https://github.com/nodejs/node-addon-api/pull/452) -* [[`0bc7987806`](https://github.com/nodejs/node-addon-api/commit/0bc7987806)] - **doc**: fix references to Weak and Persistent (Jake Barnes) [#428](https://github.com/nodejs/node-addon-api/pull/428) -* [[`ad6f569f85`](https://github.com/nodejs/node-addon-api/commit/ad6f569f85)] - **doc**: dix typo (Abhishek Kumar Singh) [#435](https://github.com/nodejs/node-addon-api/pull/435) -* [[`28df833a49`](https://github.com/nodejs/node-addon-api/commit/28df833a49)] - Merge pull request #441 from jschlight/master (Jim Schlight) -* [[`4921e74d83`](https://github.com/nodejs/node-addon-api/commit/4921e74d83)] - Rearranges names to be alphabetical (Jim Schlight) -* [[`48220335b0`](https://github.com/nodejs/node-addon-api/commit/48220335b0)] - Membership review update (Jim Schlight) -* [[`44f0695533`](https://github.com/nodejs/node-addon-api/commit/44f0695533)] - Merge pull request #394 from NickNaso/create\_release (Nicola DelGobbo) -* [[`fa49d68416`](https://github.com/nodejs/node-addon-api/commit/fa49d68416)] - **doc**: fix some `Finalizer` signatures (Philipp Renoth) [#414](https://github.com/nodejs/node-addon-api/pull/414) -* [[`020ac4a628`](https://github.com/nodejs/node-addon-api/commit/020ac4a628)] - **src**: make `Object::GetPropertyNames()` const (Philipp Renoth)[#415](https://github.com/nodejs/node-addon-api/pull/415) -* [[`91eaa6f4cb`](https://github.com/nodejs/node-addon-api/commit/91eaa6f4cb)] - **src**: fix callbackData leaks on error napi status (Philipp Renoth) [#417](https://github.com/nodejs/node-addon-api/pull/417) -* [[`0b40275752`](https://github.com/nodejs/node-addon-api/commit/0b40275752)] - **src**: fix noexcept control flow issues (Philipp Renoth) [#420](https://github.com/nodejs/node-addon-api/pull/420) -* [[`c1ff2936f9`](https://github.com/nodejs/node-addon-api/commit/c1ff2936f9)] - **src**: fix missing void\*data usage in PropertyDescriptors (Luciano Martorella) [#374](https://github.com/nodejs/node-addon-api/pull/374) - -## 2018-11-29 Version 1.6.2, @NickNaso - -### Notable changes: - -#### API - -- Fixed selection logic for version 6.x. - -### Commmits - -* [[`07a0fc4e95`](https://github.com/nodejs/node-addon-api/commit/07a0fc4e95)] - **src**: fix selection logic for 6.x (Michael Dawson) [#402](https://github.com/nodejs/node-addon-api/pull/402) - -## 2018-11-14 Version 1.6.1, @NickNaso - -### Notable changes: - -#### Documentation - -- Updated links for examples to point to node-addon-examples repo. -- Fixed typos on some parts of documentation. - -#### API - -- Removed unused member on `Napi::CallbackScope`. -- Enabled `Napi::CallbackScope` only with N-API v3. - -### Commmits - -* [[`e7cd292a74`](https://github.com/nodejs/node-addon-api/commit/e7cd292a74)] - **src**: remove unused CallbackScope member (Gabriel Schulhof) [#391](https://github.com/nodejs/node-addon-api/pull/391) -* [[`d47399fe25`](https://github.com/nodejs/node-addon-api/commit/d47399fe25)] - **src**: guard CallbackScope with N-API v3 (Michael Dawson) [#395](https://github.com/nodejs/node-addon-api/pull/395) -* [[`29a0262ab9`](https://github.com/nodejs/node-addon-api/commit/29a0262ab9)] - **doc**: fix typo (Dongjin Na) [#385](https://github.com/nodejs/node-addon-api/pull/385) -* [[`b6dc15b88d`](https://github.com/nodejs/node-addon-api/commit/b6dc15b88d)] - **doc**: make links point to node-addon-examples repo (Nicola Del Gobbo) [#389](https://github.com/nodejs/node-addon-api/pull/389) - -## 2018-11-02 Version 1.6.0, @NickNaso - -### Notable changes: - -#### Documentation - -- Improved documentation about ABI stability. - -#### API - -- Add `Napi::CallbackScope` class that help to have the equivalent of the scope -associated with a callback in place when making certain N-API calls - -#### TEST - -- Added tests for `Napi::Array` class. -- Added tests for `Napi::ArrayBuffer` class. - -### Commmits - -* [[`8ce605c657`](https://github.com/nodejs/node-addon-api/commit/8ce605c657)] - **build**: avoid using package-lock.json (Jaeseok Yoon) [#359](https://github.com/nodejs/node-addon-api/pull/359) -* [[`fa3a6150b3`](https://github.com/nodejs/node-addon-api/commit/fa3a6150b3)] - **src**: use MakeCallback() -\> Call() in AsyncWorker (Jinho Bang) [#361](https://github.com/nodejs/node-addon-api/pull/361) -* [[`2342415463`](https://github.com/nodejs/node-addon-api/commit/2342415463)] - **test**: create test objects in the stack instead of the heap (Dongjin Na) [#371](https://github.com/nodejs/node-addon-api/pull/371) -* [[`67b7db0a6f`](https://github.com/nodejs/node-addon-api/commit/67b7db0a6f)] - **test**: write tests for Array class (Jaeseok Yoon) [#363](https://github.com/nodejs/node-addon-api/pull/363) -* [[`729f6dc4ee`](https://github.com/nodejs/node-addon-api/commit/729f6dc4ee)] - **test**: add arraybuffer tests (Dongjin Na) [#369](https://github.com/nodejs/node-addon-api/pull/369) -* [[`405f3e5b5b`](https://github.com/nodejs/node-addon-api/commit/405f3e5b5b)] - **src**: implement CallbackScope class (Jinho Bang) [#362](https://github.com/nodejs/node-addon-api/pull/362) -* [[`015d95312f`](https://github.com/nodejs/node-addon-api/commit/015d95312f)] - **doc**: fix Napi::Reference link (Gentilhomme) [#365](https://github.com/nodejs/node-addon-api/pull/365) -* [[`fd65078e3c`](https://github.com/nodejs/node-addon-api/commit/fd65078e3c)] - README.md: link to new ABI stability guide (Gabriel Schulhof) [#367](https://github.com/nodejs/node-addon-api/pull/367) -* [[`ffebf9ba9a`](https://github.com/nodejs/node-addon-api/commit/ffebf9ba9a)] - Updates for release 1.5.0 (NickNaso) - -## 2018-10-03 Version 1.5.0, @NickNaso - -### Notable changes: - -#### Documentation - -- Completed the documentation to cover all the API surface. -- Numerous fixes to make documentation more consistent in all of its parts. - -#### API - -- Add `Napi::AsyncContext` class to handle asynchronous operation. -- Add `Napi::BigInt` class to work with BigInt type. -- Add `Napi::VersionManagement` class to retrieve the versions of Node.js and N-API. -- Fix potential memory leaks. -- DataView feature is enabled by default -- Add descriptor for Symbols -- Add new methods on `Napi::FunctionReference`. -- Add the possibility to retrieve the environment on `Napi::Promise::Deferred` - -#### TOOL - -- Add tool to check if a native add-on is built using N-API - -#### TEST - -- Start to increase the test coverage -- Fix in the test suite to better handle the experimental features that are not -yet backported in the previous Node.js version. - -### Commits - -* [[`2009c019af`](https://github.com/nodejs/node-addon-api/commit/2009c019af)] - Merge pull request #292 from devsnek/feature/bigint (Gus Caplan) -* [[`e44aca985e`](https://github.com/nodejs/node-addon-api/commit/e44aca985e)] - add bigint class (Gus Caplan) -* [[`a3951ab973`](https://github.com/nodejs/node-addon-api/commit/a3951ab973)] - Add documentation for Env(). (Rolf Timmermans) [#318](https://github.com/nodejs/node-addon-api/pull/318) -* [[`a6f7a6ad51`](https://github.com/nodejs/node-addon-api/commit/a6f7a6ad51)] - Add Env() to Promise::Deferred. (Rolf Timmermans) -* [[`0097e96b92`](https://github.com/nodejs/node-addon-api/commit/0097e96b92)] - Fixed broken links for Symbol and String (NickNaso) -* [[`b0ecd38d76`](https://github.com/nodejs/node-addon-api/commit/b0ecd38d76)] - Fix Code of conduct link properly (#323) (Jake Yoon) [#323](https://github.com/nodejs/node-addon-api/pull/323) -* [[`223474900f`](https://github.com/nodejs/node-addon-api/commit/223474900f)] - **doc**: update Version management (Dongjin Na) [#360](https://github.com/nodejs/node-addon-api/pull/360) -* [[`4f76262a10`](https://github.com/nodejs/node-addon-api/commit/4f76262a10)] - **doc**: some fix on `Napi::Boolean` documentation (NickNaso) [#354](https://github.com/nodejs/node-addon-api/pull/354) -* [[`78374f72d2`](https://github.com/nodejs/node-addon-api/commit/78374f72d2)] - **doc**: number documentation (NickNaso) [#356](https://github.com/nodejs/node-addon-api/pull/356) -* [[`51ffe453f8`](https://github.com/nodejs/node-addon-api/commit/51ffe453f8)] - **doc**: doc cleanup (NickNaso) [#353](https://github.com/nodejs/node-addon-api/pull/353) -* [[`fc11c944b2`](https://github.com/nodejs/node-addon-api/commit/fc11c944b2)] - **doc**: major doc cleanup (NickNaso) [#335](https://github.com/nodejs/node-addon-api/pull/335) -* [[`100d0a7cb2`](https://github.com/nodejs/node-addon-api/commit/100d0a7cb2)] - **doc**: first pass on objectwrap documentation (NickNaso) [#321](https://github.com/nodejs/node-addon-api/pull/321) -* [[`c7d54180ff`](https://github.com/nodejs/node-addon-api/commit/c7d54180ff)] - **doc**: the Napi::ObjectWrap example does not compile (Arnaud Botella) [#339](https://github.com/nodejs/node-addon-api/pull/339) -* [[`7cdd78726a`](https://github.com/nodejs/node-addon-api/commit/7cdd78726a)] - **doc**: added cpp highlight for string.md (Jaeseok Yoon) [#329](https://github.com/nodejs/node-addon-api/pull/329) -* [[`8ed29f547c`](https://github.com/nodejs/node-addon-api/commit/8ed29f547c)] - **doc**: add blurb about ABI stability (Gabriel Schulhof) [#326](https://github.com/nodejs/node-addon-api/pull/326) -* [[`757eb1f5a3`](https://github.com/nodejs/node-addon-api/commit/757eb1f5a3)] - **doc**: add function and function reference doc (NickNaso) [#299](https://github.com/nodejs/node-addon-api/pull/299) -* [[`2885c18591`](https://github.com/nodejs/node-addon-api/commit/2885c18591)] - **doc**: Create changelog for release 1.4.0 (Nicola Del Gobbo) -* [[`917bd60baa`](https://github.com/nodejs/node-addon-api/commit/917bd60baa)] - **src**: remove TODOs by fixing memory leaks (Gabriel Schulhof) [#343](https://github.com/nodejs/node-addon-api/pull/343) -* [[`dfcb93945f`](https://github.com/nodejs/node-addon-api/commit/dfcb93945f)] - **src**: implement AsyncContext class (Jinho Bang) [#252](https://github.com/nodejs/node-addon-api/pull/252) -* [[`211ed38d0d`](https://github.com/nodejs/node-addon-api/commit/211ed38d0d)] - **src**: make 'nothing' target a static library (Gabriel Schulhof) [#348](https://github.com/nodejs/node-addon-api/pull/348) -* [[`97c4ab5cf2`](https://github.com/nodejs/node-addon-api/commit/97c4ab5cf2)] - **src**: add Call and MakeCallback that accept cargs (NickNaso) [#344](https://github.com/nodejs/node-addon-api/pull/344) -* [[`b6e2d92c09`](https://github.com/nodejs/node-addon-api/commit/b6e2d92c09)] - **src**: enable DataView feature by default (Jinho) [#331](https://github.com/nodejs/node-addon-api/pull/331) -* [[`0a00e7c97b`](https://github.com/nodejs/node-addon-api/commit/0a00e7c97b)] - **src**: implement missing descriptor defs for symbols (Philipp Renoth) [#280](https://github.com/nodejs/node-addon-api/pull/280) -* [[`38e01b7e3b`](https://github.com/nodejs/node-addon-api/commit/38e01b7e3b)] - **src**: first pass on adding version management apis (NickNaso) [#325](https://github.com/nodejs/node-addon-api/pull/325) -* [[`79ee8381d2`](https://github.com/nodejs/node-addon-api/commit/79ee8381d2)] - **src**: fix compile failure in test (Michael Dawson) [#345](https://github.com/nodejs/node-addon-api/pull/345) -* [[`4d92a6066f`](https://github.com/nodejs/node-addon-api/commit/4d92a6066f)] - **src**: Add ObjectReference test case (Anisha Rohra) [#212](https://github.com/nodejs/node-addon-api/pull/212) -* [[`779560f397`](https://github.com/nodejs/node-addon-api/commit/779560f397)] - **test**: add operator overloading tests in Number (Your Name) [#355](https://github.com/nodejs/node-addon-api/pull/355) -* [[`73fed84ceb`](https://github.com/nodejs/node-addon-api/commit/73fed84ceb)] - **test**: add ability to control experimental tests (Michael Dawson) [#350](https://github.com/nodejs/node-addon-api/pull/350) -* [[`14c69abd46`](https://github.com/nodejs/node-addon-api/commit/14c69abd46)] - **test**: write tests for Boolean class (Jaeseok Yoon) [#328](https://github.com/nodejs/node-addon-api/pull/328) -* [[`2ad47a83b1`](https://github.com/nodejs/node-addon-api/commit/2ad47a83b1)] - **test**: explicitly cast to uint32\_t in test (Gabriel Schulhof) [#341](https://github.com/nodejs/node-addon-api/pull/341) -* [[`622ffaea76`](https://github.com/nodejs/node-addon-api/commit/622ffaea76)] - **test**: Tighten up compiler warnings (Mikhail Cheshkov) [#315](https://github.com/nodejs/node-addon-api/pull/315) -* [[`fd3c37b0f2`](https://github.com/nodejs/node-addon-api/commit/fd3c37b0f2)] - **tools**: add tool to check for N-API modules (Gabriel Schulhof) [#346](https://github.com/nodejs/node-addon-api/pull/346) - -## 2018-07-19 Version 1.4.0, @NickNaso - -### Notable changes: - -#### Documentation - -- Numerous additions to the documentation, filling out coverage - of API surface - -#### API - -- Add resource parameters to AsyncWorker constructor -- Add memory management feature - -### Commits - -* [[`7dc5ac8bc3`](https://github.com/nodejs/node-addon-api/commit/7dc5ac8bc3)] - **doc**: update metadata for release (Nicola Del Gobbo) -* [[`d68e86adb4`](https://github.com/nodejs/node-addon-api/commit/d68e86adb4)] - **doc**: Added documentation for PropertyDescriptor (Anisha Rohra) [#309](https://github.com/nodejs/node-addon-api/pull/309) -* [[`968a5f2000`](https://github.com/nodejs/node-addon-api/commit/968a5f2000)] - **doc**: Add documentation for ObjectReference.md (Anisha Rohra) [#307](https://github.com/nodejs/node-addon-api/pull/307) -* [[`908cdc314c`](https://github.com/nodejs/node-addon-api/commit/908cdc314c)] - **doc**: add `TypedArray` and `TypedArrayOf` (Kyle Farnung) [#305](https://github.com/nodejs/node-addon-api/pull/305) -* [[`2ff776ffe3`](https://github.com/nodejs/node-addon-api/commit/2ff776ffe3)] - backport node::Persistent (Gabriel Schulhof) [#300](https://github.com/nodejs/node-addon-api/pull/300) -* [[`98161970c9`](https://github.com/nodejs/node-addon-api/commit/98161970c9)] - Backport perf, crash and exception handling fixes (Gabriel Schulhof) [#295](https://github.com/nodejs/node-addon-api/pull/295) -* [[`dd1191e086`](https://github.com/nodejs/node-addon-api/commit/dd1191e086)] - **test**: fix asyncworker test so it runs on 6.x (Michael Dawson) [#298](https://github.com/nodejs/node-addon-api/pull/298) -* [[`11697fcecd`](https://github.com/nodejs/node-addon-api/commit/11697fcecd)] - **doc**: ArrayBuffer and Buffer documentation (Kyle Farnung) [#256](https://github.com/nodejs/node-addon-api/pull/256) -* [[`605aa2babf`](https://github.com/nodejs/node-addon-api/commit/605aa2babf)] - Add memory management feature (NickNaso) [#286](https://github.com/nodejs/node-addon-api/pull/286) -* [[`86be13a611`](https://github.com/nodejs/node-addon-api/commit/86be13a611)] - **doc**: Fix HandleScope docs (Ben Berman) [#287](https://github.com/nodejs/node-addon-api/pull/287) -* [[`90f92c4dc0`](https://github.com/nodejs/node-addon-api/commit/90f92c4dc0)] - **doc**: Update broken links in README.md (Hitesh Kanwathirtha) [#290](https://github.com/nodejs/node-addon-api/pull/290) -* [[`c2a620dc11`](https://github.com/nodejs/node-addon-api/commit/c2a620dc11)] - **doc**: Clarify positioning versus N-API (Michael Dawson) [#288](https://github.com/nodejs/node-addon-api/pull/288) -* [[`6cff890ee5`](https://github.com/nodejs/node-addon-api/commit/6cff890ee5)] - **doc**: Fix typo in docs (Ben Berman) [#284](https://github.com/nodejs/node-addon-api/pull/284) -* [[`7394bfd154`](https://github.com/nodejs/node-addon-api/commit/7394bfd154)] - **doc**: Fix typo in docs (Ben Berman) [#285](https://github.com/nodejs/node-addon-api/pull/285) -* [[`12b2cdeed3`](https://github.com/nodejs/node-addon-api/commit/12b2cdeed3)] - fix test files (Kyle Farnung) [#257](https://github.com/nodejs/node-addon-api/pull/257) -* [[`9ab6607242`](https://github.com/nodejs/node-addon-api/commit/9ab6607242)] - **doc**: Update Doc Version Number (joshgarde) [#277](https://github.com/nodejs/node-addon-api/pull/277) -* [[`e029a076c6`](https://github.com/nodejs/node-addon-api/commit/e029a076c6)] - **doc**: First pass at basic Node Addon API docs (Hitesh Kanwathirtha) [#268](https://github.com/nodejs/node-addon-api/pull/268) -* [[`74ff79717e`](https://github.com/nodejs/node-addon-api/commit/74ff79717e)] - **doc**: fix link to async\_worker.md (Michael Dawson) -* [[`5a63f45eda`](https://github.com/nodejs/node-addon-api/commit/5a63f45eda)] - **doc**: First step of error and async doc (NickNaso) [#272](https://github.com/nodejs/node-addon-api/pull/272) -* [[`9d38f61afb`](https://github.com/nodejs/node-addon-api/commit/9d38f61afb)] - **doc**: New Promise and Reference docs (Jim Schlight) [#243](https://github.com/nodejs/node-addon-api/pull/243) -* [[`43ff9fa836`](https://github.com/nodejs/node-addon-api/commit/43ff9fa836)] - **doc**: Updated Object documentation (Anisha Rohra) [#254](https://github.com/nodejs/node-addon-api/pull/254) -* [[`b197f7cc8b`](https://github.com/nodejs/node-addon-api/commit/b197f7cc8b)] - **doc**: minor typos (Nick Soggin) [#248](https://github.com/nodejs/node-addon-api/pull/248) -* [[`4b8918b352`](https://github.com/nodejs/node-addon-api/commit/4b8918b352)] - Add resource parameters to AsyncWorker constructor (Jinho Bang) [#253](https://github.com/nodejs/node-addon-api/pull/253) -* [[`1ecf7c19b6`](https://github.com/nodejs/node-addon-api/commit/1ecf7c19b6)] - **doc**: fix wrong link in readme (miloas) [#255](https://github.com/nodejs/node-addon-api/pull/255) -* [[`a750ed1932`](https://github.com/nodejs/node-addon-api/commit/a750ed1932)] - **release**: updates to metadata for next release (Michael Dawson) - -## 2018-05-08 Version 1.3.0, @mhdawson - -### Notable changes: - -#### Documentation -- Added documentation for Scopes -- Added documentation for migration from NAN -- Update documentation to better explain the use of NODE_ADDON_API - -#### API -- Implement data manipulation methods for dataview -- Use built-in N-API on Node.js >= 6.14.2 -- Value - - Added IsExternal() - - IsObject() allow functions -- String - - Fixed initialization of std::string to nullptr - -#### Tests -- Fix test failures on linuxOne and AIX -- Added basic tests for Scopes -- Fix MSVC warning C4244 in tests - -### Commits - -* [386c2aeb74] - test: remove dep on later C++ feature (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/267 -* [10697734da] - Use built-in N-API on Node.js >= 6.14.2 (Gabriel Schulhof) -* [75086da273] - test: add basic tests and doc for scopes (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/250 -* [341dbd25d5] - doc: update blurb explaining NODE_ADDON_API (Gabriel Schulhof) https://github.com/nodejs/node-addon-api/pull/251 -* [cf6c93e4ee] - don't try to escape null (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/245 -* [15e4b35fc2] - test: fix MSVC warning C4244 in tests (Kyle Farnung) https://github.com/nodejs/node-addon-api/pull/236 -* [7f3ca03b8e] - Create a doc for migration (Sampson Gao) https://github.com/nodejs/node-addon-api/pull/118 -* [0a2177debe] - Fix test failures on linuxOne and AIX (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/232 -* [d567f4b6b5] - Added Napi::Value::IsExternal() (Eric Bickle) https://github.com/nodejs/node-addon-api/pull/227 -* [1b0f0e004a] - Update node-gyp.md (Michele Campus) https://github.com/nodejs/node-addon-api/pull/226 -* [faf19c4f7a] - Fixed initialization of std::string to nullptr (Eric Bickle) https://github.com/nodejs/node-addon-api/pull/228 -* [9c4d321b57] - Implement data manipulation methods for dataview (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/218 -* [5a39fdca6f] - n-api: throw RangeError napi_create_typedarray() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/216 -* [1376377202] - Make IsObject() allow functions (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/217 -* [673b59d319] - src: Initial implementation of DataView class (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/205 -* [0a899bf1c5] - doc: update indication of latest version (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/211 -* [17c74e5a5e] - n-api: RangeError in napi_create_dataview() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/214 -* [4058a29989] - n-api: fix memory leak in napi_async_destroy() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/213 - - diff --git a/node_modules/node-addon-api/CODE_OF_CONDUCT.md b/node_modules/node-addon-api/CODE_OF_CONDUCT.md deleted file mode 100644 index eb07a97..0000000 --- a/node_modules/node-addon-api/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -# Code of Conduct - -The Node.js Code of Conduct, which applies to this project, can be found at -https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md. diff --git a/node_modules/node-addon-api/CONTRIBUTING.md b/node_modules/node-addon-api/CONTRIBUTING.md deleted file mode 100644 index 0d9fdf9..0000000 --- a/node_modules/node-addon-api/CONTRIBUTING.md +++ /dev/null @@ -1,66 +0,0 @@ -# **node-addon-api** Contribution Philosophy - -The **node-addon-api** team loves contributions. There are many ways in which you can -contribute to **node-addon-api**: -- Source code fixes -- Additional tests -- Documentation improvements -- Joining the N-API working group and participating in meetings - -## Source changes - -**node-addon-api** is meant to be a thin convenience wrapper around N-API. With this -in mind, contributions of any new APIs that wrap around a core N-API API will -be considered for merge. However, changes that wrap existing **node-addon-api** -APIs are encouraged to instead be provided as an ecosystem module. The -**node-addon-api** team is happy to link to a curated set of modules that build on -top of **node-addon-api** if they have broad usefulness to the community and promote -a recommended idiom or pattern. - -### Rationale - -The N-API team considered a couple different approaches with regards to changes -extending **node-addon-api** -- Larger core module - Incorporate these helpers and patterns into **node-addon-api** -- Extras package - Create a new package (strawman name '**node-addon-api**-extras') -that contain utility classes and methods that help promote good patterns and -idioms while writing native addons with **node-addon-api**. -- Ecosystem - Encourage creation of a module ecosystem around **node-addon-api** -where folks can build on top of it. - -#### Larger Core -This is probably our simplest option in terms of immediate action needed. It -would involve landing any open PRs against **node-addon-api**, and continuing to -encourage folks to make PRs for utility helpers against the same repository. - -The downside of the approach is the following: -- Less coherency for our API set -- More maintenance burden on the N-API WG core team. - -#### Extras Package -This involves us spinning up a new package which contains the utility classes -and methods. This has the benefit of having a separate module where helpers -which make it easier to implement certain patterns and idioms for native addons -easier. - -The downside of this approach is the following: -- Potential for confusion - we'll need to provide clear documentation to help the -community understand where a particular contribution should be directed to (what -belongs in **node-addon-api** vs **node-addon-api-extras**) -- Need to define the level of support/API guarantees -- Unclear if the maintenance burden on the N-API WG is reduced or not - -#### Ecosystem -This doesn't require a ton of up-front work from the N-API WG. Instead of -accepting utility PRs into **node-addon-api** or creating and maintaining a new -module, the WG will encourage the creation of an ecosystem of modules that -build on top of **node-addon-api**, and provide some level of advertising for these -modules (listing them out on the repository/wiki, using them in workshops/tutorials -etc). - -The downside of this approach is the following: -- Potential for lack of visibility - evangelism and education is hard, and module -authors might not find right patterns and instead implement things themselves -- There might be greater friction for the N-API WG in evolving APIs since the -ecosystem would have taken dependencies on the API shape of **node-addon-api** - diff --git a/node_modules/node-addon-api/LICENSE.md b/node_modules/node-addon-api/LICENSE.md deleted file mode 100644 index e2fad66..0000000 --- a/node_modules/node-addon-api/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2017 Node.js API collaborators ------------------------------------ - -*Node.js API collaborators listed at <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.
\ No newline at end of file diff --git a/node_modules/node-addon-api/README.md b/node_modules/node-addon-api/README.md deleted file mode 100644 index 2558c7e..0000000 --- a/node_modules/node-addon-api/README.md +++ /dev/null @@ -1,203 +0,0 @@ -# **node-addon-api module** -This module contains **header-only C++ wrapper classes** which simplify -the use of the C based [N-API](https://nodejs.org/dist/latest/docs/api/n-api.html) -provided by Node.js when using C++. It provides a C++ object model -and exception handling semantics with low overhead. - -N-API is an ABI stable C interface provided by Node.js for building native -addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore) -and is maintained as part of Node.js itself. It is intended to insulate -native addons from changes in the underlying JavaScript engine and allow -modules compiled for one version to run on later versions of Node.js without -recompilation. - -The `node-addon-api` module, which is not part of Node.js, preserves the benefits -of the N-API as it consists only of inline code that depends only on the stable API -provided by N-API. As such, modules built against one version of Node.js -using node-addon-api should run without having to be rebuilt with newer versions -of Node.js. - -It is important to remember that *other* Node.js interfaces such as -`libuv` (included in a project via `#include <uv.h>`) are not ABI-stable across -Node.js major versions. Thus, an addon must use N-API and/or `node-addon-api` -exclusively and build against a version of Node.js that includes an -implementation of N-API (meaning a version of Node.js newer than 6.14.2) in -order to benefit from ABI stability across Node.js major versions. Node.js -provides an [ABI stability guide][] containing a detailed explanation of ABI -stability in general, and the N-API ABI stability guarantee in particular. - -As new APIs are added to N-API, node-addon-api must be updated to provide -wrappers for those new APIs. For this reason node-addon-api provides -methods that allow callers to obtain the underlying N-API handles so -direct calls to N-API and the use of the objects/methods provided by -node-addon-api can be used together. For example, in order to be able -to use an API for which the node-addon-api does not yet provide a wrapper. - -APIs exposed by node-addon-api are generally used to create and -manipulate JavaScript values. Concepts and operations generally map -to ideas specified in the **ECMA262 Language Specification**. - -- **[Setup](#setup)** -- **[API Documentation](#api)** -- **[Examples](#examples)** -- **[Tests](#tests)** -- **[More resource and info about native Addons](#resources)** -- **[Code of Conduct](CODE_OF_CONDUCT.md)** -- **[Contributors](#contributors)** -- **[License](#license)** - -## **Current version: 2.0.0** - -(See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) - -[](https://nodei.co/npm/node-addon-api/) [](https://nodei.co/npm/node-addon-api/) - -<a name="setup"></a> - -## Setup - - [Installation and usage](doc/setup.md) - - [node-gyp](doc/node-gyp.md) - - [cmake-js](doc/cmake-js.md) - - [Conversion tool](doc/conversion-tool.md) - - [Checker tool](doc/checker-tool.md) - - [Generator](doc/generator.md) - - [Prebuild tools](doc/prebuild_tools.md) - -<a name="api"></a> - -### **API Documentation** - -The following is the documentation for node-addon-api. - - - [Basic Types](doc/basic_types.md) - - [Array](doc/basic_types.md#array) - - [Symbol](doc/symbol.md) - - [String](doc/string.md) - - [Name](doc/basic_types.md#name) - - [Number](doc/number.md) - - [Date](doc/date.md) - - [BigInt](doc/bigint.md) - - [Boolean](doc/boolean.md) - - [Env](doc/env.md) - - [Value](doc/value.md) - - [CallbackInfo](doc/callbackinfo.md) - - [Reference](doc/reference.md) - - [External](doc/external.md) - - [Object](doc/object.md) - - [ObjectReference](doc/object_reference.md) - - [PropertyDescriptor](doc/property_descriptor.md) - - [Error Handling](doc/error_handling.md) - - [Error](doc/error.md) - - [TypeError](doc/type_error.md) - - [RangeError](doc/range_error.md) - - [Object Lifetime Management](doc/object_lifetime_management.md) - - [HandleScope](doc/handle_scope.md) - - [EscapableHandleScope](doc/escapable_handle_scope.md) - - [Working with JavaScript Values](doc/working_with_javascript_values.md) - - [Function](doc/function.md) - - [FunctionReference](doc/function_reference.md) - - [ObjectWrap](doc/object_wrap.md) - - [ClassPropertyDescriptor](doc/class_property_descriptor.md) - - [Buffer](doc/buffer.md) - - [ArrayBuffer](doc/array_buffer.md) - - [TypedArray](doc/typed_array.md) - - [TypedArrayOf](doc/typed_array_of.md) - - [DataView](doc/dataview.md) - - [Memory Management](doc/memory_management.md) - - [Async Operations](doc/async_operations.md) - - [AsyncWorker](doc/async_worker.md) - - [AsyncContext](doc/async_context.md) - - [AsyncProgressWorker](doc/async_progress_worker.md) - - [Thread-safe Functions](doc/threadsafe_function.md) - - [Promises](doc/promises.md) - - [Version management](doc/version_management.md) - -<a name="examples"></a> - -### **Examples** - -Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** - -- **[Hello World](https://github.com/nodejs/node-addon-examples/tree/master/1_hello_world/node-addon-api)** -- **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/master/2_function_arguments/node-addon-api)** -- **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/master/3_callbacks/node-addon-api)** -- **[Object factory](https://github.com/nodejs/node-addon-examples/tree/master/4_object_factory/node-addon-api)** -- **[Function factory](https://github.com/nodejs/node-addon-examples/tree/master/5_function_factory/node-addon-api)** -- **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/master/6_object_wrap/node-addon-api)** -- **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/master/7_factory_wrap/node-addon-api)** -- **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/master/8_passing_wrapped/node-addon-api)** - -<a name="tests"></a> - -### **Tests** - -To run the **node-addon-api** tests do: - -``` -npm install -npm test -``` - -To avoid testing the deprecated portions of the API run -``` -npm install -npm test --disable-deprecated -``` - -### **Debug** - -To run the **node-addon-api** tests with `--debug` option: - -``` -npm run-script dev -``` - -If you want faster build, you might use the following option: - -``` -npm run-script dev:incremental -``` - -Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/master/test)** - -<a name="resources"></a> - -## **Contributing** - -We love contributions from the community to **node-addon-api**. -See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module. - -### **More resource and info about native Addons** -- **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** -- **[N-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** -- **[N-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** - -<a name="contributors"></a> - -## WG Members / Collaborators - -### Active -| Name | GitHub Link | -| ------------------- | ----------------------------------------------------- | -| Anna Henningsen | [addaleax](https://github.com/addaleax) | -| Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | -| Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | -| Jim Schlight | [jschlight](https://github.com/jschlight) | -| Michael Dawson | [mhdawson](https://github.com/mhdawson) | -| Kevin Eady | [KevinEady](https://github.com/KevinEady) -| Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | - -### Emeritus -| Name | GitHub Link | -| ------------------- | ----------------------------------------------------- | -| Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | -| Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | -| Jason Ginchereau | [jasongin](https://github.com/jasongin) | -| Sampson Gao | [sampsongao](https://github.com/sampsongao) | -| Taylor Woll | [boingoing](https://github.com/boingoing) | - -<a name="license"></a> - -Licensed under [MIT](./LICENSE.md) - -[ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ diff --git a/node_modules/node-addon-api/appveyor.yml b/node_modules/node-addon-api/appveyor.yml deleted file mode 100644 index 439b91d..0000000 --- a/node_modules/node-addon-api/appveyor.yml +++ /dev/null @@ -1,48 +0,0 @@ -environment: - # https://github.com/jasongin/nvs/blob/master/doc/CI.md - NVS_VERSION: 1.4.2 - fast_finish: true - matrix: - - NODEJS_VERSION: node/4 - - NODEJS_VERSION: node/6 - - NODEJS_VERSION: node/8 - - NODEJS_VERSION: node/9 - - NODEJS_VERSION: node/10 - - NODEJS_VERSION: chakracore/8 - - NODEJS_VERSION: chakracore/10 - - NODEJS_VERSION: nightly - - NODEJS_VERSION: chakracore-nightly - -matrix: - fast_finish: true - allow_failures: - - NODEJS_VERSION: nightly - - NODEJS_VERSION: chakracore-nightly - -platform: - - x86 - - x64 - -install: - # nvs - - git clone --branch v%NVS_VERSION% --depth 1 https://github.com/jasongin/nvs %LOCALAPPDATA%\nvs - - set PATH=%LOCALAPPDATA%\nvs;%PATH% - - nvs --version - # node.js - - nvs add %NODEJS_VERSION%/%PLATFORM% - - nvs use %NODEJS_VERSION%/%PLATFORM% - - node --version - - node -p process.arch - - npm --version - # app - - npm install - -test_script: - - npm test - -build: off - -version: "{build}" - -cache: - - node_modules diff --git a/node_modules/node-addon-api/doc/Doxyfile b/node_modules/node-addon-api/doc/Doxyfile deleted file mode 100644 index 995090d..0000000 --- a/node_modules/node-addon-api/doc/Doxyfile +++ /dev/null @@ -1,2450 +0,0 @@ -# Doxyfile 1.8.13 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a double hash (##) is considered a comment and is placed in -# front of the TAG it is preceding. -# -# All text after a single hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists, items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (\" \"). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all text -# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv -# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv -# for the list of possible encodings. -# The default value is: UTF-8. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by -# double-quotes, unless you are using Doxywizard) that should identify the -# project for which the documentation is generated. This name is used in the -# title of most generated pages and in a few other places. -# The default value is: My Project. - -PROJECT_NAME = N-API - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. This -# could be handy for archiving the generated documentation or if some version -# control system is used. - -PROJECT_NUMBER = 1.3.0 - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer a -# quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = "C++ wrapper classes for the ABI-stable C APIs for Node.js" - -# With the PROJECT_LOGO tag one can specify a logo or an icon that is included -# in the documentation. The maximum height of the logo should not exceed 55 -# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy -# the logo to the output directory. - -PROJECT_LOGO = - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path -# into which the generated documentation will be written. If a relative path is -# entered, it will be relative to the location where doxygen was started. If -# left blank the current directory will be used. - -OUTPUT_DIRECTORY = doc - -# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- -# directories (in 2 levels) under the output directory of each output format and -# will distribute the generated files over these directories. Enabling this -# option can be useful when feeding doxygen a huge amount of source files, where -# putting all generated files in the same directory would otherwise causes -# performance problems for the file system. -# The default value is: NO. - -CREATE_SUBDIRS = NO - -# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII -# characters to appear in the names of generated files. If set to NO, non-ASCII -# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode -# U+3044. -# The default value is: NO. - -ALLOW_UNICODE_NAMES = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, -# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), -# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, -# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), -# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, -# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, -# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, -# Ukrainian and Vietnamese. -# The default value is: English. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member -# descriptions after the members that are listed in the file and class -# documentation (similar to Javadoc). Set to NO to disable this. -# The default value is: YES. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief -# description of a member or function before the detailed description -# -# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. -# The default value is: YES. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator that is -# used to form the text in various listings. Each string in this list, if found -# as the leading text of the brief description, will be stripped from the text -# and the result, after processing the whole list, is used as the annotated -# text. Otherwise, the brief description is used as-is. If left blank, the -# following values are used ($name is automatically replaced with the name of -# the entity):The $name class, The $name widget, The $name file, is, provides, -# specifies, contains, represents, a, an and the. - -ABBREVIATE_BRIEF = "The $name class" \ - "The $name widget" \ - "The $name file" \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# doxygen will generate a detailed section even if there is only a brief -# description. -# The default value is: NO. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. -# The default value is: NO. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path -# before files name in the file list and in the header files. If set to NO the -# shortest path that makes the file name unique will be used -# The default value is: YES. - -FULL_PATH_NAMES = YES - -# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. -# Stripping is only done if one of the specified strings matches the left-hand -# part of the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the path to -# strip. -# -# Note that you can specify absolute paths here, but also relative paths, which -# will be relative from the directory where doxygen is started. -# This tag requires that the tag FULL_PATH_NAMES is set to YES. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the -# path mentioned in the documentation of a class, which tells the reader which -# header file to include in order to use a class. If left blank only the name of -# the header file containing the class definition is used. Otherwise one should -# specify the list of include paths that are normally passed to the compiler -# using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but -# less readable) file names. This can be useful is your file systems doesn't -# support long names like on DOS, Mac, or CD-ROM. -# The default value is: NO. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the -# first line (until the first dot) of a Javadoc-style comment as the brief -# description. If set to NO, the Javadoc-style will behave just like regular Qt- -# style comments (thus requiring an explicit @brief command for a brief -# description.) -# The default value is: NO. - -JAVADOC_AUTOBRIEF = YES - -# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first -# line (until the first dot) of a Qt-style comment as the brief description. If -# set to NO, the Qt-style will behave just like regular Qt-style comments (thus -# requiring an explicit \brief command for a brief description.) -# The default value is: NO. - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a -# multi-line C++ special comment block (i.e. a block of //! or /// comments) as -# a brief description. This used to be the default behavior. The new default is -# to treat a multi-line C++ comment block as a detailed description. Set this -# tag to YES if you prefer the old behavior instead. -# -# Note that setting this tag to YES also means that rational rose comments are -# not recognized any more. -# The default value is: NO. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the -# documentation from any documented member that it re-implements. -# The default value is: YES. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new -# page for each member. If set to NO, the documentation of a member will be part -# of the file/class/namespace that contains it. -# The default value is: NO. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen -# uses this value to replace tabs by spaces in code fragments. -# Minimum value: 1, maximum value: 16, default value: 4. - -TAB_SIZE = 4 - -# This tag can be used to specify a number of aliases that act as commands in -# the documentation. An alias has the form: -# name=value -# For example adding -# "sideeffect=@par Side Effects:\n" -# will allow you to put the command \sideeffect (or @sideeffect) in the -# documentation, which will result in a user-defined paragraph with heading -# "Side Effects:". You can put \n's in the value part of an alias to insert -# newlines. - -ALIASES = - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding "class=itcl::class" -# will allow you to use the command class in the itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources -# only. Doxygen will then generate output that is more tailored for C. For -# instance, some of the names that are used will be different. The list of all -# members will be omitted, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or -# Python sources only. Doxygen will then generate output that is more tailored -# for that language. For instance, namespaces will be presented as packages, -# qualified scopes will look different, etc. -# The default value is: NO. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources. Doxygen will then generate output that is tailored for Fortran. -# The default value is: NO. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for VHDL. -# The default value is: NO. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given -# extension. Doxygen has a built-in mapping, but you can override or extend it -# using this tag. The format is ext=language, where ext is a file extension, and -# language is one of the parsers supported by doxygen: IDL, Java, Javascript, -# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: -# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: -# Fortran. In the later case the parser tries to guess whether the code is fixed -# or free formatted code, this is the default for Fortran type files), VHDL. For -# instance to make doxygen treat .inc files as Fortran files (default is PHP), -# and .f files as C (default is Fortran), use: inc=Fortran f=C. -# -# Note: For files without extension you can use no_extension as a placeholder. -# -# Note that for custom extensions you also need to set FILE_PATTERNS otherwise -# the files are not read by doxygen. - -EXTENSION_MAPPING = - -# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments -# according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you can -# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in -# case of backward compatibilities issues. -# The default value is: YES. - -MARKDOWN_SUPPORT = YES - -# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up -# to that level are automatically included in the table of contents, even if -# they do not have an id attribute. -# Note: This feature currently applies only to Markdown headings. -# Minimum value: 0, maximum value: 99, default value: 0. -# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. - -TOC_INCLUDE_HEADINGS = 0 - -# When enabled doxygen tries to link words that correspond to documented -# classes, or namespaces to their corresponding documentation. Such a link can -# be prevented in individual cases by putting a % sign in front of the word or -# globally by setting AUTOLINK_SUPPORT to NO. -# The default value is: YES. - -AUTOLINK_SUPPORT = YES - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should set this -# tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); -# versus func(std::string) {}). This also make the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. -# The default value is: NO. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. -# The default value is: NO. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: -# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen -# will parse them like normal C++ but will assume all classes use public instead -# of private inheritance when no explicit protection keyword is present. -# The default value is: NO. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate -# getter and setter methods for a property. Setting this option to YES will make -# doxygen to replace the get and set methods by a property in the documentation. -# This will only work if the methods are indeed getting or setting a simple -# type. If this is not the case, or you want to show the methods anyway, you -# should set this option to NO. -# The default value is: YES. - -IDL_PROPERTY_SUPPORT = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. -# The default value is: NO. - -DISTRIBUTE_GROUP_DOC = NO - -# If one adds a struct or class to a group and this option is enabled, then also -# any nested class or struct is added to the same group. By default this option -# is disabled and one has to add nested compounds explicitly via \ingroup. -# The default value is: NO. - -GROUP_NESTED_COMPOUNDS = NO - -# Set the SUBGROUPING tag to YES to allow class member groups of the same type -# (for instance a group of public functions) to be put as a subgroup of that -# type (e.g. under the Public Functions section). Set it to NO to prevent -# subgrouping. Alternatively, this can be done per class using the -# \nosubgrouping command. -# The default value is: YES. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions -# are shown inside the group in which they are included (e.g. using \ingroup) -# instead of on a separate page (for HTML and Man pages) or section (for LaTeX -# and RTF). -# -# Note that this feature does not work in combination with -# SEPARATE_MEMBER_PAGES. -# The default value is: NO. - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions -# with only public data fields or simple typedef fields will be shown inline in -# the documentation of the scope in which they are defined (i.e. file, -# namespace, or group documentation), provided this scope is documented. If set -# to NO, structs, classes, and unions are shown on a separate page (for HTML and -# Man pages) or section (for LaTeX and RTF). -# The default value is: NO. - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or -# enum is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically be -# useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. -# The default value is: NO. - -TYPEDEF_HIDES_STRUCT = NO - -# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This -# cache is used to resolve symbols given their name and scope. Since this can be -# an expensive process and often the same symbol appears multiple times in the -# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small -# doxygen will become slower. If the cache is too large, memory is wasted. The -# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range -# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 -# symbols. At the end of a run doxygen will report the cache usage and suggest -# the optimal cache size from a speed point of view. -# Minimum value: 0, maximum value: 9, default value: 0. - -LOOKUP_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in -# documentation are documented, even if no documentation was available. Private -# class members and static file members will be hidden unless the -# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. -# Note: This will also disable the warnings about undocumented members that are -# normally produced when WARNINGS is set to YES. -# The default value is: NO. - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will -# be included in the documentation. -# The default value is: NO. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal -# scope will be included in the documentation. -# The default value is: NO. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be -# included in the documentation. -# The default value is: NO. - -EXTRACT_STATIC = NO - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined -# locally in source files will be included in the documentation. If set to NO, -# only classes defined in header files are included. Does not have any effect -# for Java sources. -# The default value is: YES. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. If set to YES, local methods, -# which are defined in the implementation section but not in the interface are -# included in the documentation. If set to NO, only methods in the interface are -# included. -# The default value is: NO. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base name of -# the file that contains the anonymous namespace. By default anonymous namespace -# are hidden. -# The default value is: NO. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all -# undocumented members inside documented classes or files. If set to NO these -# members will be included in the various overviews, but no documentation -# section is generated. This option has no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. If set -# to NO, these classes will be included in the various overviews. This option -# has no effect if EXTRACT_ALL is enabled. -# The default value is: NO. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend -# (class|struct|union) declarations. If set to NO, these declarations will be -# included in the documentation. -# The default value is: NO. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any -# documentation blocks found inside the body of a function. If set to NO, these -# blocks will be appended to the function's detailed documentation block. -# The default value is: NO. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation that is typed after a -# \internal command is included. If the tag is set to NO then the documentation -# will be excluded. Set it to YES to include the internal documentation. -# The default value is: NO. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file -# names in lower-case letters. If set to YES, upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. -# The default value is: system dependent. - -CASE_SENSE_NAMES = NO - -# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with -# their full class and namespace scopes in the documentation. If set to YES, the -# scope will be hidden. -# The default value is: NO. - -HIDE_SCOPE_NAMES = NO - -# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will -# append additional text to a page's title, such as Class Reference. If set to -# YES the compound reference will be hidden. -# The default value is: NO. - -HIDE_COMPOUND_REFERENCE= NO - -# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of -# the files that are included by a file in the documentation of that file. -# The default value is: YES. - -SHOW_INCLUDE_FILES = YES - -# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each -# grouped member an include statement to the documentation, telling the reader -# which file to include in order to use the member. -# The default value is: NO. - -SHOW_GROUPED_MEMB_INC = NO - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include -# files with double quotes in the documentation rather than with sharp brackets. -# The default value is: NO. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the -# documentation for inline members. -# The default value is: YES. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the -# (detailed) documentation of file and class members alphabetically by member -# name. If set to NO, the members will appear in declaration order. -# The default value is: YES. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief -# descriptions of file, namespace and class members alphabetically by member -# name. If set to NO, the members will appear in declaration order. Note that -# this will also influence the order of the classes in the class list. -# The default value is: NO. - -SORT_BRIEF_DOCS = NO - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the -# (brief and detailed) documentation of class members so that constructors and -# destructors are listed first. If set to NO the constructors will appear in the -# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. -# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief -# member documentation. -# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting -# detailed member documentation. -# The default value is: NO. - -SORT_MEMBERS_CTORS_1ST = NO - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy -# of group names into alphabetical order. If set to NO the group names will -# appear in their defined order. -# The default value is: NO. - -SORT_GROUP_NAMES = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by -# fully-qualified names, including namespaces. If set to NO, the class list will -# be sorted only by class name, not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the alphabetical -# list. -# The default value is: NO. - -SORT_BY_SCOPE_NAME = NO - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper -# type resolution of all parameters of a function it will reject a match between -# the prototype and the implementation of a member function even if there is -# only one candidate or it is obvious which candidate to choose by doing a -# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still -# accept a match between prototype and implementation in such cases. -# The default value is: NO. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo -# list. This list is created by putting \todo commands in the documentation. -# The default value is: YES. - -GENERATE_TODOLIST = YES - -# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test -# list. This list is created by putting \test commands in the documentation. -# The default value is: YES. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug -# list. This list is created by putting \bug commands in the documentation. -# The default value is: YES. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) -# the deprecated list. This list is created by putting \deprecated commands in -# the documentation. -# The default value is: YES. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional documentation -# sections, marked by \if <section_label> ... \endif and \cond <section_label> -# ... \endcond blocks. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the -# initial value of a variable or macro / define can have for it to appear in the -# documentation. If the initializer consists of more lines than specified here -# it will be hidden. Use a value of 0 to hide initializers completely. The -# appearance of the value of individual variables and macros / defines can be -# controlled using \showinitializer or \hideinitializer command in the -# documentation regardless of this setting. -# Minimum value: 0, maximum value: 10000, default value: 30. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at -# the bottom of the documentation of classes and structs. If set to YES, the -# list will mention the files that were used to generate the documentation. -# The default value is: YES. - -SHOW_USED_FILES = YES - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This -# will remove the Files entry from the Quick Index and from the Folder Tree View -# (if specified). -# The default value is: YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces -# page. This will remove the Namespaces entry from the Quick Index and from the -# Folder Tree View (if specified). -# The default value is: YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command command input-file, where command is the value of the -# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided -# by doxygen. Whatever the program writes to standard output is used as the file -# version. For an example see the documentation. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. To create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. You can -# optionally specify a file name after the option, if omitted DoxygenLayout.xml -# will be used as the name of the layout file. -# -# Note that if you run doxygen from a directory containing a file called -# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE -# tag is left empty. - -LAYOUT_FILE = - -# The CITE_BIB_FILES tag can be used to specify one or more bib files containing -# the reference definitions. This must be a list of .bib files. The .bib -# extension is automatically appended if omitted. This requires the bibtex tool -# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. -# For LaTeX the style of the bibliography can be controlled using -# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the -# search path. See also \cite for info how to create references. - -CITE_BIB_FILES = - -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated to -# standard output by doxygen. If QUIET is set to YES this implies that the -# messages are off. -# The default value is: NO. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES -# this implies that the warnings are on. -# -# Tip: Turn warnings on while writing the documentation. -# The default value is: YES. - -WARNINGS = YES - -# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate -# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag -# will automatically be disabled. -# The default value is: YES. - -WARN_IF_UNDOCUMENTED = YES - -# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some parameters -# in a documented function, or documenting parameters that don't exist or using -# markup commands wrongly. -# The default value is: YES. - -WARN_IF_DOC_ERROR = YES - -# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that -# are documented, but have no documentation for their parameters or return -# value. If set to NO, doxygen will only warn about wrong or incomplete -# parameter documentation, but not about the absence of documentation. -# The default value is: NO. - -WARN_NO_PARAMDOC = NO - -# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when -# a warning is encountered. -# The default value is: NO. - -WARN_AS_ERROR = NO - -# The WARN_FORMAT tag determines the format of the warning messages that doxygen -# can produce. The string should contain the $file, $line, and $text tags, which -# will be replaced by the file and line number from which the warning originated -# and the warning text. Optionally the format may contain $version, which will -# be replaced by the version of the file (if it could be obtained via -# FILE_VERSION_FILTER) -# The default value is: $file:$line: $text. - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning and error -# messages should be written. If left blank the output is written to standard -# error (stderr). - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag is used to specify the files and/or directories that contain -# documented source files. You may enter file names like myfile.cpp or -# directories like /usr/src/myproject. Separate the files or directories with -# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING -# Note: If this tag is empty the current directory is searched. - -INPUT = . - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses -# libiconv (or the iconv built into libc) for the transcoding. See the libiconv -# documentation (see: http://www.gnu.org/software/libiconv) for the list of -# possible encodings. -# The default value is: UTF-8. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and -# *.h) to filter out the source-files in the directories. -# -# Note that for custom extensions or not directly supported extensions you also -# need to set EXTENSION_MAPPING for the extension otherwise the files are not -# read by doxygen. -# -# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, -# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, -# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, -# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, -# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf. - -FILE_PATTERNS = napi.h \ - README.md - -# The RECURSIVE tag can be used to specify whether or not subdirectories should -# be searched for input files as well. -# The default value is: NO. - -RECURSIVE = NO - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. -# The default value is: NO. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories for example use the pattern */test/* - -EXCLUDE_PATTERNS = - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test -# -# Note that the wildcards are matched against the file with absolute path, so to -# exclude all test directories use the pattern */test/* - -EXCLUDE_SYMBOLS = - -# The EXAMPLE_PATH tag can be used to specify one or more files or directories -# that contain example code fragments that are included (see the \include -# command). - -EXAMPLE_PATH = - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and -# *.h) to filter out the source-files in the directories. If left blank all -# files are included. - -EXAMPLE_PATTERNS = * - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude commands -# irrespective of the value of the RECURSIVE tag. -# The default value is: NO. - -EXAMPLE_RECURSIVE = NO - -# The IMAGE_PATH tag can be used to specify one or more files or directories -# that contain images that are to be included in the documentation (see the -# \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command: -# -# <filter> <input-file> -# -# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the -# name of an input file. Doxygen will then use the output that the filter -# program writes to standard output. If FILTER_PATTERNS is specified, this tag -# will be ignored. -# -# Note that the filter must not add or remove lines; it is applied before the -# code is scanned, but not when the output code is generated. If lines are added -# or removed, the anchors will not be placed correctly. -# -# Note that for custom extensions or not directly supported extensions you also -# need to set EXTENSION_MAPPING for the extension otherwise the files are not -# properly processed by doxygen. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. The filters are a list of the form: pattern=filter -# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how -# filters are used. If the FILTER_PATTERNS tag is empty or if none of the -# patterns match the file name, INPUT_FILTER is applied. -# -# Note that for custom extensions or not directly supported extensions you also -# need to set EXTENSION_MAPPING for the extension otherwise the files are not -# properly processed by doxygen. - -FILTER_PATTERNS = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will also be used to filter the input files that are used for -# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). -# The default value is: NO. - -FILTER_SOURCE_FILES = NO - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and -# it is also possible to disable source filtering for a specific pattern using -# *.ext= (so without naming a filter). -# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. - -FILTER_SOURCE_PATTERNS = - -# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that -# is part of the input, its contents will be placed on the main page -# (index.html). This can be useful if you have a project on for instance GitHub -# and want to reuse the introduction page also for the doxygen output. - -USE_MDFILE_AS_MAINPAGE = README.md - -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will be -# generated. Documented entities will be cross-referenced with these sources. -# -# Note: To get rid of all source code in the generated output, make sure that -# also VERBATIM_HEADERS is set to NO. -# The default value is: NO. - -SOURCE_BROWSER = YES - -# Setting the INLINE_SOURCES tag to YES will include the body of functions, -# classes and enums directly into the documentation. -# The default value is: NO. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any -# special comment blocks from generated source code fragments. Normal C, C++ and -# Fortran comments will always remain visible. -# The default value is: YES. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES then for each documented -# function all documented functions referencing it will be listed. -# The default value is: NO. - -REFERENCED_BY_RELATION = NO - -# If the REFERENCES_RELATION tag is set to YES then for each documented function -# all documented entities called/used by that function will be listed. -# The default value is: NO. - -REFERENCES_RELATION = NO - -# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set -# to YES then the hyperlinks from functions in REFERENCES_RELATION and -# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will -# link to the documentation. -# The default value is: YES. - -REFERENCES_LINK_SOURCE = YES - -# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the -# source code will show a tooltip with additional information such as prototype, -# brief description and links to the definition and documentation. Since this -# will make the HTML file larger and loading of large files a bit slower, you -# can opt to disable this feature. -# The default value is: YES. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -SOURCE_TOOLTIPS = YES - -# If the USE_HTAGS tag is set to YES then the references to source code will -# point to the HTML generated by the htags(1) tool instead of doxygen built-in -# source browser. The htags tool is part of GNU's global source tagging system -# (see http://www.gnu.org/software/global/global.html). You will need version -# 4.8.6 or higher. -# -# To use it do the following: -# - Install the latest version of global -# - Enable SOURCE_BROWSER and USE_HTAGS in the config file -# - Make sure the INPUT points to the root of the source tree -# - Run doxygen as normal -# -# Doxygen will invoke htags (and that will in turn invoke gtags), so these -# tools must be available from the command line (i.e. in the search path). -# -# The result: instead of the source browser generated by doxygen, the links to -# source code will now point to the output of htags. -# The default value is: NO. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a -# verbatim copy of the header file for each class for which an include is -# specified. Set to NO to disable this. -# See also: Section \class. -# The default value is: YES. - -VERBATIM_HEADERS = YES - -# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the -# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the -# cost of reduced performance. This can be particularly helpful with template -# rich C++ code for which doxygen's built-in parser lacks the necessary type -# information. -# Note: The availability of this option depends on whether or not doxygen was -# generated with the -Duse-libclang=ON option for CMake. -# The default value is: NO. - -CLANG_ASSISTED_PARSING = NO - -# If clang assisted parsing is enabled you can provide the compiler with command -# line options that you would normally use when invoking the compiler. Note that -# the include paths will already be set by doxygen for the files and directories -# specified with INPUT and INCLUDE_PATH. -# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. - -CLANG_OPTIONS = - -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all -# compounds will be generated. Enable this if the project contains a lot of -# classes, structs, unions or interfaces. -# The default value is: YES. - -ALPHABETICAL_INDEX = YES - -# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in -# which the alphabetical index list will be split. -# Minimum value: 1, maximum value: 20, default value: 5. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all classes will -# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag -# can be used to specify a prefix (or a list of prefixes) that should be ignored -# while generating the index headers. -# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output -# The default value is: YES. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each -# generated HTML page (for example: .htm, .php, .asp). -# The default value is: .html. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a user-defined HTML header file for -# each generated HTML page. If the tag is left blank doxygen will generate a -# standard header. -# -# To get valid HTML the header file that includes any scripts and style sheets -# that doxygen needs, which is dependent on the configuration options used (e.g. -# the setting GENERATE_TREEVIEW). It is highly recommended to start with a -# default header using -# doxygen -w html new_header.html new_footer.html new_stylesheet.css -# YourConfigFile -# and then modify the file new_header.html. See also section "Doxygen usage" -# for information on how to generate the default header that doxygen normally -# uses. -# Note: The header is subject to change so you typically have to regenerate the -# default header when upgrading to a newer version of doxygen. For a description -# of the possible markers and block names see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_HEADER = - -# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each -# generated HTML page. If the tag is left blank doxygen will generate a standard -# footer. See HTML_HEADER for more information on how to generate a default -# footer and what special commands can be used inside the footer. See also -# section "Doxygen usage" for information on how to generate the default footer -# that doxygen normally uses. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_FOOTER = - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style -# sheet that is used by each HTML page. It can be used to fine-tune the look of -# the HTML output. If left blank doxygen will generate a default style sheet. -# See also section "Doxygen usage" for information on how to generate the style -# sheet that doxygen normally uses. -# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as -# it is more robust and this tag (HTML_STYLESHEET) will in the future become -# obsolete. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_STYLESHEET = - -# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined -# cascading style sheets that are included after the standard style sheets -# created by doxygen. Using this option one can overrule certain style aspects. -# This is preferred over using HTML_STYLESHEET since it does not replace the -# standard style sheet and is therefore more robust against future updates. -# Doxygen will copy the style sheet files to the output directory. -# Note: The order of the extra style sheet files is of importance (e.g. the last -# style sheet in the list overrules the setting of the previous ones in the -# list). For an example see the documentation. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_STYLESHEET = - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that the -# files will be copied as-is; there are no commands or markers available. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_EXTRA_FILES = - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen -# will adjust the colors in the style sheet and background images according to -# this color. Hue is specified as an angle on a colorwheel, see -# http://en.wikipedia.org/wiki/Hue for more information. For instance the value -# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 -# purple, and 360 is red again. -# Minimum value: 0, maximum value: 359, default value: 220. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_HUE = 220 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors -# in the HTML output. For a value of 0 the output will use grayscales only. A -# value of 255 will produce the most vivid colors. -# Minimum value: 0, maximum value: 255, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_SAT = 100 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the -# luminance component of the colors in the HTML output. Values below 100 -# gradually make the output lighter, whereas values above 100 make the output -# darker. The value divided by 100 is the actual gamma applied, so 80 represents -# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not -# change the gamma. -# Minimum value: 40, maximum value: 240, default value: 80. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting this -# to YES can help to show when doxygen was last run and thus if the -# documentation is up to date. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_TIMESTAMP = NO - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_DYNAMIC_SECTIONS = NO - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries -# shown in the various tree structured indices initially; the user can expand -# and collapse entries dynamically later on. Doxygen will expand the tree to -# such a level that at most the specified number of entries are visible (unless -# a fully collapsed tree already exceeds this amount). So setting the number of -# entries 1 will produce a full collapsed tree by default. 0 is a special value -# representing an infinite number of entries and will result in a full expanded -# tree by default. -# Minimum value: 0, maximum value: 9999, default value: 100. -# This tag requires that the tag GENERATE_HTML is set to YES. - -HTML_INDEX_NUM_ENTRIES = 100 - -# If the GENERATE_DOCSET tag is set to YES, additional index files will be -# generated that can be used as input for Apple's Xcode 3 integrated development -# environment (see: http://developer.apple.com/tools/xcode/), introduced with -# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a -# Makefile in the HTML output directory. Running make will produce the docset in -# that directory and running make install will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at -# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_DOCSET = NO - -# This tag determines the name of the docset feed. A documentation feed provides -# an umbrella under which multiple documentation sets from a single provider -# (such as a company or product suite) can be grouped. -# The default value is: Doxygen generated docs. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_FEEDNAME = "Doxygen generated docs" - -# This tag specifies a string that should uniquely identify the documentation -# set bundle. This should be a reverse domain-name style string, e.g. -# com.mycompany.MyDocSet. Doxygen will append .docset to the name. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_BUNDLE_ID = org.doxygen.Project - -# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify -# the documentation publisher. This should be a reverse domain-name style -# string, e.g. com.mycompany.MyDocSet.documentation. -# The default value is: org.doxygen.Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_ID = org.doxygen.Publisher - -# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. -# The default value is: Publisher. -# This tag requires that the tag GENERATE_DOCSET is set to YES. - -DOCSET_PUBLISHER_NAME = Publisher - -# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three -# additional HTML index files: index.hhp, index.hhc, and index.hhk. The -# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop -# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on -# Windows. -# -# The HTML Help Workshop contains a compiler that can convert all HTML output -# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML -# files are now used as the Windows 98 help format, and will replace the old -# Windows help format (.hlp) on all Windows platforms in the future. Compressed -# HTML files also contain an index, a table of contents, and you can search for -# words in the documentation. The HTML workshop also contains a viewer for -# compressed HTML files. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_HTMLHELP = NO - -# The CHM_FILE tag can be used to specify the file name of the resulting .chm -# file. You can add a path in front of the file if the result should not be -# written to the html output directory. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_FILE = - -# The HHC_LOCATION tag can be used to specify the location (absolute path -# including file name) of the HTML help compiler (hhc.exe). If non-empty, -# doxygen will try to run the HTML help compiler on the generated index.hhp. -# The file has to be specified with full path. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -HHC_LOCATION = - -# The GENERATE_CHI flag controls if a separate .chi index file is generated -# (YES) or that it should be included in the master .chm file (NO). -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -GENERATE_CHI = NO - -# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) -# and project file content. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -CHM_INDEX_ENCODING = - -# The BINARY_TOC flag controls whether a binary table of contents is generated -# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it -# enables the Previous and Next buttons. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members to -# the table of contents of the HTML help documentation and to the tree view. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTMLHELP is set to YES. - -TOC_EXPAND = NO - -# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and -# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that -# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help -# (.qch) of the generated HTML documentation. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_QHP = NO - -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify -# the file name of the resulting .qch file. The path specified is relative to -# the HTML output folder. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QCH_FILE = - -# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help -# Project output. For more information please see Qt Help Project / Namespace -# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_NAMESPACE = org.doxygen.Project - -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt -# Help Project output. For more information please see Qt Help Project / Virtual -# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- -# folders). -# The default value is: doc. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_VIRTUAL_FOLDER = doc - -# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom -# filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_NAME = - -# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the -# custom filter to add. For more information please see Qt Help Project / Custom -# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- -# filters). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_CUST_FILTER_ATTRS = - -# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this -# project's filter section matches. Qt Help Project / Filter Attributes (see: -# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHP_SECT_FILTER_ATTRS = - -# The QHG_LOCATION tag can be used to specify the location of Qt's -# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the -# generated .qhp file. -# This tag requires that the tag GENERATE_QHP is set to YES. - -QHG_LOCATION = - -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be -# generated, together with the HTML files, they form an Eclipse help plugin. To -# install this plugin and make it available under the help contents menu in -# Eclipse, the contents of the directory containing the HTML and XML files needs -# to be copied into the plugins directory of eclipse. The name of the directory -# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. -# After copying Eclipse needs to be restarted before the help appears. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_ECLIPSEHELP = NO - -# A unique identifier for the Eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have this -# name. Each documentation set should have its own identifier. -# The default value is: org.doxygen.Project. -# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. - -ECLIPSE_DOC_ID = org.doxygen.Project - -# If you want full control over the layout of the generated HTML pages it might -# be necessary to disable the index and replace it with your own. The -# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top -# of each HTML page. A value of NO enables the index and the value YES disables -# it. Since the tabs in the index contain the same information as the navigation -# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. If the tag -# value is set to YES, a side panel will be generated containing a tree-like -# index structure (just like the one that is generated for HTML Help). For this -# to work a browser that supports JavaScript, DHTML, CSS and frames is required -# (i.e. any modern browser). Windows users are probably better off using the -# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can -# further fine-tune the look of the index. As an example, the default style -# sheet generated by doxygen has an example that shows how to put an image at -# the root of the tree instead of the PROJECT_NAME. Since the tree basically has -# the same information as the tab index, you could consider setting -# DISABLE_INDEX to YES when enabling this option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -GENERATE_TREEVIEW = NO - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that -# doxygen will group on one line in the generated HTML documentation. -# -# Note that a value of 0 will completely suppress the enum values from appearing -# in the overview section. -# Minimum value: 0, maximum value: 20, default value: 4. -# This tag requires that the tag GENERATE_HTML is set to YES. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used -# to set the initial width (in pixels) of the frame in which the tree is shown. -# Minimum value: 0, maximum value: 1500, default value: 250. -# This tag requires that the tag GENERATE_HTML is set to YES. - -TREEVIEW_WIDTH = 250 - -# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to -# external symbols imported via tag files in a separate window. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of LaTeX formulas included as images in -# the HTML documentation. When you change the font size after a successful -# doxygen run you need to manually remove any form_*.png images from the HTML -# output directory to force them to be regenerated. -# Minimum value: 8, maximum value: 50, default value: 10. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are not -# supported properly for IE 6.0, but are supported on all modern browsers. -# -# Note that when changing this option you need to delete any form_*.png files in -# the HTML output directory before the changes have effect. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see -# http://www.mathjax.org) which uses client side Javascript for the rendering -# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX -# installed or if you want to formulas look prettier in the HTML output. When -# enabled you may also need to install MathJax separately and configure the path -# to it using the MATHJAX_RELPATH option. -# The default value is: NO. -# This tag requires that the tag GENERATE_HTML is set to YES. - -USE_MATHJAX = NO - -# When MathJax is enabled you can set the default output format to be used for -# the MathJax output. See the MathJax site (see: -# http://docs.mathjax.org/en/latest/output.html) for more details. -# Possible values are: HTML-CSS (which is slower, but has the best -# compatibility), NativeMML (i.e. MathML) and SVG. -# The default value is: HTML-CSS. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_FORMAT = HTML-CSS - -# When MathJax is enabled you need to specify the location relative to the HTML -# output directory using the MATHJAX_RELPATH option. The destination directory -# should contain the MathJax.js script. For instance, if the mathjax directory -# is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax -# Content Delivery Network so you can quickly see the result without installing -# MathJax. However, it is strongly recommended to install a local copy of -# MathJax from http://www.mathjax.org before deployment. -# The default value is: http://cdn.mathjax.org/mathjax/latest. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest - -# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax -# extension names that should be enabled during MathJax rendering. For example -# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_EXTENSIONS = - -# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces -# of code that will be used on startup of the MathJax code. See the MathJax site -# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an -# example see the documentation. -# This tag requires that the tag USE_MATHJAX is set to YES. - -MATHJAX_CODEFILE = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box for -# the HTML output. The underlying search engine uses javascript and DHTML and -# should work on any modern browser. Note that when using HTML help -# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) -# there is already a search function so this one should typically be disabled. -# For large projects the javascript based search engine can be slow, then -# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to -# search using the keyboard; to jump to the search box use <access key> + S -# (what the <access key> is depends on the OS and browser, but it is typically -# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down -# key> to jump into the search results window, the results can be navigated -# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel -# the search. The filter options can be selected when the cursor is inside the -# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys> -# to select a filter and <Enter> or <escape> to activate or cancel the filter -# option. -# The default value is: YES. -# This tag requires that the tag GENERATE_HTML is set to YES. - -SEARCHENGINE = YES - -# When the SERVER_BASED_SEARCH tag is enabled the search engine will be -# implemented using a web server instead of a web client using Javascript. There -# are two flavors of web server based searching depending on the EXTERNAL_SEARCH -# setting. When disabled, doxygen will generate a PHP script for searching and -# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing -# and searching needs to be provided by external tools. See the section -# "External Indexing and Searching" for details. -# The default value is: NO. -# This tag requires that the tag SEARCHENGINE is set to YES. - -SERVER_BASED_SEARCH = NO - -# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP -# script for searching. Instead the search results are written to an XML file -# which needs to be processed by an external indexer. Doxygen will invoke an -# external search engine pointed to by the SEARCHENGINE_URL option to obtain the -# search results. -# -# Doxygen ships with an example indexer (doxyindexer) and search engine -# (doxysearch.cgi) which are based on the open source search engine library -# Xapian (see: http://xapian.org/). -# -# See the section "External Indexing and Searching" for details. -# The default value is: NO. -# This tag requires that the tag SEARCHENGINE is set to YES. - -EXTERNAL_SEARCH = NO - -# The SEARCHENGINE_URL should point to a search engine hosted by a web server -# which will return the search results when EXTERNAL_SEARCH is enabled. -# -# Doxygen ships with an example indexer (doxyindexer) and search engine -# (doxysearch.cgi) which are based on the open source search engine library -# Xapian (see: http://xapian.org/). See the section "External Indexing and -# Searching" for details. -# This tag requires that the tag SEARCHENGINE is set to YES. - -SEARCHENGINE_URL = - -# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed -# search data is written to a file for indexing by an external tool. With the -# SEARCHDATA_FILE tag the name of this file can be specified. -# The default file is: searchdata.xml. -# This tag requires that the tag SEARCHENGINE is set to YES. - -SEARCHDATA_FILE = searchdata.xml - -# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the -# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is -# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple -# projects and redirect the results back to the right project. -# This tag requires that the tag SEARCHENGINE is set to YES. - -EXTERNAL_SEARCH_ID = - -# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen -# projects other than the one defined by this configuration file, but that are -# all added to the same external search index. Each project needs to have a -# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of -# to a relative location where the documentation can be found. The format is: -# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... -# This tag requires that the tag SEARCHENGINE is set to YES. - -EXTRA_SEARCH_MAPPINGS = - -#--------------------------------------------------------------------------- -# Configuration options related to the LaTeX output -#--------------------------------------------------------------------------- - -# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output. -# The default value is: YES. - -GENERATE_LATEX = NO - -# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: latex. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_OUTPUT = latex - -# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be -# invoked. -# -# Note that when enabling USE_PDFLATEX this option is only used for generating -# bitmaps for formulas in the HTML output, but not in the Makefile that is -# written to the output directory. -# The default file is: latex. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_CMD_NAME = latex - -# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate -# index for LaTeX. -# The default file is: makeindex. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -MAKEINDEX_CMD_NAME = makeindex - -# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX -# documents. This may be useful for small projects and may help to save some -# trees in general. -# The default value is: NO. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -COMPACT_LATEX = NO - -# The PAPER_TYPE tag can be used to set the paper type that is used by the -# printer. -# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x -# 14 inches) and executive (7.25 x 10.5 inches). -# The default value is: a4. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -PAPER_TYPE = a4 - -# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names -# that should be included in the LaTeX output. The package can be specified just -# by its name or with the correct syntax as to be used with the LaTeX -# \usepackage command. To get the times font for instance you can specify : -# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times} -# To use the option intlimits with the amsmath package you can specify: -# EXTRA_PACKAGES=[intlimits]{amsmath} -# If left blank no extra packages will be included. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -EXTRA_PACKAGES = - -# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the -# generated LaTeX document. The header should contain everything until the first -# chapter. If it is left blank doxygen will generate a standard header. See -# section "Doxygen usage" for information on how to let doxygen write the -# default header to a separate file. -# -# Note: Only use a user-defined header if you know what you are doing! The -# following commands have a special meaning inside the header: $title, -# $datetime, $date, $doxygenversion, $projectname, $projectnumber, -# $projectbrief, $projectlogo. Doxygen will replace $title with the empty -# string, for the replacement values of the other commands the user is referred -# to HTML_HEADER. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_HEADER = - -# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the -# generated LaTeX document. The footer should contain everything after the last -# chapter. If it is left blank doxygen will generate a standard footer. See -# LATEX_HEADER for more information on how to generate a default footer and what -# special commands can be used inside the footer. -# -# Note: Only use a user-defined footer if you know what you are doing! -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_FOOTER = - -# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined -# LaTeX style sheets that are included after the standard style sheets created -# by doxygen. Using this option one can overrule certain style aspects. Doxygen -# will copy the style sheet files to the output directory. -# Note: The order of the extra style sheet files is of importance (e.g. the last -# style sheet in the list overrules the setting of the previous ones in the -# list). -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_EXTRA_STYLESHEET = - -# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the LATEX_OUTPUT output -# directory. Note that the files will be copied as-is; there are no commands or -# markers available. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_EXTRA_FILES = - -# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is -# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will -# contain links (just like the HTML output) instead of page references. This -# makes the output suitable for online browsing using a PDF viewer. -# The default value is: YES. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -PDF_HYPERLINKS = YES - -# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate -# the PDF file directly from the LaTeX files. Set this option to YES, to get a -# higher quality PDF documentation. -# The default value is: YES. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -USE_PDFLATEX = YES - -# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode -# command to the generated LaTeX files. This will instruct LaTeX to keep running -# if errors occur, instead of asking the user for help. This option is also used -# when generating formulas in HTML. -# The default value is: NO. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_BATCHMODE = NO - -# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the -# index chapters (such as File Index, Compound Index, etc.) in the output. -# The default value is: NO. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_HIDE_INDICES = NO - -# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source -# code with syntax highlighting in the LaTeX output. -# -# Note that which sources are shown also depends on other settings such as -# SOURCE_BROWSER. -# The default value is: NO. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_SOURCE_CODE = NO - -# The LATEX_BIB_STYLE tag can be used to specify the style to use for the -# bibliography, e.g. plainnat, or ieeetr. See -# http://en.wikipedia.org/wiki/BibTeX and \cite for more info. -# The default value is: plain. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_BIB_STYLE = plain - -# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated -# page will contain the date and time when the page was generated. Setting this -# to NO can help when comparing the output of multiple runs. -# The default value is: NO. -# This tag requires that the tag GENERATE_LATEX is set to YES. - -LATEX_TIMESTAMP = NO - -#--------------------------------------------------------------------------- -# Configuration options related to the RTF output -#--------------------------------------------------------------------------- - -# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The -# RTF output is optimized for Word 97 and may not look too pretty with other RTF -# readers/editors. -# The default value is: NO. - -GENERATE_RTF = NO - -# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: rtf. -# This tag requires that the tag GENERATE_RTF is set to YES. - -RTF_OUTPUT = rtf - -# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF -# documents. This may be useful for small projects and may help to save some -# trees in general. -# The default value is: NO. -# This tag requires that the tag GENERATE_RTF is set to YES. - -COMPACT_RTF = NO - -# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will -# contain hyperlink fields. The RTF file will contain links (just like the HTML -# output) instead of page references. This makes the output suitable for online -# browsing using Word or some other Word compatible readers that support those -# fields. -# -# Note: WordPad (write) and others do not support links. -# The default value is: NO. -# This tag requires that the tag GENERATE_RTF is set to YES. - -RTF_HYPERLINKS = NO - -# Load stylesheet definitions from file. Syntax is similar to doxygen's config -# file, i.e. a series of assignments. You only have to provide replacements, -# missing definitions are set to their default value. -# -# See also section "Doxygen usage" for information on how to generate the -# default style sheet that doxygen normally uses. -# This tag requires that the tag GENERATE_RTF is set to YES. - -RTF_STYLESHEET_FILE = - -# Set optional variables used in the generation of an RTF document. Syntax is -# similar to doxygen's config file. A template extensions file can be generated -# using doxygen -e rtf extensionFile. -# This tag requires that the tag GENERATE_RTF is set to YES. - -RTF_EXTENSIONS_FILE = - -# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code -# with syntax highlighting in the RTF output. -# -# Note that which sources are shown also depends on other settings such as -# SOURCE_BROWSER. -# The default value is: NO. -# This tag requires that the tag GENERATE_RTF is set to YES. - -RTF_SOURCE_CODE = NO - -#--------------------------------------------------------------------------- -# Configuration options related to the man page output -#--------------------------------------------------------------------------- - -# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for -# classes and files. -# The default value is: NO. - -GENERATE_MAN = NO - -# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. A directory man3 will be created inside the directory specified by -# MAN_OUTPUT. -# The default directory is: man. -# This tag requires that the tag GENERATE_MAN is set to YES. - -MAN_OUTPUT = man - -# The MAN_EXTENSION tag determines the extension that is added to the generated -# man pages. In case the manual section does not start with a number, the number -# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is -# optional. -# The default value is: .3. -# This tag requires that the tag GENERATE_MAN is set to YES. - -MAN_EXTENSION = .3 - -# The MAN_SUBDIR tag determines the name of the directory created within -# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by -# MAN_EXTENSION with the initial . removed. -# This tag requires that the tag GENERATE_MAN is set to YES. - -MAN_SUBDIR = - -# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it -# will generate one additional man file for each entity documented in the real -# man page(s). These additional files only source the real man page, but without -# them the man command would be unable to find the correct page. -# The default value is: NO. -# This tag requires that the tag GENERATE_MAN is set to YES. - -MAN_LINKS = NO - -#--------------------------------------------------------------------------- -# Configuration options related to the XML output -#--------------------------------------------------------------------------- - -# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that -# captures the structure of the code including all documentation. -# The default value is: NO. - -GENERATE_XML = NO - -# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a -# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of -# it. -# The default directory is: xml. -# This tag requires that the tag GENERATE_XML is set to YES. - -XML_OUTPUT = xml - -# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program -# listings (including syntax highlighting and cross-referencing information) to -# the XML output. Note that enabling this will significantly increase the size -# of the XML output. -# The default value is: YES. -# This tag requires that the tag GENERATE_XML is set to YES. - -XML_PROGRAMLISTING = YES - -#--------------------------------------------------------------------------- -# Configuration options related to the DOCBOOK output -#--------------------------------------------------------------------------- - -# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files -# that can be used to generate PDF. -# The default value is: NO. - -GENERATE_DOCBOOK = NO - -# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in -# front of it. -# The default directory is: docbook. -# This tag requires that the tag GENERATE_DOCBOOK is set to YES. - -DOCBOOK_OUTPUT = docbook - -# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the -# program listings (including syntax highlighting and cross-referencing -# information) to the DOCBOOK output. Note that enabling this will significantly -# increase the size of the DOCBOOK output. -# The default value is: NO. -# This tag requires that the tag GENERATE_DOCBOOK is set to YES. - -DOCBOOK_PROGRAMLISTING = NO - -#--------------------------------------------------------------------------- -# Configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- - -# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an -# AutoGen Definitions (see http://autogen.sf.net) file that captures the -# structure of the code including all documentation. Note that this feature is -# still experimental and incomplete at the moment. -# The default value is: NO. - -GENERATE_AUTOGEN_DEF = NO - -#--------------------------------------------------------------------------- -# Configuration options related to the Perl module output -#--------------------------------------------------------------------------- - -# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module -# file that captures the structure of the code including all documentation. -# -# Note that this feature is still experimental and incomplete at the moment. -# The default value is: NO. - -GENERATE_PERLMOD = NO - -# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary -# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI -# output from the Perl module output. -# The default value is: NO. -# This tag requires that the tag GENERATE_PERLMOD is set to YES. - -PERLMOD_LATEX = NO - -# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely -# formatted so it can be parsed by a human reader. This is useful if you want to -# understand what is going on. On the other hand, if this tag is set to NO, the -# size of the Perl module output will be much smaller and Perl will parse it -# just the same. -# The default value is: YES. -# This tag requires that the tag GENERATE_PERLMOD is set to YES. - -PERLMOD_PRETTY = YES - -# The names of the make variables in the generated doxyrules.make file are -# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful -# so different doxyrules.make files included by the same Makefile don't -# overwrite each other's variables. -# This tag requires that the tag GENERATE_PERLMOD is set to YES. - -PERLMOD_MAKEVAR_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- - -# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all -# C-preprocessor directives found in the sources and include files. -# The default value is: YES. - -ENABLE_PREPROCESSING = YES - -# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names -# in the source code. If set to NO, only conditional compilation will be -# performed. Macro expansion can be done in a controlled way by setting -# EXPAND_ONLY_PREDEF to YES. -# The default value is: NO. -# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. - -MACRO_EXPANSION = NO - -# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then -# the macro expansion is limited to the macros specified with the PREDEFINED and -# EXPAND_AS_DEFINED tags. -# The default value is: NO. -# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. - -EXPAND_ONLY_PREDEF = NO - -# If the SEARCH_INCLUDES tag is set to YES, the include files in the -# INCLUDE_PATH will be searched if a #include is found. -# The default value is: YES. -# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. - -SEARCH_INCLUDES = YES - -# The INCLUDE_PATH tag can be used to specify one or more directories that -# contain include files that are not input files but should be processed by the -# preprocessor. -# This tag requires that the tag SEARCH_INCLUDES is set to YES. - -INCLUDE_PATH = - -# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard -# patterns (like *.h and *.hpp) to filter out the header-files in the -# directories. If left blank, the patterns specified with FILE_PATTERNS will be -# used. -# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. - -INCLUDE_FILE_PATTERNS = - -# The PREDEFINED tag can be used to specify one or more macro names that are -# defined before the preprocessor is started (similar to the -D option of e.g. -# gcc). The argument of the tag is a list of macros of the form: name or -# name=definition (no spaces). If the definition and the "=" are omitted, "=1" -# is assumed. To prevent a macro definition from being undefined via #undef or -# recursively expanded use the := operator instead of the = operator. -# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. - -PREDEFINED = - -# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this -# tag can be used to specify a list of macro names that should be expanded. The -# macro definition that is found in the sources will be used. Use the PREDEFINED -# tag if you want to use a different macro definition that overrules the -# definition found in the source code. -# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. - -EXPAND_AS_DEFINED = - -# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will -# remove all references to function-like macros that are alone on a line, have -# an all uppercase name, and do not end with a semicolon. Such function macros -# are typically used for boiler-plate code, and will confuse the parser if not -# removed. -# The default value is: YES. -# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. - -SKIP_FUNCTION_MACROS = YES - -#--------------------------------------------------------------------------- -# Configuration options related to external references -#--------------------------------------------------------------------------- - -# The TAGFILES tag can be used to specify one or more tag files. For each tag -# file the location of the external documentation should be added. The format of -# a tag file without this location is as follows: -# TAGFILES = file1 file2 ... -# Adding location for the tag files is done as follows: -# TAGFILES = file1=loc1 "file2 = loc2" ... -# where loc1 and loc2 can be relative or absolute paths or URLs. See the -# section "Linking to external documentation" for more information about the use -# of tag files. -# Note: Each tag file must have a unique name (where the name does NOT include -# the path). If a tag file is not located in the directory in which doxygen is -# run, you must also specify the path to the tagfile here. - -TAGFILES = - -# When a file name is specified after GENERATE_TAGFILE, doxygen will create a -# tag file that is based on the input files it reads. See section "Linking to -# external documentation" for more information about the usage of tag files. - -GENERATE_TAGFILE = - -# If the ALLEXTERNALS tag is set to YES, all external class will be listed in -# the class index. If set to NO, only the inherited external classes will be -# listed. -# The default value is: NO. - -ALLEXTERNALS = NO - -# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed -# in the modules index. If set to NO, only the current project's groups will be -# listed. -# The default value is: YES. - -EXTERNAL_GROUPS = YES - -# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in -# the related pages index. If set to NO, only the current project's pages will -# be listed. -# The default value is: YES. - -EXTERNAL_PAGES = YES - -# The PERL_PATH should be the absolute path and name of the perl script -# interpreter (i.e. the result of 'which perl'). -# The default file (with absolute path) is: /usr/bin/perl. - -PERL_PATH = /usr/bin/perl - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- - -# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram -# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to -# NO turns the diagrams off. Note that this option also works with HAVE_DOT -# disabled, but it is recommended to install and use dot, since it yields more -# powerful graphs. -# The default value is: YES. - -CLASS_DIAGRAMS = YES - -# You can define message sequence charts within doxygen comments using the \msc -# command. Doxygen will then run the mscgen tool (see: -# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the -# documentation. The MSCGEN_PATH tag allows you to specify the directory where -# the mscgen tool resides. If left empty the tool is assumed to be found in the -# default search path. - -MSCGEN_PATH = - -# You can include diagrams made with dia in doxygen documentation. Doxygen will -# then run dia to produce the diagram and insert it in the documentation. The -# DIA_PATH tag allows you to specify the directory where the dia binary resides. -# If left empty dia is assumed to be found in the default search path. - -DIA_PATH = - -# If set to YES the inheritance and collaboration graphs will hide inheritance -# and usage relations if the target is undocumented or is not a class. -# The default value is: YES. - -HIDE_UNDOC_RELATIONS = YES - -# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is -# available from the path. This tool is part of Graphviz (see: -# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent -# Bell Labs. The other options in this section have no effect if this option is -# set to NO -# The default value is: NO. - -HAVE_DOT = NO - -# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed -# to run in parallel. When set to 0 doxygen will base this on the number of -# processors available in the system. You can set it explicitly to a value -# larger than 0 to get control over the balance between CPU load and processing -# speed. -# Minimum value: 0, maximum value: 32, default value: 0. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_NUM_THREADS = 0 - -# When you want a differently looking font in the dot files that doxygen -# generates you can specify the font name using DOT_FONTNAME. You need to make -# sure dot is able to find the font, which can be done by putting it in a -# standard location or by setting the DOTFONTPATH environment variable or by -# setting DOT_FONTPATH to the directory containing the font. -# The default value is: Helvetica. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_FONTNAME = Helvetica - -# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of -# dot graphs. -# Minimum value: 4, maximum value: 24, default value: 10. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_FONTSIZE = 10 - -# By default doxygen will tell dot to use the default font as specified with -# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set -# the path where dot can find it using this tag. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_FONTPATH = - -# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for -# each documented class showing the direct and indirect inheritance relations. -# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -CLASS_GRAPH = YES - -# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a -# graph for each documented class showing the direct and indirect implementation -# dependencies (inheritance, containment, and class references variables) of the -# class with other documented classes. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -COLLABORATION_GRAPH = YES - -# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for -# groups, showing the direct groups dependencies. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -GROUP_GRAPHS = YES - -# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and -# collaboration diagrams in a style similar to the OMG's Unified Modeling -# Language. -# The default value is: NO. -# This tag requires that the tag HAVE_DOT is set to YES. - -UML_LOOK = NO - -# If the UML_LOOK tag is enabled, the fields and methods are shown inside the -# class node. If there are many fields or methods and many nodes the graph may -# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the -# number of items for each type to make the size more manageable. Set this to 0 -# for no limit. Note that the threshold may be exceeded by 50% before the limit -# is enforced. So when you set the threshold to 10, up to 15 fields may appear, -# but if the number exceeds 15, the total amount of fields shown is limited to -# 10. -# Minimum value: 0, maximum value: 100, default value: 10. -# This tag requires that the tag HAVE_DOT is set to YES. - -UML_LIMIT_NUM_FIELDS = 10 - -# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and -# collaboration graphs will show the relations between templates and their -# instances. -# The default value is: NO. -# This tag requires that the tag HAVE_DOT is set to YES. - -TEMPLATE_RELATIONS = NO - -# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to -# YES then doxygen will generate a graph for each documented file showing the -# direct and indirect include dependencies of the file with other documented -# files. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -INCLUDE_GRAPH = YES - -# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are -# set to YES then doxygen will generate a graph for each documented file showing -# the direct and indirect include dependencies of the file with other documented -# files. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -INCLUDED_BY_GRAPH = YES - -# If the CALL_GRAPH tag is set to YES then doxygen will generate a call -# dependency graph for every global function or class method. -# -# Note that enabling this option will significantly increase the time of a run. -# So in most cases it will be better to enable call graphs for selected -# functions only using the \callgraph command. Disabling a call graph can be -# accomplished by means of the command \hidecallgraph. -# The default value is: NO. -# This tag requires that the tag HAVE_DOT is set to YES. - -CALL_GRAPH = NO - -# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller -# dependency graph for every global function or class method. -# -# Note that enabling this option will significantly increase the time of a run. -# So in most cases it will be better to enable caller graphs for selected -# functions only using the \callergraph command. Disabling a caller graph can be -# accomplished by means of the command \hidecallergraph. -# The default value is: NO. -# This tag requires that the tag HAVE_DOT is set to YES. - -CALLER_GRAPH = NO - -# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical -# hierarchy of all classes instead of a textual one. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -GRAPHICAL_HIERARCHY = YES - -# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the -# dependencies a directory has on other directories in a graphical way. The -# dependency relations are determined by the #include relations between the -# files in the directories. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -DIRECTORY_GRAPH = YES - -# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images -# generated by dot. For an explanation of the image formats see the section -# output formats in the documentation of the dot tool (Graphviz (see: -# http://www.graphviz.org/)). -# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order -# to make the SVG files visible in IE 9+ (other browsers do not have this -# requirement). -# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo, -# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and -# png:gdiplus:gdiplus. -# The default value is: png. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_IMAGE_FORMAT = png - -# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to -# enable generation of interactive SVG images that allow zooming and panning. -# -# Note that this requires a modern browser other than Internet Explorer. Tested -# and working are Firefox, Chrome, Safari, and Opera. -# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make -# the SVG files visible. Older versions of IE do not have SVG support. -# The default value is: NO. -# This tag requires that the tag HAVE_DOT is set to YES. - -INTERACTIVE_SVG = NO - -# The DOT_PATH tag can be used to specify the path where the dot tool can be -# found. If left blank, it is assumed the dot tool can be found in the path. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_PATH = - -# The DOTFILE_DIRS tag can be used to specify one or more directories that -# contain dot files that are included in the documentation (see the \dotfile -# command). -# This tag requires that the tag HAVE_DOT is set to YES. - -DOTFILE_DIRS = - -# The MSCFILE_DIRS tag can be used to specify one or more directories that -# contain msc files that are included in the documentation (see the \mscfile -# command). - -MSCFILE_DIRS = - -# The DIAFILE_DIRS tag can be used to specify one or more directories that -# contain dia files that are included in the documentation (see the \diafile -# command). - -DIAFILE_DIRS = - -# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the -# path where java can find the plantuml.jar file. If left blank, it is assumed -# PlantUML is not used or called during a preprocessing step. Doxygen will -# generate a warning when it encounters a \startuml command in this case and -# will not generate output for the diagram. - -PLANTUML_JAR_PATH = - -# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a -# configuration file for plantuml. - -PLANTUML_CFG_FILE = - -# When using plantuml, the specified paths are searched for files specified by -# the !include statement in a plantuml block. - -PLANTUML_INCLUDE_PATH = - -# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes -# that will be shown in the graph. If the number of nodes in a graph becomes -# larger than this value, doxygen will truncate the graph, which is visualized -# by representing a node as a red box. Note that doxygen if the number of direct -# children of the root node in a graph is already larger than -# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that -# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. -# Minimum value: 0, maximum value: 10000, default value: 50. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_GRAPH_MAX_NODES = 50 - -# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs -# generated by dot. A depth value of 3 means that only nodes reachable from the -# root by following a path via at most 3 edges will be shown. Nodes that lay -# further from the root node will be omitted. Note that setting this option to 1 -# or 2 may greatly reduce the computation time needed for large code bases. Also -# note that the size of a graph can be further restricted by -# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. -# Minimum value: 0, maximum value: 1000, default value: 0. -# This tag requires that the tag HAVE_DOT is set to YES. - -MAX_DOT_GRAPH_DEPTH = 0 - -# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent -# background. This is disabled by default, because dot on Windows does not seem -# to support this out of the box. -# -# Warning: Depending on the platform used, enabling this option may lead to -# badly anti-aliased labels on the edges of a graph (i.e. they become hard to -# read). -# The default value is: NO. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_TRANSPARENT = NO - -# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output -# files in one run (i.e. multiple -o and -T options on the command line). This -# makes dot run faster, but since only newer versions of dot (>1.8.10) support -# this, this feature is disabled by default. -# The default value is: NO. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_MULTI_TARGETS = NO - -# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page -# explaining the meaning of the various boxes and arrows in the dot generated -# graphs. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -GENERATE_LEGEND = YES - -# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot -# files that are used to generate the various graphs. -# The default value is: YES. -# This tag requires that the tag HAVE_DOT is set to YES. - -DOT_CLEANUP = YES diff --git a/node_modules/node-addon-api/doc/array_buffer.md b/node_modules/node-addon-api/doc/array_buffer.md deleted file mode 100644 index ca9d45c..0000000 --- a/node_modules/node-addon-api/doc/array_buffer.md +++ /dev/null @@ -1,129 +0,0 @@ -# ArrayBuffer - -The `Napi::ArrayBuffer` class corresponds to the -[JavaScript `ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) -class. - -## Methods - -### New - -Allocates a new `Napi::ArrayBuffer` instance with a given length. - -```cpp -static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, size_t byteLength); -``` - -- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance. -- `[in] byteLength`: The length to be allocated, in bytes. - -Returns a new `Napi::ArrayBuffer` instance. - -### New - -Wraps the provided external data into a new `Napi::ArrayBuffer` instance. - -The `Napi::ArrayBuffer` instance does not assume ownership for the data and -expects it to be valid for the lifetime of the instance. Since the -`Napi::ArrayBuffer` is subject to garbage collection this overload is only -suitable for data which is static and never needs to be freed. - -```cpp -static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, void* externalData, size_t byteLength); -``` - -- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance. -- `[in] externalData`: The pointer to the external data to wrap. -- `[in] byteLength`: The length of the `externalData`, in bytes. - -Returns a new `Napi::ArrayBuffer` instance. - -### New - -Wraps the provided external data into a new `Napi::ArrayBuffer` instance. - -The `Napi::ArrayBuffer` instance does not assume ownership for the data and -expects it to be valid for the lifetime of the instance. The data can only be -freed once the `finalizeCallback` is invoked to indicate that the -`Napi::ArrayBuffer` has been released. - -```cpp -template <typename Finalizer> -static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, - void* externalData, - size_t byteLength, - Finalizer finalizeCallback); -``` - -- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance. -- `[in] externalData`: The pointer to the external data to wrap. -- `[in] byteLength`: The length of the `externalData`, in bytes. -- `[in] finalizeCallback`: A function to be called when the `Napi::ArrayBuffer` is - destroyed. It must implement `operator()`, accept a `void*` (which is the - `externalData` pointer), and return `void`. - -Returns a new `Napi::ArrayBuffer` instance. - -### New - -Wraps the provided external data into a new `Napi::ArrayBuffer` instance. - -The `Napi::ArrayBuffer` instance does not assume ownership for the data and expects it -to be valid for the lifetime of the instance. The data can only be freed once -the `finalizeCallback` is invoked to indicate that the `Napi::ArrayBuffer` has been -released. - -```cpp -template <typename Finalizer, typename Hint> -static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, - void* externalData, - size_t byteLength, - Finalizer finalizeCallback, - Hint* finalizeHint); -``` - -- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance. -- `[in] externalData`: The pointer to the external data to wrap. -- `[in] byteLength`: The length of the `externalData`, in bytes. -- `[in] finalizeCallback`: The function to be called when the `Napi::ArrayBuffer` is - destroyed. It must implement `operator()`, accept a `void*` (which is the - `externalData` pointer) and `Hint*`, and return `void`. -- `[in] finalizeHint`: The hint to be passed as the second parameter of the - finalize callback. - -Returns a new `Napi::ArrayBuffer` instance. - -### Constructor - -Initializes an empty instance of the `Napi::ArrayBuffer` class. - -```cpp -Napi::ArrayBuffer::ArrayBuffer(); -``` - -### Constructor - -Initializes a wrapper instance of an existing `Napi::ArrayBuffer` object. - -```cpp -Napi::ArrayBuffer::ArrayBuffer(napi_env env, napi_value value); -``` - -- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance. -- `[in] value`: The `Napi::ArrayBuffer` reference to wrap. - -### ByteLength - -```cpp -size_t Napi::ArrayBuffer::ByteLength() const; -``` - -Returns the length of the wrapped data, in bytes. - -### Data - -```cpp -void* Napi::ArrayBuffer::Data() const; -``` - -Returns a pointer the wrapped data. diff --git a/node_modules/node-addon-api/doc/async_context.md b/node_modules/node-addon-api/doc/async_context.md deleted file mode 100644 index 8e1f481..0000000 --- a/node_modules/node-addon-api/doc/async_context.md +++ /dev/null @@ -1,86 +0,0 @@ -# AsyncContext - -The [Napi::AsyncWorker](async_worker.md) class may not be appropriate for every -scenario. When using any other async mechanism, introducing a new class -`Napi::AsyncContext` is necessary to ensure an async operation is properly -tracked by the runtime. The `Napi::AsyncContext` class can be passed to -[Napi::Function::MakeCallback()](function.md) method to properly restore the -correct async execution context. - -## Methods - -### Constructor - -Creates a new `Napi::AsyncContext`. - -```cpp -explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name); -``` - -- `[in] env`: The environment in which to create the `Napi::AsyncContext`. -- `[in] resource_name`: Null-terminated strings that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the `async_hooks` API. - -### Constructor - -Creates a new `Napi::AsyncContext`. - -```cpp -explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name, const Napi::Object& resource); -``` - -- `[in] env`: The environment in which to create the `Napi::AsyncContext`. -- `[in] resource_name`: Null-terminated strings that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the `async_hooks` API. -- `[in] resource`: Object associated with the asynchronous operation that -will be passed to possible `async_hooks`. - -### Destructor - -The `Napi::AsyncContext` to be destroyed. - -```cpp -virtual Napi::AsyncContext::~AsyncContext(); -``` - -### Env - -Requests the environment in which the async context has been initially created. - -```cpp -Napi::Env Env() const; -``` - -Returns the `Napi::Env` environment in which the async context has been created. - -## Operator - -```cpp -Napi::AsyncContext::operator napi_async_context() const; -``` - -Returns the N-API `napi_async_context` wrapped by the `Napi::AsyncContext` -object. This can be used to mix usage of the C N-API and node-addon-api. - -## Example - -```cpp -#include "napi.h" - -void MakeCallbackWithAsyncContext(const Napi::CallbackInfo& info) { - Napi::Function callback = info[0].As<Napi::Function>(); - Napi::Object resource = info[1].As<Napi::Object>(); - - // Creat a new async context instance. - Napi::AsyncContext context(info.Env(), "async_context_test", resource); - - // Invoke the callback with the async context instance. - callback.MakeCallback(Napi::Object::New(info.Env()), - std::initializer_list<napi_value>{}, context); - - // The async context instance is automatically destroyed here because it's - // block-scope like `Napi::HandleScope`. -} -``` diff --git a/node_modules/node-addon-api/doc/async_operations.md b/node_modules/node-addon-api/doc/async_operations.md deleted file mode 100644 index 064a9c5..0000000 --- a/node_modules/node-addon-api/doc/async_operations.md +++ /dev/null @@ -1,31 +0,0 @@ -# Asynchronous operations - -Node.js native add-ons often need to execute long running tasks and to avoid -blocking the **event loop** they have to run them asynchronously from the -**event loop**. -In the Node.js model of execution the event loop thread represents the thread -where JavaScript code is executing. The Node.js guidance is to avoid blocking -other work queued on the event loop thread. Therefore, we need to do this work on -another thread. - -All this means that native add-ons need to leverage async helpers from libuv as -part of their implementation. This allows them to schedule work to be executed -asynchronously so that their methods can return in advance of the work being -completed. - -Node Addon API provides an interface to support functions that cover -the most common asynchronous use cases. There is an abstract classes to implement -asynchronous operations: - -- **[`Napi::AsyncWorker`](async_worker.md)** - -These class helps manage asynchronous operations through an abstraction -of the concept of moving data between the **event loop** and **worker threads**. - -Also, the above class may not be appropriate for every scenario. When using any -other asynchronous mechanism, the following API is necessary to ensure an -asynchronous operation is properly tracked by the runtime: - -- **[AsyncContext](async_context.md)** - -- **[CallbackScope](callback_scope.md)** diff --git a/node_modules/node-addon-api/doc/async_progress_worker.md b/node_modules/node-addon-api/doc/async_progress_worker.md deleted file mode 100644 index 296b51b..0000000 --- a/node_modules/node-addon-api/doc/async_progress_worker.md +++ /dev/null @@ -1,344 +0,0 @@ -# AsyncProgressWorker - -`Napi::AsyncProgressWorker` is an abstract class which implements `Napi::AsyncWorker` -while extending `Napi::AsyncWorker` internally with `Napi::ThreadSafeFunction` for -moving work progress reports from worker thread(s) to event loop threads. - -Like `Napi::AsyncWorker`, once created, execution is requested by calling -`Napi::AsyncProgressWorker::Queue`. When a thread is available for execution -the `Napi::AsyncProgressWorker::Execute` method will be invoked. During the -execution, `Napi::AsyncProgressWorker::ExecutionProgress::Send` can be used to -indicate execution process, which will eventually invoke `Napi::AsyncProgressWorker::OnProgress` -on the JavaScript thread to safely call into JavaScript. Once `Napi::AsyncProgressWorker::Execute` -completes either `Napi::AsyncProgressWorker::OnOK` or `Napi::AsyncProgressWorker::OnError` -will be invoked. Once the `Napi::AsyncProgressWorker::OnOK` or `Napi::AsyncProgressWorker::OnError` -methods are complete the `Napi::AsyncProgressWorker` instance is destructed. - -For the most basic use, only the `Napi::AsyncProgressWorker::Execute` and -`Napi::AsyncProgressWorker::OnProgress` method must be implemented in a subclass. - -## Methods - -[`Napi::AsyncWorker`][] provides detailed descriptions for most methods. - -### Execute - -This method is used to execute some tasks outside of the **event loop** on a libuv -worker thread. Subclasses must implement this method and the method is run on -a thread other than that running the main event loop. As the method is not -running on the main event loop, it must avoid calling any methods from node-addon-api -or running any code that might invoke JavaScript. Instead, once this method is -complete any interaction through node-addon-api with JavaScript should be implemented -in the `Napi::AsyncProgressWorker::OnOK` method and/or `Napi::AsyncProgressWorker::OnError` -which run on the main thread and are invoked when the `Napi::AsyncProgressWorker::Execute` -method completes. - -```cpp -virtual void Napi::AsyncProgressWorker::Execute(const ExecutionProgress& progress) = 0; -``` - -### OnOK - -This method is invoked when the computation in the `Execute` method ends. -The default implementation runs the `Callback` optionally provided when the -`AsyncProgressWorker` class was created. The `Callback` will by default receive no -arguments. Arguments to the callback can be provided by overriding the `GetResult()` -method. - -```cpp -virtual void Napi::AsyncProgressWorker::OnOK(); -``` - -### OnProgress - -This method is invoked when the computation in the `Napi::AsyncProgressWorker::ExecutionProcess::Send` -method was called during worker thread execution. - -```cpp -virtual void Napi::AsyncProgressWorker::OnProgress(const T* data, size_t count) -``` - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(const Napi::Function& callback); -``` - -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. - -Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(const Napi::Function& callback, const char* resource_name); -``` - -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. - -Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(const Napi::Function& callback, const char* resource_name, const Napi::Object& resource); -``` - -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. -- `[in] resource`: Object associated with the asynchronous operation that -will be passed to possible async_hooks. - -Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(const Napi::Object& receiver, const Napi::Function& callback); -``` - -- `[in] receiver`: The `this` object passed to the called function. -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. - -Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(const Napi::Object& receiver, const Napi::Function& callback, const char* resource_name); -``` - -- `[in] receiver`: The `this` object passed to the called function. -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. - -Returns a `Napi::AsyncWork` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(const Napi::Object& receiver, const Napi::Function& callback, const char* resource_name, const Napi::Object& resource); -``` - -- `[in] receiver`: The `this` object to be passed to the called function. -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. -- `[in] resource`: Object associated with the asynchronous operation that -will be passed to possible async_hooks. - -Returns a `Napi::AsyncWork` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(Napi::Env env); -``` - -- `[in] env`: The environment in which to create the `Napi::AsyncProgressWorker`. - -Returns an `Napi::AsyncProgressWorker` instance which can later be queued for execution by calling -`Napi::AsyncProgressWorker::Queue`. - -Available with `NAPI_VERSION` equal to or greater than 5. - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(Napi::Env env, const char* resource_name); -``` - -- `[in] env`: The environment in which to create the `Napi::AsyncProgressWorker`. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. - -Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by -calling `Napi::AsyncProgressWorker::Queue`. - -Available with `NAPI_VERSION` equal to or greater than 5. - -### Constructor - -Creates a new `Napi::AsyncProgressWorker`. - -```cpp -explicit Napi::AsyncProgressWorker(Napi::Env env, const char* resource_name, const Napi::Object& resource); -``` - -- `[in] env`: The environment in which to create the `Napi::AsyncProgressWorker`. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. -- `[in] resource`: Object associated with the asynchronous operation that -will be passed to possible async_hooks. - -Returns a `Napi::AsyncProgressWorker` instance which can later be queued for execution by -calling `Napi::AsyncProgressWorker::Queue`. - -Available with `NAPI_VERSION` equal to or greater than 5. - -### Destructor - -Deletes the created work object that is used to execute logic asynchronously and -release the internal `Napi::ThreadSafeFunction`, which will be aborted to prevent -unexpected upcoming thread safe calls. - -```cpp -virtual Napi::AsyncProgressWorker::~AsyncProgressWorker(); -``` - -# AsyncProgressWorker::ExecutionProcess - -A bridge class created before the worker thread execution of `Napi::AsyncProgressWorker::Execute`. - -## Methods - -### Send - -`Napi::AsyncProgressWorker::ExecutionProcess::Send` takes two arguments, a pointer -to a generic type of data, and a `size_t` to indicate how many items the pointer is -pointing to. - -The data pointed to will be copied to internal slots of `Napi::AsyncProgressWorker` so -after the call to `Napi::AsyncProgressWorker::ExecutionProcess::Send` the data can -be safely released. - -Note that `Napi::AsyncProgressWorker::ExecutionProcess::Send` merely guarantees -**eventual** invocation of `Napi::AsyncProgressWorker::OnProgress`, which means -multiple send might be coalesced into single invocation of `Napi::AsyncProgressWorker::OnProgress` -with latest data. - -```cpp -void Napi::AsyncProgressWorker::ExecutionProcess::Send(const T* data, size_t count) const; -``` - -## Example - -The first step to use the `Napi::AsyncProgressWorker` class is to create a new class that -inherits from it and implement the `Napi::AsyncProgressWorker::Execute` abstract method. -Typically input to the worker will be saved within the class' fields generally -passed in through its constructor. - -During the worker thread execution, the first argument of `Napi::AsyncProgressWorker::Execute` -can be used to report the progress of the execution. - -When the `Napi::AsyncProgressWorker::Execute` method completes without errors the -`Napi::AsyncProgressWorker::OnOK` function callback will be invoked. In this function the -results of the computation will be reassembled and returned back to the initial -JavaScript context. - -`Napi::AsyncProgressWorker` ensures that all the code in the `Napi::AsyncProgressWorker::Execute` -function runs in the background out of the **event loop** thread and at the end -the `Napi::AsyncProgressWorker::OnOK` or `Napi::AsyncProgressWorker::OnError` function will be -called and are executed as part of the event loop. - -The code below shows a basic example of the `Napi::AsyncProgressWorker` implementation: - -```cpp -#include<napi.h> - -#include <chrono> -#include <thread> - -use namespace Napi; - -class EchoWorker : public AsyncProgressWorker<uint32_t> { - public: - EchoWorker(Function& callback, std::string& echo) - : AsyncProgressWorker(callback), echo(echo) {} - - ~EchoWorker() {} - // This code will be executed on the worker thread - void Execute(const ExecutionProgress& progress) { - // Need to simulate cpu heavy task - for (uint32_t i = 0; i < 100; ++i) { - progress.Send(&i, 1) - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - } - - void OnOK() { - HandleScope scope(Env()); - Callback().Call({Env().Null(), String::New(Env(), echo)}); - } - - void OnProgress(const uint32_t* data, size_t /* count */) { - HandleScope scope(Env()); - Callback().Call({Env().Null(), Env().Null(), Number::New(Env(), *data)}); - } - - private: - std::string echo; -}; -``` - -The `EchoWorker`'s constructor calls the base class' constructor to pass in the -callback that the `Napi::AsyncProgressWorker` base class will store persistently. When -the work on the `Napi::AsyncProgressWorker::Execute` method is done the -`Napi::AsyncProgressWorker::OnOk` method is called and the results are return back to -JavaScript when the stored callback is invoked with its associated environment. - -The following code shows an example of how to create and use an `Napi::AsyncProgressWorker` - -```cpp -#include <napi.h> - -// Include EchoWorker class -// .. - -use namespace Napi; - -Value Echo(const CallbackInfo& info) { - // We need to validate the arguments here - Function cb = info[1].As<Function>(); - std::string in = info[0].As<String>(); - EchoWorker* wk = new EchoWorker(cb, in); - wk->Queue(); - return info.Env().Undefined(); -} -``` - -The implementation of a `Napi::AsyncProgressWorker` can be used by creating a -new instance and passing to its constructor the callback to execute when the -asynchronous task ends and other data needed for the computation. Once created, -the only other action needed is to call the `Napi::AsyncProgressWorker::Queue` -method that will queue the created worker for execution. - -[`Napi::AsyncWorker`]: ./async_worker.md diff --git a/node_modules/node-addon-api/doc/async_worker.md b/node_modules/node-addon-api/doc/async_worker.md deleted file mode 100644 index 88668af..0000000 --- a/node_modules/node-addon-api/doc/async_worker.md +++ /dev/null @@ -1,398 +0,0 @@ -# AsyncWorker - -`Napi::AsyncWorker` is an abstract class that you can subclass to remove many of -the tedious tasks of moving data between the event loop and worker threads. This -class internally handles all the details of creating and executing an asynchronous -operation. - -Once created, execution is requested by calling `Napi::AsyncWorker::Queue`. When -a thread is available for execution the `Napi::AsyncWorker::Execute` method will -be invoked. Once `Napi::AsyncWorker::Execute` completes either -`Napi::AsyncWorker::OnOK` or `Napi::AsyncWorker::OnError` will be invoked. Once -the `Napi::AsyncWorker::OnOK` or `Napi::AsyncWorker::OnError` methods are -complete the `Napi::AsyncWorker` instance is destructed. - -For the most basic use, only the `Napi::AsyncWorker::Execute` method must be -implemented in a subclass. - -## Methods - -### Env - -Requests the environment in which the async worker has been initially created. - -```cpp -Napi::Env Napi::AsyncWorker::Env() const; -``` - -Returns the environment in which the async worker has been created. - -### Queue - -Requests that the work be queued for execution. - -```cpp -void Napi::AsyncWorker::Queue(); -``` - -### Cancel - -Cancels queued work if it has not yet been started. If it has already started -executing, it cannot be cancelled. If cancelled successfully neither -`OnOK` nor `OnError` will be called. - -```cpp -void Napi::AsyncWorker::Cancel(); -``` - -### Receiver - -```cpp -Napi::ObjectReference& Napi::AsyncWorker::Receiver(); -``` - -Returns the persistent object reference of the receiver object set when the async -worker was created. - -### Callback - -```cpp -Napi::FunctionReference& Napi::AsyncWorker::Callback(); -``` - -Returns the persistent function reference of the callback set when the async -worker was created. The returned function reference will receive the results of -the computation that happened in the `Napi::AsyncWorker::Execute` method, unless -the default implementation of `Napi::AsyncWorker::OnOK` or -`Napi::AsyncWorker::OnError` is overridden. - -### SuppressDestruct - -```cpp -void Napi::AsyncWorker::SuppressDestruct(); -``` - -Prevents the destruction of the `Napi::AsyncWorker` instance upon completion of -the `Napi::AsyncWorker::OnOK` callback. - -### SetError - -Sets the error message for the error that happened during the execution. Setting -an error message will cause the `Napi::AsyncWorker::OnError` method to be -invoked instead of `Napi::AsyncWorker::OnOK` once the -`Napi::AsyncWorker::Execute` method completes. - -```cpp -void Napi::AsyncWorker::SetError(const std::string& error); -``` - -- `[in] error`: The reference to the string that represent the message of the error. - -### Execute - -This method is used to execute some tasks outside of the **event loop** on a libuv -worker thread. Subclasses must implement this method and the method is run on -a thread other than that running the main event loop. As the method is not -running on the main event loop, it must avoid calling any methods from node-addon-api -or running any code that might invoke JavaScript. Instead, once this method is -complete any interaction through node-addon-api with JavaScript should be implemented -in the `Napi::AsyncWorker::OnOK` method and `Napi::AsyncWorker::OnError` which run -on the main thread and are invoked when the `Napi::AsyncWorker::Execute` method completes. - -```cpp -virtual void Napi::AsyncWorker::Execute() = 0; -``` - -### OnOK - -This method is invoked when the computation in the `Execute` method ends. -The default implementation runs the `Callback` optionally provided when the -`AsyncWorker` class was created. The `Callback` will by default receive no -arguments. The arguments to the `Callback` can be provided by overriding the -`GetResult()` method. - -```cpp -virtual void Napi::AsyncWorker::OnOK(); -``` -### GetResult - -This method returns the arguments passed to the `Callback` invoked by the default -`OnOK()` implementation. The default implementation returns an empty vector, -providing no arguments to the `Callback`. - -```cpp -virtual std::vector<napi_value> Napi::AsyncWorker::GetResult(Napi::Env env); -``` - -### OnError - -This method is invoked after `Napi::AsyncWorker::Execute` completes if an error -occurs while `Napi::AsyncWorker::Execute` is running and C++ exceptions are -enabled or if an error was set through a call to `Napi::AsyncWorker::SetError`. -The default implementation calls the `Callback` provided when the `Napi::AsyncWorker` -class was created, passing in the error as the first parameter. - -```cpp -virtual void Napi::AsyncWorker::OnError(const Napi::Error& e); -``` - -### Destroy - -This method is invoked when the instance must be deallocated. If -`SuppressDestruct()` was not called then this method will be called after either -`OnError()` or `OnOK()` complete. The default implementation of this method -causes the instance to delete itself using the `delete` operator. The method is -provided so as to ensure that instances allocated by means other than the `new` -operator can be deallocated upon work completion. - -```cpp -virtual void Napi::AsyncWorker::Destroy(); -``` - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(const Napi::Function& callback); -``` - -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. - -Returns a `Napi::AsyncWorker` instance which can later be queued for execution by calling -`Queue`. - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(const Napi::Function& callback, const char* resource_name); -``` - -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. - -Returns a `Napi::AsyncWorker` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(const Napi::Function& callback, const char* resource_name, const Napi::Object& resource); -``` - -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. -- `[in] resource`: Object associated with the asynchronous operation that -will be passed to possible async_hooks. - -Returns a `Napi::AsyncWorker` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(const Napi::Object& receiver, const Napi::Function& callback); -``` - -- `[in] receiver`: The `this` object passed to the called function. -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. - -Returns a `Napi::AsyncWorker` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(const Napi::Object& receiver, const Napi::Function& callback, const char* resource_name); -``` - -- `[in] receiver`: The `this` object passed to the called function. -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. - -Returns a `Napi::AsyncWork` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(const Napi::Object& receiver, const Napi::Function& callback, const char* resource_name, const Napi::Object& resource); -``` - -- `[in] receiver`: The `this` object passed to the called function. -- `[in] callback`: The function which will be called when an asynchronous -operations ends. The given function is called from the main event loop thread. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. -- `[in] resource`: Object associated with the asynchronous operation that -will be passed to possible async_hooks. - -Returns a `Napi::AsyncWork` instance which can later be queued for execution by -calling `Napi::AsyncWork::Queue`. - - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(Napi::Env env); -``` - -- `[in] env`: The environment in which to create the `Napi::AsyncWorker`. - -Returns an `Napi::AsyncWorker` instance which can later be queued for execution by calling -`Napi::AsyncWorker::Queue`. - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(Napi::Env env, const char* resource_name); -``` - -- `[in] env`: The environment in which to create the `Napi::AsyncWorker`. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. - -Returns a `Napi::AsyncWorker` instance which can later be queued for execution by -calling `Napi::AsyncWorker::Queue`. - -### Constructor - -Creates a new `Napi::AsyncWorker`. - -```cpp -explicit Napi::AsyncWorker(Napi::Env env, const char* resource_name, const Napi::Object& resource); -``` - -- `[in] env`: The environment in which to create the `Napi::AsyncWorker`. -- `[in] resource_name`: Null-terminated string that represents the -identifier for the kind of resource that is being provided for diagnostic -information exposed by the async_hooks API. -- `[in] resource`: Object associated with the asynchronous operation that -will be passed to possible async_hooks. - -Returns a `Napi::AsyncWorker` instance which can later be queued for execution by -calling `Napi::AsyncWorker::Queue`. - -### Destructor - -Deletes the created work object that is used to execute logic asynchronously. - -```cpp -virtual Napi::AsyncWorker::~AsyncWorker(); -``` - -## Operator - -```cpp -Napi::AsyncWorker::operator napi_async_work() const; -``` - -Returns the N-API napi_async_work wrapped by the `Napi::AsyncWorker` object. This -can be used to mix usage of the C N-API and node-addon-api. - -## Example - -The first step to use the `Napi::AsyncWorker` class is to create a new class that -inherits from it and implement the `Napi::AsyncWorker::Execute` abstract method. -Typically input to your worker will be saved within class' fields generally -passed in through its constructor. - -When the `Napi::AsyncWorker::Execute` method completes without errors the -`Napi::AsyncWorker::OnOK` function callback will be invoked. In this function the -results of the computation will be reassembled and returned back to the initial -JavaScript context. - -`Napi::AsyncWorker` ensures that all the code in the `Napi::AsyncWorker::Execute` -function runs in the background out of the **event loop** thread and at the end -the `Napi::AsyncWorker::OnOK` or `Napi::AsyncWorker::OnError` function will be -called and are executed as part of the event loop. - -The code below shows a basic example of `Napi::AsyncWorker` the implementation: - -```cpp -#include<napi.h> - -#include <chrono> -#include <thread> - -use namespace Napi; - -class EchoWorker : public AsyncWorker { - public: - EchoWorker(Function& callback, std::string& echo) - : AsyncWorker(callback), echo(echo) {} - - ~EchoWorker() {} - // This code will be executed on the worker thread - void Execute() { - // Need to simulate cpu heavy task - std::this_thread::sleep_for(std::chrono::seconds(1)); - } - - void OnOK() { - HandleScope scope(Env()); - Callback().Call({Env().Null(), String::New(Env(), echo)}); - } - - private: - std::string echo; -}; -``` - -The `EchoWorker`'s contructor calls the base class' constructor to pass in the -callback that the `Napi::AsyncWorker` base class will store persistently. When -the work on the `Napi::AsyncWorker::Execute` method is done the -`Napi::AsyncWorker::OnOk` method is called and the results return back to -JavaScript invoking the stored callback with its associated environment. - -The following code shows an example of how to create and use an `Napi::AsyncWorker`. - -```cpp -#include<napi.h> - -// Include EchoWorker class -// .. - -use namespace Napi; - -Value Echo(const CallbackInfo& info) { - // You need to validate the arguments here. - Function cb = info[1].As<Function>(); - std::string in = info[0].As<String>(); - EchoWorker* wk = new EchoWorker(cb, in); - wk->Queue(); - return info.Env().Undefined(); -``` - -Using the implementation of a `Napi::AsyncWorker` is straight forward. You only -need to create a new instance and pass to its constructor the callback you want to -execute when your asynchronous task ends and other data you need for your -computation. Once created the only other action you have to do is to call the -`Napi::AsyncWorker::Queue` method that will queue the created worker for execution. diff --git a/node_modules/node-addon-api/doc/basic_types.md b/node_modules/node-addon-api/doc/basic_types.md deleted file mode 100644 index 03ec14b..0000000 --- a/node_modules/node-addon-api/doc/basic_types.md +++ /dev/null @@ -1,423 +0,0 @@ -# Basic Types - -Node Addon API consists of a few fundamental data types. These allow a user of -the API to create, convert and introspect fundamental JavaScript types, and -interoperate with their C++ counterparts. - -## Value - -`Napi::Value` is the base class of Node Addon API's fundamental object type hierarchy. -It represents a JavaScript value of an unknown type. It is a thin wrapper around -the N-API datatype `napi_value`. Methods on this class can be used to check -the JavaScript type of the underlying N-API `napi_value` and also to convert to -C++ types. - -### Constructor - -```cpp -Napi::Value::Value(); -``` - -Used to create a Node Addon API `Napi::Value` that represents an **empty** value. - -```cpp -Napi::Value::Value(napi_env env, napi_value value); -``` - -- `[in] env` - The `napi_env` environment in which to construct the `Napi::Value` -object. -- `[in] value` - The underlying JavaScript value that the `Napi::Value` instance -represents. - -Returns a Node.js Addon API `Napi::Value` that represents the `napi_value` passed -in. - -### Operators - -#### operator napi_value - -```cpp -Napi::Value::operator napi_value() const; -``` - -Returns the underlying N-API `napi_value`. If the instance is _empty_, this -returns `nullptr`. - -#### operator == - -```cpp -bool Napi::Value::operator ==(const Value& other) const; -``` - -Returns `true` if this value strictly equals another value, or `false` otherwise. - -#### operator != - -```cpp -bool Napi::Value::operator !=(const Value& other) const; -``` - -Returns `false` if this value strictly equals another value, or `true` otherwise. - -### Methods - -#### From -```cpp -template <typename T> -static Napi::Value Napi::Value::From(napi_env env, const T& value); -``` - -- `[in] env` - The `napi_env` environment in which to construct the `Napi::Value` object. -- `[in] value` - The C++ type to represent in JavaScript. - -Returns a `Napi::Value` representing the input C++ type in JavaScript. - -This method is used to convert from a C++ type to a JavaScript value. -Here, `value` may be any of: -- `bool` - returns a `Napi::Boolean`. -- Any integer type - returns a `Napi::Number`. -- Any floating point type - returns a `Napi::Number`. -- `const char*` (encoded using UTF-8, null-terminated) - returns a `Napi::String`. -- `const char16_t*` (encoded using UTF-16-LE, null-terminated) - returns a `Napi::String`. -- `std::string` (encoded using UTF-8) - returns a `Napi::String`. -- `std::u16string` - returns a `Napi::String`. -- `napi::Value` - returns a `Napi::Value`. -- `napi_value` - returns a `Napi::Value`. - -#### As -```cpp -template <typename T> T Napi::Value::As() const; -``` - -Returns the `Napi::Value` cast to a desired C++ type. - -Use this when the actual type is known or assumed. - -Note: -This conversion does NOT coerce the type. Calling any methods inappropriate for -the actual value type will throw `Napi::Error`. - -#### StrictEquals -```cpp -bool Napi::Value::StrictEquals(const Value& other) const; -``` - -- `[in] other` - The value to compare against. - -Returns true if the other `Napi::Value` is strictly equal to this one. - -#### Env -```cpp -Napi::Env Napi::Value::Env() const; -``` - -Returns the environment that the value is associated with. See -[`Napi::Env`](env.md) for more details about environments. - -#### IsEmpty -```cpp -bool Napi::Value::IsEmpty() const; -``` - -Returns `true` if the value is uninitialized. - -An empty value is invalid, and most attempts to perform an operation on an -empty value will result in an exception. 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 `Napi::Value` -return type may return an empty value to indicate a pending exception. If C++ -exceptions are not being used, callers should check the result of -`Env::IsExceptionPending` before attempting to use the value. - -#### Type -```cpp -napi_valuetype Napi::Value::Type() const; -``` - -Returns the underlying N-API `napi_valuetype` of the value. - -#### IsUndefined -```cpp -bool Napi::Value::IsUndefined() const; -``` - -Returns `true` if the underlying value is a JavaScript `undefined` or `false` -otherwise. - -#### IsNull -```cpp -bool Napi::Value::IsNull() const; -``` - -Returns `true` if the underlying value is a JavaScript `null` or `false` -otherwise. - -#### IsBoolean -```cpp -bool Napi::Value::IsBoolean() const; -``` - -Returns `true` if the underlying value is a JavaScript `true` or JavaScript -`false`, or `false` if the value is not a `Napi::Boolean` value in JavaScript. - -#### IsNumber -```cpp -bool Napi::Value::IsNumber() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::Number` or `false` -otherwise. - -#### IsString -```cpp -bool Napi::Value::IsString() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::String` or `false` -otherwise. - -#### IsSymbol -```cpp -bool Napi::Value::IsSymbol() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::Symbol` or `false` -otherwise. - -#### IsArray -```cpp -bool Napi::Value::IsArray() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::Array` or `false` -otherwise. - -#### IsArrayBuffer -```cpp -bool Napi::Value::IsArrayBuffer() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::ArrayBuffer` or `false` -otherwise. - -#### IsTypedArray -```cpp -bool Napi::Value::IsTypedArray() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::TypedArray` or `false` -otherwise. - -#### IsObject -```cpp -bool Napi::Value::IsObject() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::Object` or `false` -otherwise. - -#### IsFunction -```cpp -bool Napi::Value::IsFunction() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::Function` or `false` -otherwise. - -#### IsPromise -```cpp -bool Napi::Value::IsPromise() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::Promise` or `false` -otherwise. - -#### IsDataView -```cpp -bool Napi::Value::IsDataView() const; -``` - -Returns `true` if the underlying value is a JavaScript `Napi::DataView` or `false` -otherwise. - -#### IsBuffer -```cpp -bool Napi::Value::IsBuffer() const; -``` - -Returns `true` if the underlying value is a Node.js `Napi::Buffer` or `false` -otherwise. - -#### IsExternal -```cpp -bool Napi::Value::IsExternal() const; -``` - -Returns `true` if the underlying value is a N-API external object or `false` -otherwise. - -#### IsDate -```cpp -bool Napi::Value::IsDate() const; -``` - -Returns `true` if the underlying value is a JavaScript `Date` or `false` -otherwise. - -#### ToBoolean -```cpp -Napi::Boolean Napi::Value::ToBoolean() const; -``` - -Returns a `Napi::Boolean` representing the `Napi::Value`. - -This is a wrapper around `napi_coerce_to_boolean`. This will throw a JavaScript -exception if the coercion fails. If C++ exceptions are not being used, callers -should check the result of `Env::IsExceptionPending` before attempting to use -the returned value. - -#### ToNumber -```cpp -Napi::Number Napi::Value::ToNumber() const; -``` - -Returns a `Napi::Number` representing the `Napi::Value`. - -Note: -This can cause script code to be executed according to JavaScript semantics. -This is a wrapper around `napi_coerce_to_number`. This will throw a JavaScript -exception if the coercion fails. If C++ exceptions are not being used, callers -should check the result of `Env::IsExceptionPending` before attempting to use -the returned value. - -#### ToString -```cpp -Napi::String Napi::Value::ToString() const; -``` - -Returns a `Napi::String` representing the `Napi::Value`. - -Note that this can cause script code to be executed according to JavaScript -semantics. This is a wrapper around `napi_coerce_to_string`. This will throw a -JavaScript exception if the coercion fails. If C++ exceptions are not being -used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -#### ToObject -```cpp -Napi::Object Napi::Value::ToObject() const; -``` - -Returns a `Napi::Object` representing the `Napi::Value`. - -This is a wrapper around `napi_coerce_to_object`. This will throw a JavaScript -exception if the coercion fails. If C++ exceptions are not being used, callers -should check the result of `Env::IsExceptionPending` before attempting to use -the returned value. - -## Name - -Names are JavaScript values that can be used as a property name. There are two -specialized types of names supported in Node.js Addon API [`Napi::String`](string.md) -and [`Napi::Symbol`](symbol.md). - -### Methods - -#### Constructor -```cpp -Napi::Name::Name(); -``` - -Returns an empty `Napi::Name`. - -```cpp -Napi::Name::Name(napi_env env, napi_value value); -``` -- `[in] env` - The environment in which to create the array. -- `[in] value` - The primitive to wrap. - -Returns a `Napi::Name` created from the JavaScript primitive. - -Note: -The value is not coerced to a string. - -## Array - -Arrays are native representations of JavaScript Arrays. `Napi::Array` is a wrapper -around `napi_value` representing a JavaScript Array. - -[`Napi::TypedArray`][] and [`Napi::ArrayBuffer`][] correspond to JavaScript data -types such as [`Int32Array`][] and [`ArrayBuffer`][], respectively, that can be -used for transferring large amounts of data from JavaScript to the native side. -An example illustrating the use of a JavaScript-provided `ArrayBuffer` in native -code is available [here](https://github.com/nodejs/node-addon-examples/tree/master/array_buffer_to_native/node-addon-api). - -### Constructor -```cpp -Napi::Array::Array(); -``` - -Returns an empty array. - -If an error occurs, a `Napi::Error` will be thrown. If C++ exceptions are not -being used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -```cpp -Napi::Array::Array(napi_env env, napi_value value); -``` -- `[in] env` - The environment in which to create the array. -- `[in] value` - The primitive to wrap. - -Returns a `Napi::Array` wrapping a `napi_value`. - -If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not -being used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -### Methods - -#### New -```cpp -static Napi::Array Napi::Array::New(napi_env env); -``` -- `[in] env` - The environment in which to create the array. - -Returns a new `Napi::Array`. - -If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not -being used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -#### New - -```cpp -static Napi::Array Napi::Array::New(napi_env env, size_t length); -``` -- `[in] env` - The environment in which to create the array. -- `[in] length` - The length of the array. - -Returns a new `Napi::Array` with the given length. - -If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not -being used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -#### Length -```cpp -uint32_t Napi::Array::Length() const; -``` - -Returns the length of the array. - -Note: -This can execute JavaScript code implicitly according to JavaScript semantics. -If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not -being used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -[`Napi::TypedArray`]: ./typed_array.md -[`Napi::ArrayBuffer`]: ./array_buffer.md -[`Int32Array`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int32Array -[`ArrayBuffer`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer diff --git a/node_modules/node-addon-api/doc/bigint.md b/node_modules/node-addon-api/doc/bigint.md deleted file mode 100644 index cc98104..0000000 --- a/node_modules/node-addon-api/doc/bigint.md +++ /dev/null @@ -1,92 +0,0 @@ -# BigInt - -A JavaScript BigInt value. - -## Methods - -### New - -```cpp -static Napi::BigInt Napi::BigInt::New(Napi::Env env, int64_t value); -``` - - - `[in] env`: The environment in which to construct the `Napi::BigInt` object. - - `[in] value`: The value the JavaScript `BigInt` will contain - -These APIs convert the C `int64_t` and `uint64_t` types to the JavaScript -`BigInt` type. - -```cpp -static Napi::BigInt Napi::BigInt::New(Napi::Env env, - int sign_bit, - size_t word_count, - const uint64_t* words); -``` - - - `[in] env`: The environment in which to construct the `Napi::BigInt` object. - - `[in] sign_bit`: Determines if the resulting `BigInt` will be positive or negative. - - `[in] word_count`: The length of the words array. - - `[in] words`: An array of `uint64_t` little-endian 64-bit words. - -This API converts an array of unsigned 64-bit words into a single `BigInt` -value. - -The resulting `BigInt` is calculated as: (–1)<sup>`sign_bit`</sup> (`words[0]` -× (2<sup>64</sup>)<sup>0</sup> + `words[1]` × (2<sup>64</sup>)<sup>1</sup> + …) - -Returns a new JavaScript `BigInt`. - -### Constructor - -```cpp -Napi::BigInt(); -``` - -Returns a new empty JavaScript `Napi::BigInt`. - -### Int64Value - -```cpp -int64_t Napi::BitInt::Int64Value(bool* lossless) const; -``` - - - `[out] lossless`: Indicates whether the `BigInt` value was converted losslessly. - -Returns the C `int64_t` primitive equivalent of the given JavaScript -`BigInt`. If needed it will truncate the value, setting lossless to false. - -### Uint64Value - -```cpp -uint64_t Napi::BigInt::Uint64Value(bool* lossless) const; -``` - - - `[out] lossless`: Indicates whether the `BigInt` value was converted - losslessly. - -Returns the C `uint64_t` primitive equivalent of the given JavaScript -`BigInt`. If needed it will truncate the value, setting lossless to false. - -### WordCount - -```cpp -size_t Napi::BigInt::WordCount() const; -``` - -Returns the number of words needed to store this `BigInt` value. - -### ToWords - -```cpp -void Napi::BigInt::ToWords(size_t* word_count, int* sign_bit, uint64_t* words); -``` - - - `[out] sign_bit`: Integer representing if the JavaScript `BigInt` is positive - or negative. - - `[in/out] word_count`: Must be initialized to the length of the words array. - Upon return, it will be set to the actual number of words that would be - needed to store this `BigInt`. - - `[out] words`: Pointer to a pre-allocated 64-bit word array. - -Returns a single `BigInt` value into a sign bit, 64-bit little-endian array, -and the number of elements in the array. diff --git a/node_modules/node-addon-api/doc/boolean.md b/node_modules/node-addon-api/doc/boolean.md deleted file mode 100644 index 01b6a4c..0000000 --- a/node_modules/node-addon-api/doc/boolean.md +++ /dev/null @@ -1,64 +0,0 @@ -# Boolean - -`Napi::Boolean` class is a representation of the JavaScript `Boolean` object. The -`Napi::Boolean` class inherits its behavior from the `Napi::Value` class -(for more info see: [`Napi::Value`](value.md)). - -## Methods - -### Constructor - -Creates a new empty instance of an `Napi::Boolean` object. - -```cpp -Napi::Boolean::Boolean(); -``` - -Returns a new _empty_ `Napi::Boolean` object. - -### Contructor - -Creates a new instance of the `Napi::Boolean` object. - -```cpp -Napi::Boolean(napi_env env, napi_value value); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Boolean` object. -- `[in] value`: The `napi_value` which is a handle for a JavaScript `Boolean`. - -Returns a non-empty `Napi::Boolean` object. - -### New - -Initializes a new instance of the `Napi::Boolean` object. - -```cpp -Napi::Boolean Napi::Boolean::New(napi_env env, bool value); -``` -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Boolean` object. -- `[in] value`: The primitive boolean value (`true` or `false`). - -Returns a new instance of the `Napi::Boolean` object. - -### Value - -Converts a `Napi::Boolean` value to a boolean primitive. - -```cpp -bool Napi::Boolean::Value() const; -``` - -Returns the boolean primitive type of the corresponding `Napi::Boolean` object. - -## Operators - -### operator bool - -Converts a `Napi::Boolean` value to a boolean primitive. - -```cpp -Napi::Boolean::operator bool() const; -``` - -Returns the boolean primitive type of the corresponding `Napi::Boolean` object. diff --git a/node_modules/node-addon-api/doc/buffer.md b/node_modules/node-addon-api/doc/buffer.md deleted file mode 100644 index 8f76b20..0000000 --- a/node_modules/node-addon-api/doc/buffer.md +++ /dev/null @@ -1,140 +0,0 @@ -# Buffer - -The `Napi::Buffer` class creates a projection of raw data that can be consumed by -script. - -## Methods - -### New - -Allocates a new `Napi::Buffer` object with a given length. - -```cpp -static Napi::Buffer<T> Napi::Buffer::New(napi_env env, size_t length); -``` - -- `[in] env`: The environment in which to create the `Napi::Buffer` object. -- `[in] length`: The number of `T` elements to allocate. - -Returns a new `Napi::Buffer` object. - -### New - -Wraps the provided external data into a new `Napi::Buffer` object. - -The `Napi::Buffer` object does not assume ownership for the data and expects it to be -valid for the lifetime of the object. Since the `Napi::Buffer` is subject to garbage -collection this overload is only suitable for data which is static and never -needs to be freed. - -```cpp -static Napi::Buffer<T> Napi::Buffer::New(napi_env env, T* data, size_t length); -``` - -- `[in] env`: The environment in which to create the `Napi::Buffer` object. -- `[in] data`: The pointer to the external data to expose. -- `[in] length`: The number of `T` elements in the external data. - -Returns a new `Napi::Buffer` object. - -### New - -Wraps the provided external data into a new `Napi::Buffer` object. - -The `Napi::Buffer` object does not assume ownership for the data and expects it -to be valid for the lifetime of the object. The data can only be freed once the -`finalizeCallback` is invoked to indicate that the `Napi::Buffer` has been released. - -```cpp -template <typename Finalizer> -static Napi::Buffer<T> Napi::Buffer::New(napi_env env, - T* data, - size_t length, - Finalizer finalizeCallback); -``` - -- `[in] env`: The environment in which to create the `Napi::Buffer` object. -- `[in] data`: The pointer to the external data to expose. -- `[in] length`: The number of `T` elements in the external data. -- `[in] finalizeCallback`: The function to be called when the `Napi::Buffer` is - destroyed. It must implement `operator()`, accept a `T*` (which is the - external data pointer), and return `void`. - -Returns a new `Napi::Buffer` object. - -### New - -Wraps the provided external data into a new `Napi::Buffer` object. - -The `Napi::Buffer` object does not assume ownership for the data and expects it to be -valid for the lifetime of the object. The data can only be freed once the -`finalizeCallback` is invoked to indicate that the `Napi::Buffer` has been released. - -```cpp -template <typename Finalizer, typename Hint> -static Napi::Buffer<T> Napi::Buffer::New(napi_env env, - T* data, - size_t length, - Finalizer finalizeCallback, - Hint* finalizeHint); -``` - -- `[in] env`: The environment in which to create the `Napi::Buffer` object. -- `[in] data`: The pointer to the external data to expose. -- `[in] length`: The number of `T` elements in the external data. -- `[in] finalizeCallback`: The function to be called when the `Napi::Buffer` is - destroyed. It must implement `operator()`, accept a `T*` (which is the - external data pointer) and `Hint*`, and return `void`. -- `[in] finalizeHint`: The hint to be passed as the second parameter of the - finalize callback. - -Returns a new `Napi::Buffer` object. - -### Copy - -Allocates a new `Napi::Buffer` object and copies the provided external data into it. - -```cpp -static Napi::Buffer<T> Napi::Buffer::Copy(napi_env env, const T* data, size_t length); -``` - -- `[in] env`: The environment in which to create the `Napi::Buffer` object. -- `[in] data`: The pointer to the external data to copy. -- `[in] length`: The number of `T` elements in the external data. - -Returns a new `Napi::Buffer` object containing a copy of the data. - -### Constructor - -Initializes an empty instance of the `Napi::Buffer` class. - -```cpp -Napi::Buffer::Buffer(); -``` - -### Constructor - -Initializes the `Napi::Buffer` object using an existing Uint8Array. - -```cpp -Napi::Buffer::Buffer(napi_env env, napi_value value); -``` - -- `[in] env`: The environment in which to create the `Napi::Buffer` object. -- `[in] value`: The Uint8Array reference to wrap. - -### Data - -```cpp -T* Napi::Buffer::Data() const; -``` - -Returns a pointer the external data. - -### Length - -```cpp -size_t Napi::Buffer::Length() const; -``` - -Returns the number of `T` elements in the external data. diff --git a/node_modules/node-addon-api/doc/callback_scope.md b/node_modules/node-addon-api/doc/callback_scope.md deleted file mode 100644 index 35f0f8d..0000000 --- a/node_modules/node-addon-api/doc/callback_scope.md +++ /dev/null @@ -1,54 +0,0 @@ -# CallbackScope - -There are cases (for example, resolving promises) where it is necessary to have -the equivalent of the scope associated with a callback in place when making -certain N-API calls. - -## Methods - -### Constructor - -Creates a new callback scope on the stack. - -```cpp -Napi::CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope); -``` - -- `[in] env`: The environment in which to create the `Napi::CallbackScope`. -- `[in] scope`: The pre-existing `napi_callback_scope` or `Napi::CallbackScope`. - -### Constructor - -Creates a new callback scope on the stack. - -```cpp -Napi::CallbackScope::CallbackScope(napi_env env, napi_async_context context); -``` - -- `[in] env`: The environment in which to create the `Napi::CallbackScope`. -- `[in] async_context`: The pre-existing `napi_async_context` or `Napi::AsyncContext`. - -### Destructor - -Deletes the instance of `Napi::CallbackScope` object. - -```cpp -virtual Napi::CallbackScope::~CallbackScope(); -``` - -### Env - -```cpp -Napi::Env Napi::CallbackScope::Env() const; -``` - -Returns the `Napi::Env` associated with the `Napi::CallbackScope`. - -## Operator - -```cpp -Napi::CallbackScope::operator napi_callback_scope() const; -``` - -Returns the N-API `napi_callback_scope` wrapped by the `Napi::CallbackScope` -object. This can be used to mix usage of the C N-API and node-addon-api. diff --git a/node_modules/node-addon-api/doc/callbackinfo.md b/node_modules/node-addon-api/doc/callbackinfo.md deleted file mode 100644 index 0bf4e1a..0000000 --- a/node_modules/node-addon-api/doc/callbackinfo.md +++ /dev/null @@ -1,97 +0,0 @@ -# CallbackInfo - -The object representing the components of the JavaScript request being made. - -The `Napi::CallbackInfo` object is usually created and passed by the Node.js runtime or node-addon-api infrastructure. - -The `Napi::CallbackInfo` object contains the arguments passed by the caller. The number of arguments is returned by the `Length` method. Each individual argument can be accessed using the `operator[]` method. - -The `SetData` and `Data` methods are used to set and retrieve the data pointer contained in the `Napi::CallbackInfo` object. - -## Methods - -### Constructor - -```cpp -Napi::CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::CallbackInfo` object. -- `[in] info`: The `napi_callback_info` data structure from which to construct the `Napi::CallbackInfo` object. - -### Env - -```cpp -Napi::Env Napi::CallbackInfo::Env() const; -``` - -Returns the `Env` object in which the request is being made. - -### NewTarget - -```cpp -Napi::Value Napi::CallbackInfo::NewTarget() const; -``` - -Returns the `new.target` value of the constructor call. If the function that was invoked (and for which the `Napi::NCallbackInfo` was passed) is not a constructor call, a call to `IsEmpty()` on the returned value returns true. - -### IsConstructCall - -```cpp -bool Napi::CallbackInfo::IsConstructCall() const; -``` - -Returns a `bool` indicating if the function that was invoked (and for which the `Napi::CallbackInfo` was passed) is a constructor call. - -### Length - -```cpp -size_t Napi::CallbackInfo::Length() const; -``` - -Returns the number of arguments passed in the `Napi::CallbackInfo` object. - -### operator [] - -```cpp -const Napi::Value operator [](size_t index) const; -``` - -- `[in] index`: The zero-based index of the requested argument. - -Returns a `Napi::Value` object containing the requested argument. - -### This - -```cpp -Napi::Value Napi::CallbackInfo::This() const; -``` - -Returns the JavaScript `this` value for the call - -### Data - -```cpp -void* Napi::CallbackInfo::Data() const; -``` - -Returns the data pointer for the callback. - -### SetData - -```cpp -void Napi::CallbackInfo::SetData(void* data); -``` - -- `[in] data`: The new data pointer to associate with this `Napi::CallbackInfo` object. - -Returns `void`. - -### Not documented here - -```cpp -Napi::CallbackInfo::~CallbackInfo(); -// Disallow copying to prevent multiple free of _dynamicArgs -Napi::CallbackInfo::CallbackInfo(CallbackInfo const &) = delete; -void Napi::CallbackInfo::operator=(CallbackInfo const &) = delete; -``` diff --git a/node_modules/node-addon-api/doc/checker-tool.md b/node_modules/node-addon-api/doc/checker-tool.md deleted file mode 100644 index 499d3ab..0000000 --- a/node_modules/node-addon-api/doc/checker-tool.md +++ /dev/null @@ -1,32 +0,0 @@ -# Checker Tool - -**node-addon-api** provides a [checker tool][] that will inspect a given -directory tree, identifying all Node.js native addons therein, and further -indicating for each addon whether it is an N-API addon. - -## To use the checker tool: - - 1. Install the application with `npm install`. - - 2. If the application does not depend on **node-addon-api**, copy the - checker tool into the application's directory. - - 3. If the application does not depend on **node-addon-api**, run the checker - tool from the application's directory: - - ```sh - node ./check-napi.js - ``` - - Otherwise, the checker tool can be run from the application's - `node_modules/` subdirectory: - - ```sh - node ./node_modules/node-addon-api/tools/check-napi.js - ``` - -The tool accepts the root directory from which to start checking for Node.js -native addons as a single optional command line parameter. If ommitted it will -start checking from the current directory (`.`). - -[checker tool]: ../tools/check-napi.js diff --git a/node_modules/node-addon-api/doc/class_property_descriptor.md b/node_modules/node-addon-api/doc/class_property_descriptor.md deleted file mode 100644 index bb492de..0000000 --- a/node_modules/node-addon-api/doc/class_property_descriptor.md +++ /dev/null @@ -1,117 +0,0 @@ -# Class property and descriptor - -Property descriptor for use with `Napi::ObjectWrap::DefineClass()`. -This is different from the standalone `Napi::PropertyDescriptor` because it is -specific to each `Napi::ObjectWrap<T>` subclass. -This prevents using descriptors from a different class when defining a new class -(preventing the callbacks from having incorrect `this` pointers). - -## Example - -```cpp -#include <napi.h> - -class Example : public Napi::ObjectWrap<Example> { - public: - static Napi::Object Init(Napi::Env env, Napi::Object exports); - Example(const Napi::CallbackInfo &info); - - private: - static Napi::FunctionReference constructor; - double _value; - Napi::Value GetValue(const Napi::CallbackInfo &info); - void SetValue(const Napi::CallbackInfo &info, const Napi::Value &value); -}; - -Napi::Object Example::Init(Napi::Env env, Napi::Object exports) { - Napi::Function func = DefineClass(env, "Example", { - // Register a class instance accessor with getter and setter functions. - InstanceAccessor("value", &Example::GetValue, &Example::SetValue), - // We can also register a readonly accessor by passing nullptr as the setter. - InstanceAccessor("readOnlyProp", &Example::GetValue, nullptr) - }); - - constructor = Napi::Persistent(func); - constructor.SuppressDestruct(); - exports.Set("Example", func); - - return exports; -} - -Example::Example(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Example>(info) { - Napi::Env env = info.Env(); - // ... - Napi::Number value = info[0].As<Napi::Number>(); - this->_value = value.DoubleValue(); -} - -Napi::FunctionReference Example::constructor; - -Napi::Value Example::GetValue(const Napi::CallbackInfo &info) { - Napi::Env env = info.Env(); - return Napi::Number::New(env, this->_value); -} - -void Example::SetValue(const Napi::CallbackInfo &info, const Napi::Value &value) { - Napi::Env env = info.Env(); - // ... - Napi::Number arg = value.As<Napi::Number>(); - this->_value = arg.DoubleValue(); -} - -// Initialize native add-on -Napi::Object Init (Napi::Env env, Napi::Object exports) { - Example::Init(env, exports); - return exports; -} - -// Register and initialize native add-on -NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) -``` - -The above code can be used from JavaScript as follows: - -```js -'use strict'; - -const { Example } = require('bindings')('addon'); - -const example = new Example(11); -console.log(example.value); -// It prints 11 -example.value = 19; -console.log(example.value); -// It prints 19 -example.readOnlyProp = 500; -console.log(example.readOnlyProp); -// Unchanged. It prints 19 -``` - -## Methods - -### Constructor - -Creates new instance of `Napi::ClassPropertyDescriptor` descriptor object. - -```cpp -Napi::ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} -``` - -- `[in] desc`: The `napi_property_descriptor` - -Returns new instance of `Napi::ClassPropertyDescriptor` that is used as property descriptor -inside the `Napi::ObjectWrap<T>` class. - -### Operator - -```cpp -operator napi_property_descriptor&() { return _desc; } -``` - -Returns the original N-API `napi_property_descriptor` wrapped inside the `Napi::ClassPropertyDescriptor` - -```cpp -operator const napi_property_descriptor&() const { return _desc; } -``` - -Returns the original N-API `napi_property_descriptor` wrapped inside the `Napi::ClassPropertyDescriptor` diff --git a/node_modules/node-addon-api/doc/cmake-js.md b/node_modules/node-addon-api/doc/cmake-js.md deleted file mode 100644 index 08cd3ea..0000000 --- a/node_modules/node-addon-api/doc/cmake-js.md +++ /dev/null @@ -1,68 +0,0 @@ -# CMake.js - -[**CMake.js**](https://github.com/cmake-js/cmake-js) is a build tool that allow native addon developers to compile their -C or C++ code into executable form. It works like **[node-gyp](node-gyp.md)** but -instead of Google's [**gyp**](https://gyp.gsrc.io) tool it is based on the [**CMake**](https://cmake.org) build system. - -## Quick Start - -### Install CMake - -CMake.js requires that CMake be installed. Installers for a variety of platforms can be found on the [CMake website](https://cmake.org). - -### Install CMake.js - -For developers, CMake.js is typically installed as a global package: - -```bash -npm install -g cmake-js -cmake-js --help -``` - -> For *users* of your native addon, CMake.js should be configured as a dependency in your `package.json` as described in the [CMake.js documentation](https://github.com/cmake-js/cmake-js). - -### CMakeLists.txt - -Your project will require a `CMakeLists.txt` file. The [CMake.js README file](https://github.com/cmake-js/cmake-js#usage) shows what's necessary. - -### NAPI_VERSION - -When building N-API addons, it's crucial to specify the N-API version your code is designed to work with. With CMake.js, this information is specified in the `CMakeLists.txt` file: - -``` -add_definitions(-DNAPI_VERSION=3) -``` - -Since N-API is ABI-stable, your N-API addon will work, without recompilation, with the N-API version you specify in `NAPI_VERSION` and all subsequent N-API versions. - -In the absence of a need for features available only in a specific N-API version, version 3 is a good choice as it is the version of N-API that was active when N-API left experimental status. - -### NAPI_EXPERIMENTAL - -The following line in the `CMakeLists.txt` file will enable N-API experimental features if your code requires them: - -``` -add_definitions(-DNAPI_EXPERIMENTAL) -``` - -### node-addon-api - -If your N-API native add-on uses the optional [**node-addon-api**](https://github.com/nodejs/node-addon-api#node-addon-api-module) C++ wrapper, the `CMakeLists.txt` file requires additional configuration information as described on the [CMake.js README file](https://github.com/cmake-js/cmake-js#n-api-and-node-addon-api). - -## Example - -A working example of an N-API native addon built using CMake.js can be found on the [node-addon-examples repository](https://github.com/nodejs/node-addon-examples/tree/master/build_with_cmake#building-n-api-addons-using-cmakejs). - -## **CMake** Reference - - - [Installation](https://github.com/cmake-js/cmake-js#installation) - - [How to use](https://github.com/cmake-js/cmake-js#usage) - - [Using N-API and node-addon-api](https://github.com/cmake-js/cmake-js#n-api-and-node-addon-api) - - [Tutorials](https://github.com/cmake-js/cmake-js#tutorials) - - [Use case in the works - ArrayFire.js](https://github.com/cmake-js/cmake-js#use-case-in-the-works---arrayfirejs) - -Sometimes finding the right settings is not easy so to accomplish at most -complicated task please refer to: - -- [CMake documentation](https://cmake.org/) -- [CMake.js wiki](https://github.com/cmake-js/cmake-js/wiki) diff --git a/node_modules/node-addon-api/doc/conversion-tool.md b/node_modules/node-addon-api/doc/conversion-tool.md deleted file mode 100644 index 3b50b9c..0000000 --- a/node_modules/node-addon-api/doc/conversion-tool.md +++ /dev/null @@ -1,28 +0,0 @@ -# Conversion Tool - -To make the migration to **node-addon-api** easier, we have provided a script to -help complete some tasks. - -## To use the conversion script: - - 1. Go to your module directory - -``` -cd [module_path] -``` - - 2. Install node-addon-api module - -``` -npm install node-addon-api -``` - 3. Run node-addon-api conversion script - -``` -node ./node_modules/node-addon-api/tools/conversion.js ./ -``` - - 4. While this script makes conversion easier, it still cannot fully convert -the module. The next step is to try to build the module and complete the -remaining conversions necessary to allow it to compile and pass all of the -module's tests.
\ No newline at end of file diff --git a/node_modules/node-addon-api/doc/creating_a_release.md b/node_modules/node-addon-api/doc/creating_a_release.md deleted file mode 100644 index bc9a859..0000000 --- a/node_modules/node-addon-api/doc/creating_a_release.md +++ /dev/null @@ -1,62 +0,0 @@ -# Creating a release - -Only collaborators in npm for **node-addon-api** can create releases. -If you want to be able to do releases ask one of the existing -collaborators to add you. If necessary you can ask the build -Working Group who manages the Node.js npm user to add you if -there are no other active collaborators. - -## Prerequisites - -Before to start creating a new release check if you have installed the following -tools: - -* [Changelog maker](https://www.npmjs.com/package/changelog-maker) - -If not please follow the instruction reported in the tool's documentation to -install it. - -## Publish new release - -These are the steps to follow to create a new release: - -* Open an issue in the **node-addon-api** repo documenting the intent to create a -new release. Give people some time to comment or suggest PRs that should land first. - -* Validate all tests pass by running npm test on master. - -* Update the version in **package.json** appropriately. - -* Update the [README.md](https://github.com/nodejs/node-addon-api/blob/master/README.md) -to show the new version as the latest. - -* Generate the changelog for the new version using **changelog maker** tool. From -the route folder of the repo launch the following command: - - ```bash - > changelog-maker - ``` -* Use the output generated by **changelog maker** to pdate the [CHANGELOG.md](https://github.com/nodejs/node-addon-api/blob/master/CHANGELOG.md) -following the style used in publishing the previous release. - -* Add any new contributors to the "contributors" section in the package.json - -* Validate all tests pass by running npm test on master. - -* Use **[CI](https://ci.nodejs.org/view/x%20-%20Abi%20stable%20module%20API/job/node-test-node-addon-api/)** -to validate tests pass for latest 11, 10, 8, 6 releases (note there are still some issues on SmartOS and -Windows in the testing). - -* Do a clean checkout of node-addon-api. - -* Login and then run `npm publish`. - -* Create a release in Github (look at existing releases for an example). - -* Validate that you can run `npm install node-addon-api` successfully -and that the correct version is installed. - -* Comment on the issue opened in the first step that the release has been created -and close the issue. - -* Tweet that the release has been created. diff --git a/node_modules/node-addon-api/doc/dataview.md b/node_modules/node-addon-api/doc/dataview.md deleted file mode 100644 index 64b865b..0000000 --- a/node_modules/node-addon-api/doc/dataview.md +++ /dev/null @@ -1,244 +0,0 @@ -# DataView - -The `Napi::DataView` class corresponds to the -[JavaScript `DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) -class. - -## Methods - -### New - -Allocates a new `Napi::DataView` instance with a given `Napi::ArrayBuffer`. - -```cpp -static Napi::DataView Napi::DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer); -``` - -- `[in] env`: The environment in which to create the `Napi::DataView` instance. -- `[in] arrayBuffer` : `Napi::ArrayBuffer` underlying the `Napi::DataView`. - -Returns a new `Napi::DataView` instance. - -### New - -Allocates a new `Napi::DataView` instance with a given `Napi::ArrayBuffer`. - -```cpp -static Napi::DataView Napi::DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset); -``` - -- `[in] env`: The environment in which to create the `Napi::DataView` instance. -- `[in] arrayBuffer` : `Napi::ArrayBuffer` underlying the `Napi::DataView`. -- `[in] byteOffset` : The byte offset within the `Napi::ArrayBuffer` from which to start projecting the `Napi::DataView`. - -Returns a new `Napi::DataView` instance. - -### New - -Allocates a new `Napi::DataView` instance with a given `Napi::ArrayBuffer`. - -```cpp -static Napi::DataView Napi::DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset, size_t byteLength); -``` - -- `[in] env`: The environment in which to create the `Napi::DataView` instance. -- `[in] arrayBuffer` : `Napi::ArrayBuffer` underlying the `Napi::DataView`. -- `[in] byteOffset` : The byte offset within the `Napi::ArrayBuffer` from which to start projecting the `Napi::DataView`. -- `[in] byteLength` : Number of elements in the `Napi::DataView`. - -Returns a new `Napi::DataView` instance. - -### Constructor - -Initializes an empty instance of the `Napi::DataView` class. - -```cpp -Napi::DataView(); -``` - -### Constructor - -Initializes a wrapper instance of an existing `Napi::DataView` instance. - -```cpp -Napi::DataView(napi_env env, napi_value value); -``` - -- `[in] env`: The environment in which to create the `Napi::DataView` instance. -- `[in] value`: The `Napi::DataView` reference to wrap. - -### ArrayBuffer - -```cpp -Napi::ArrayBuffer Napi::DataView::ArrayBuffer() const; -``` - -Returns the backing array buffer. - -### ByteOffset - -```cpp -size_t Napi::DataView::ByteOffset() const; -``` - -Returns the offset into the `Napi::DataView` where the array starts, in bytes. - -### ByteLength - -```cpp -size_t Napi::DataView::ByteLength() const; -``` - -Returns the length of the array, in bytes. - -### GetFloat32 - -```cpp -float Napi::DataView::GetFloat32(size_t byteOffset) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. - -Returns a signed 32-bit float (float) at the specified byte offset from the start of the `Napi::DataView`. - -### GetFloat64 - -```cpp -double Napi::DataView::GetFloat64(size_t byteOffset) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. - -Returns a signed 64-bit float (double) at the specified byte offset from the start of the `Napi::DataView`. - -### GetInt8 - -```cpp -int8_t Napi::DataView::GetInt8(size_t byteOffset) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. - -Returns a signed 8-bit integer (byte) at the specified byte offset from the start of the `Napi::DataView`. - -### GetInt16 - -```cpp -int16_t Napi::DataView::GetInt16(size_t byteOffset) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. - -Returns a signed 16-bit integer (short) at the specified byte offset from the start of the `Napi::DataView`. - -### GetInt32 - -```cpp -int32_t Napi::DataView::GetInt32(size_t byteOffset) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. - -Returns a signed 32-bit integer (long) at the specified byte offset from the start of the `Napi::DataView`. - -### GetUint8 - -```cpp -uint8_t Napi::DataView::GetUint8(size_t byteOffset) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. - -Returns a unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the `Napi::DataView`. - -### GetUint16 - -```cpp -uint16_t Napi::DataView::GetUint16(size_t byteOffset) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. - -Returns a unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the `Napi::DataView`. - -### GetUint32 - -```cpp -uint32_t Napi::DataView::GetUint32(size_t byteOffset) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. - -Returns a unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the `Napi::DataView`. - -### SetFloat32 - -```cpp -void Napi::DataView::SetFloat32(size_t byteOffset, float value) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. -- `[in] value`: The value to set. - -### SetFloat64 - -```cpp -void Napi::DataView::SetFloat64(size_t byteOffset, double value) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. -- `[in] value`: The value to set. - -### SetInt8 - -```cpp -void Napi::DataView::SetInt8(size_t byteOffset, int8_t value) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. -- `[in] value`: The value to set. - -### SetInt16 - -```cpp -void Napi::DataView::SetInt16(size_t byteOffset, int16_t value) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. -- `[in] value`: The value to set. - -### SetInt32 - -```cpp -void Napi::DataView::SetInt32(size_t byteOffset, int32_t value) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. -- `[in] value`: The value to set. - -### SetUint8 - -```cpp -void Napi::DataView::SetUint8(size_t byteOffset, uint8_t value) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. -- `[in] value`: The value to set. - -### SetUint16 - -```cpp -void Napi::DataView::SetUint16(size_t byteOffset, uint16_t value) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. -- `[in] value`: The value to set. - -### SetUint32 - -```cpp -void Napi::DataView::SetUint32(size_t byteOffset, uint32_t value) const; -``` - -- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data. -- `[in] value`: The value to set. diff --git a/node_modules/node-addon-api/doc/date.md b/node_modules/node-addon-api/doc/date.md deleted file mode 100644 index 959b4b9..0000000 --- a/node_modules/node-addon-api/doc/date.md +++ /dev/null @@ -1,68 +0,0 @@ -# Date - -`Napi::Date` class is a representation of the JavaScript `Date` object. The -`Napi::Date` class inherits its behavior from `Napi::Value` class -(for more info see [`Napi::Value`](value.md)) - -## Methods - -### Constructor - -Creates a new _empty_ instance of a `Napi::Date` object. - -```cpp -Napi::Date::Date(); -``` - -Creates a new _non-empty_ instance of a `Napi::Date` object. - -```cpp -Napi::Date::Date(napi_env env, napi_value value); -``` - - - `[in] env`: The environment in which to construct the `Napi::Date` object. - - `[in] value`: The `napi_value` which is a handle for a JavaScript `Date`. - -### New - -Creates a new instance of a `Napi::Date` object. - -```cpp -static Napi::Date Napi::Date::New(Napi::Env env, double value); -``` - - - `[in] env`: The environment in which to construct the `Napi::Date` object. - - `[in] value`: The time value the JavaScript `Date` will contain represented - as the number of milliseconds since 1 January 1970 00:00:00 UTC. - -Returns a new instance of `Napi::Date` object. - -### ValueOf - -```cpp -double Napi::Date::ValueOf() const; -``` - -Returns the time value as `double` primitive represented as the number of - milliseconds since 1 January 1970 00:00:00 UTC. - -## Operators - -### operator double - -Converts a `Napi::Date` value to a `double` primitive. - -```cpp -Napi::Date::operator double() const; -``` - -### Example - -The following shows an example of casting a `Napi::Date` value to a `double` - primitive. - -```cpp -double operatorVal = Napi::Date::New(Env(), 0); // Napi::Date to double -// or -auto instanceVal = info[0].As<Napi::Date>().ValueOf(); -``` diff --git a/node_modules/node-addon-api/doc/env.md b/node_modules/node-addon-api/doc/env.md deleted file mode 100644 index 9bde741..0000000 --- a/node_modules/node-addon-api/doc/env.md +++ /dev/null @@ -1,63 +0,0 @@ -# Env - -The opaque data structure containing the environment in which the request is being run. - -The Env object is usually created and passed by the Node.js runtime or node-addon-api infrastructure. - -## Methods - -### Constructor - -```cpp -Napi::Env::Env(napi_env env); -``` - -- `[in] env`: The `napi_env` environment from which to construct the `Napi::Env` object. - -### napi_env - -```cpp -operator napi_env() const; -``` - -Returns the `napi_env` opaque data structure representing the environment. - -### Global - -```cpp -Napi::Object Napi::Env::Global() const; -``` - -Returns the `Napi::Object` representing the environment's JavaScript Global Object. - -### Undefined - -```cpp -Napi::Value Napi::Env::Undefined() const; -``` - -Returns the `Napi::Value` representing the environment's JavaScript Undefined Object. - -### Null - -```cpp -Napi::Value Napi::Env::Null() const; -``` - -Returns the `Napi::Value` representing the environment's JavaScript Null Object. - -### IsExceptionPending - -```cpp -bool Napi::Env::IsExceptionPending() const; -``` - -Returns a `bool` indicating if an exception is pending in the environment. - -### GetAndClearPendingException - -```cpp -Napi::Error Napi::Env::GetAndClearPendingException(); -``` - -Returns an `Napi::Error` object representing the environment's pending exception, if any. diff --git a/node_modules/node-addon-api/doc/error.md b/node_modules/node-addon-api/doc/error.md deleted file mode 100644 index 1526bdd..0000000 --- a/node_modules/node-addon-api/doc/error.md +++ /dev/null @@ -1,115 +0,0 @@ -# Error - -The `Napi::Error` class is a representation of the JavaScript `Error` object that is thrown -when runtime errors occur. The Error object can also be used as a base object for -user-defined exceptions. - -The `Napi::Error` class is a persistent reference to a JavaScript error object thus -inherits its behavior from the `Napi::ObjectReference` class (for more info see: [`Napi::ObjectReference`](object_reference.md)). - -If C++ exceptions are enabled (for more info see: [Setup](setup.md)), then the -`Napi::Error` class extends `std::exception` and enables integrated -error-handling for C++ exceptions and JavaScript exceptions. - -For more details about error handling refer to the section titled [Error handling](error_handling.md). - -## Methods - -### New - -Creates empty instance of an `Napi::Error` object for the specified environment. - -```cpp -Napi::Error::New(Napi::Env env); -``` - -- `[in] env`: The environment in which to construct the `Napi::Error` object. - -Returns an instance of `Napi::Error` object. - -### New - -Creates instance of an `Napi::Error` object. - -```cpp -Napi::Error::New(Napi::Env env, const char* message); -``` - -- `[in] env`: The environment in which to construct the `Napi::Error` object. -- `[in] message`: Null-terminated string to be used as the message for the `Napi::Error`. - -Returns instance of an `Napi::Error` object. - -### New - -Creates instance of an `Napi::Error` object - -```cpp -Napi::Error::New(Napi::Env env, const std::string& message); -``` - -- `[in] env`: The environment in which to construct the `Napi::Error` object. -- `[in] message`: Reference string to be used as the message for the `Napi::Error`. - -Returns instance of an `Napi::Error` object. - -### Fatal - -In case of an unrecoverable error in a native module, a fatal error can be thrown -to immediately terminate the process. - -```cpp -static NAPI_NO_RETURN void Napi::Error::Fatal(const char* location, const char* message); -``` - -The function call does not return, the process will be terminated. - -### Constructor - -Creates empty instance of an `Napi::Error`. - -```cpp -Napi::Error::Error(); -``` - -Returns an instance of `Napi::Error` object. - -### Constructor - -Initializes an `Napi::Error` instance from an existing JavaScript error object. - -```cpp -Napi::Error::Error(napi_env env, napi_value value); -``` - -- `[in] env`: The environment in which to construct the error object. -- `[in] value`: The `Napi::Error` reference to wrap. - -Returns instance of an `Napi::Error` object. - -### Message - -```cpp -std::string& Napi::Error::Message() const NAPI_NOEXCEPT; -``` - -Returns the reference to the string that represent the message of the error. - -### ThrowAsJavaScriptException - -Throw the error as JavaScript exception. - -```cpp -void Napi::Error::ThrowAsJavaScriptException() const; -``` - -Throws the error as a JavaScript exception. - -### what - -```cpp -const char* Napi::Error::what() const NAPI_NOEXCEPT override; -``` - -Returns a pointer to a null-terminated string that is used to identify the -exception. This method can be used only if the exception mechanism is enabled. diff --git a/node_modules/node-addon-api/doc/error_handling.md b/node_modules/node-addon-api/doc/error_handling.md deleted file mode 100644 index 9a0ef34..0000000 --- a/node_modules/node-addon-api/doc/error_handling.md +++ /dev/null @@ -1,186 +0,0 @@ -# Error handling - -Error handling represents one of the most important considerations when -implementing a Node.js native add-on. When an error occurs in your C++ code you -have to handle and dispatch it correctly. **node-addon-api** uses return values and -JavaScript exceptions for error handling. You can choose return values or -exception handling based on the mechanism that works best for your add-on. - -The `Napi::Error` is a persistent reference (for more info see: [`Napi::ObjectReference`](object_reference.md)) -to a JavaScript error object. Use of this class depends on whether C++ -exceptions are enabled at compile time. - -If C++ exceptions are enabled (for more info see: [Setup](setup.md)), then the -`Napi::Error` class extends `std::exception` and enables integrated -error-handling for C++ exceptions and JavaScript exceptions. - -The following sections explain the approach for each case: - -- [Handling Errors With C++ Exceptions](#exceptions) -- [Handling Errors Without C++ Exceptions](#noexceptions) - -<a name="exceptions"></a> - -In most cases when an error occurs, the addon should do whatever clean is possible -and then return to JavaScript so that they error can be propagated. In less frequent -cases the addon may be able to recover from the error, clear the error and then -continue. - -## Handling Errors With C++ Exceptions - -When C++ exceptions are enabled try/catch can be used to catch exceptions thrown -from calls to JavaScript and then they can either be handled or rethrown before -returning from a native method. - -If a node-addon-api call fails without executing any JavaScript code (for example due to -an invalid argument), then node-addon-api automatically converts and throws -the error as a C++ exception of type `Napi::Error`. - -If a JavaScript function called by C++ code via node-addon-api throws a JavaScript -exception, then node-addon-api automatically converts and throws it as a C++ -exception of type `Napi:Error` on return from the JavaScript code to the native -method. - -If a C++ exception of type `Napi::Error` escapes from a N-API C++ callback, then -the N-API wrapper automatically converts and throws it as a JavaScript exception. - -On return from a native method, node-addon-api will automatically convert a pending C++ -exception to a JavaScript exception. - -When C++ exceptions are enabled try/catch can be used to catch exceptions thrown -from calls to JavaScript and then they can either be handled or rethrown before -returning from a native method. - -## Examples with C++ exceptions enabled - -### Throwing a C++ exception - -```cpp -Env env = ... -throw Napi::Error::New(env, "Example exception"); -// other C++ statements -// ... -``` - -The statements following the throw statement 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 returning to JavaScript. - -### Propagating a N-API C++ exception - -```cpp -Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>(); -Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); -// other C++ statements -// ... -``` - -The C++ statements following the call to the JavaScript function 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 returning to JavaScript. - -### Handling a N-API C++ exception - -```cpp -Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>(); -Napi::Value result; -try { - result = jsFunctionThatThrows({ arg1, arg2 }); -} catch (const Error& e) { - cerr << "Caught JavaScript exception: " + e.what(); -} -``` - -Since the exception was caught here, it will not be propagated as a JavaScript -exception. - -<a name="noexceptions"></a> - -## Handling Errors Without C++ Exceptions - -If C++ exceptions are disabled (for more info see: [Setup](setup.md)), then the -`Napi::Error` class does not extend `std::exception`. This means that any calls to -node-addon-api function do not throw a C++ exceptions. Instead, it raises -_pending_ JavaScript exceptions and returns an _empty_ `Napi::Value`. -The calling code should check `env.IsExceptionPending()` before attempting to use a -returned value, and may use methods on the `Napi::Env` class -to check for, get, and clear a pending JavaScript exception (for more info see: [Env](env.md)). -If the pending exception is not cleared, it will be thrown when the native code -returns to JavaScript. - -## Examples with C++ exceptions disabled - -### Throwing a JS exception - -```cpp -Napi::Env env = ... -Napi::Error::New(env, "Example exception").ThrowAsJavaScriptException(); -return; -``` - -After throwing a JavaScript exception, the code should generally return -immediately from the native callback, after performing any necessary cleanup. - -### Propagating a N-API JS exception - -```cpp -Napi::Env env = ... -Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>(); -Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); -if (env.IsExceptionPending()) { - Error e = env.GetAndClearPendingException(); - return e.Value(); -} -``` - -If env.IsExceptionPending() returns true 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. - -### Handling a N-API JS exception - -```cpp -Napi::Env env = ... -Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>(); -Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); -if (env.IsExceptionPending()) { - 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. - -## Calling N-API directly from a **node-addon-api** addon - -**node-addon-api** provides macros for throwing errors in response to non-OK -`napi_status` results when calling [N-API](https://nodejs.org/docs/latest/api/n-api.html) -functions from within a native addon. These macros are defined differently -depending on whether C++ exceptions are enabled or not, but are available for -use in either case. - -### `NAPI_THROW(e, ...)` - -This macro accepts a `Napi::Error`, throws it, and returns the value given as -the last parameter. If C++ exceptions are enabled (by defining -`NAPI_CPP_EXCEPTIONS` during the build), the return value will be ignored. - -### `NAPI_THROW_IF_FAILED(env, status, ...)` - -This macro accepts a `Napi::Env` and a `napi_status`. It constructs an error -from the `napi_status`, throws it, and returns the value given as the last -parameter. If C++ exceptions are enabled (by defining `NAPI_CPP_EXCEPTIONS` -during the build), the return value will be ignored. - -### `NAPI_THROW_IF_FAILED_VOID(env, status)` - -This macro accepts a `Napi::Env` and a `napi_status`. It constructs an error -from the `napi_status`, throws it, and returns. - -### `NAPI_FATAL_IF_FAILED(status, location, message)` - -This macro accepts a `napi_status`, a C string indicating the location where the -error occurred, and a second C string for the message to display. diff --git a/node_modules/node-addon-api/doc/escapable_handle_scope.md b/node_modules/node-addon-api/doc/escapable_handle_scope.md deleted file mode 100644 index 978aab3..0000000 --- a/node_modules/node-addon-api/doc/escapable_handle_scope.md +++ /dev/null @@ -1,82 +0,0 @@ -# EscapableHandleScope - -The `Napi::EscapableHandleScope` class is used to manage the lifetime of object handles -which are created through the use of node-addon-api. These handles -keep an object alive in the heap in order to ensure that the objects -are not collected by the garbage collector while native code is using them. -A handle may be created when any new node-addon-api Value or one -of its subclasses is created or returned. - -The `Napi::EscapableHandleScope` is a special type of `Napi::HandleScope` -which allows a single handle to be "promoted" to an outer scope. - -For more details refer to the section titled -[Object lifetime management](object_lifetime_management.md). - -## Methods - -### Constructor - -Creates a new escapable handle scope. - -```cpp -Napi::EscapableHandleScope Napi::EscapableHandleScope::New(Napi:Env env); -``` - -- `[in] Env`: The environment in which to construct the `Napi::EscapableHandleScope` object. - -Returns a new `Napi::EscapableHandleScope` - -### Constructor - -Creates a new escapable handle scope. - -```cpp -Napi::EscapableHandleScope Napi::EscapableHandleScope::New(napi_env env, napi_handle_scope scope); -``` - -- `[in] env`: napi_env in which the scope passed in was created. -- `[in] scope`: pre-existing napi_handle_scope. - -Returns a new `Napi::EscapableHandleScope` instance which wraps the -napi_escapable_handle_scope handle passed in. This can be used -to mix usage of the C N-API and node-addon-api. - -operator EscapableHandleScope::napi_escapable_handle_scope - -```cpp -operator Napi::EscapableHandleScope::napi_escapable_handle_scope() const -``` - -Returns the N-API napi_escapable_handle_scope wrapped by the `Napi::EscapableHandleScope` object. -This can be used to mix usage of the C N-API and node-addon-api by allowing -the class to be used be converted to a napi_escapable_handle_scope. - -### Destructor -```cpp -Napi::EscapableHandleScope::~EscapableHandleScope(); -``` - -Deletes the `Napi::EscapableHandleScope` instance and allows any objects/handles created -in the scope to be collected by the garbage collector. There is no -guarantee as to when the gargbage collector will do this. - -### Escape - -```cpp -napi::Value Napi::EscapableHandleScope::Escape(napi_value escapee); -``` - -- `[in] escapee`: Napi::Value or napi_env to promote to the outer scope - -Returns `Napi::Value` which can be used in the outer scope. This method can -be called at most once on a given `Napi::EscapableHandleScope`. If it is called -more than once an exception will be thrown. - -### Env - -```cpp -Napi::Env Napi::EscapableHandleScope::Env() const; -``` - -Returns the `Napi::Env` associated with the `Napi::EscapableHandleScope`. diff --git a/node_modules/node-addon-api/doc/external.md b/node_modules/node-addon-api/doc/external.md deleted file mode 100644 index 4022b61..0000000 --- a/node_modules/node-addon-api/doc/external.md +++ /dev/null @@ -1,59 +0,0 @@ -# External (template) - -The `Napi::External` template class implements the ability to create a `Napi::Value` object with arbitrary C++ data. It is the user's responsibility to manage the memory for the arbitrary C++ data. - -`Napi::External` objects can be created with an optional Finalizer function and optional Hint value. The Finalizer function, if specified, is called when your `Napi::External` object is released by Node's garbage collector. It gives your code the opportunity to free any dynamically created data. If you specify a Hint value, it is passed to your Finalizer function. - -## Methods - -### New - -```cpp -template <typename T> -static Napi::External Napi::External::New(napi_env env, T* data); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object. -- `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object. - -Returns the created `Napi::External<T>` object. - -### New - -```cpp -template <typename T> -static Napi::External Napi::External::New(napi_env env, - T* data, - Finalizer finalizeCallback); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object. -- `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object. -- `[in] finalizeCallback`: A function called when the `Napi::External` object is released by the garbage collector accepting a T* and returning void. - -Returns the created `Napi::External<T>` object. - -### New - -```cpp -template <typename T> -static Napi::External Napi::External::New(napi_env env, - T* data, - Finalizer finalizeCallback, - Hint* finalizeHint); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object. -- `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object. -- `[in] finalizeCallback`: A function called when the `Napi::External` object is released by the garbage collector accepting T* and Hint* parameters and returning void. -- `[in] finalizeHint`: A hint value passed to the `finalizeCallback` function. - -Returns the created `Napi::External<T>` object. - -### Data - -```cpp -T* Napi::External::Data() const; -``` - -Returns a pointer to the arbitrary C++ data held by the `Napi::External` object. diff --git a/node_modules/node-addon-api/doc/function.md b/node_modules/node-addon-api/doc/function.md deleted file mode 100644 index efc7ed4..0000000 --- a/node_modules/node-addon-api/doc/function.md +++ /dev/null @@ -1,294 +0,0 @@ -# Function - -The `Napi::Function` class provides a set of methods for creating a function object in -native code that can later be called from JavaScript. The created function is not -automatically visible from JavaScript. Instead it needs to be part of the add-on's -module exports or be returned by one of the module's exported functions. - -In addition the `Napi::Function` class also provides methods that can be used to call -functions that were created in JavaScript and passed to the native add-on. - -The `Napi::Function` class inherits its behavior from the `Napi::Object` class (for more info -see: [`Napi::Object`](object.md)). - -## Example - -```cpp -#include <napi.h> - -using namespace Napi; - -Value Fn(const CallbackInfo& info) { - Env env = info.Env(); - // ... - return String::New(env, "Hello World"); -} - -Object Init(Env env, Object exports) { - exports.Set(String::New(env, "fn"), Function::New(env, Fn)); -} - -NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) -``` - -The above code can be used from JavaScript as follows: - -```js -const addon = require('./addon'); -addon.fn(); -``` - -With the `Napi::Function` class it is possible to call a JavaScript function object -from a native add-on with two different methods: `Call` and `MakeCallback`. -The API of these two methods is very similar, but they are used in different -contexts. The `MakeCallback` method is used to call from native code back into -JavaScript after returning from an [asynchronous operation](async_operations.md) -and in general in situations which don't have an existing JavaScript function on -the stack. The `Call` method is used when there is already a JavaScript function -on the stack (for example when running a native method called from JavaScript). - -## Methods - -### Constructor - -Creates a new empty instance of `Napi::Function`. - -```cpp -Napi::Function::Function(); -``` - -### Constructor - -Creates a new instance of the `Napi::Function` object. - -```cpp -Napi::Function::Function(napi_env env, napi_value value); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object. -- `[in] value`: The `napi_value` which is a handle for a JavaScript function. - -Returns a non-empty `Napi::Function` instance. - -### New - -Creates an instance of a `Napi::Function` object. - -```cpp -template <typename Callable> -static Napi::Function Napi::Function::New(napi_env env, Callable cb, const char* utf8name = nullptr, void* data = nullptr); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object. -- `[in] cb`: Object that implements `Callable`. -- `[in] utf8name`: Null-terminated string to be used as the name of the function. -- `[in] data`: User-provided data context. This will be passed back into the -function when invoked later. - -Returns an instance of a `Napi::Function` object. - -### New - -```cpp -template <typename Callable> -static Napi::Function Napi::Function::New(napi_env env, Callable cb, const std::string& utf8name, void* data = nullptr); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object. -- `[in] cb`: Object that implements `Callable`. -- `[in] utf8name`: String to be used as the name of the function. -- `[in] data`: User-provided data context. This will be passed back into the -function when invoked later. - -Returns an instance of a `Napi::Function` object. - -### New - -Creates a new JavaScript value from one that represents the constructor for the -object. - -```cpp -Napi::Object Napi::Function::New(const std::initializer_list<napi_value>& args) const; -``` - -- `[in] args`: Initializer list of JavaScript values as `napi_value` representing -the arguments of the contructor function. - -Returns a new JavaScript object. - -### New - -Creates a new JavaScript value from one that represents the constructor for the -object. - -```cpp -Napi::Object Napi::Function::New(const std::vector<napi_value>& args) const; -``` - -- `[in] args`: Vector of JavaScript values as `napi_value` representing the -arguments of the constructor function. - -Returns a new JavaScript object. - -### New - -Creates a new JavaScript value from one that represents the constructor for the -object. - -```cpp -Napi::Object Napi::Function::New(size_t argc, const napi_value* args) const; -``` - -- `[in] argc`: The number of the arguments passed to the contructor function. -- `[in] args`: Array of JavaScript values as `napi_value` representing the -arguments of the constructor function. - -Returns a new JavaScript object. - -### Call - -Calls a Javascript function from a native add-on. - -```cpp -Napi::Value Napi::Function::Call(const std::initializer_list<napi_value>& args) const; -``` - -- `[in] args`: Initializer list of JavaScript values as `napi_value` representing -the arguments of the function. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -### Call - -Calls a JavaScript function from a native add-on. - -```cpp -Napi::Value Napi::Function::Call(const std::vector<napi_value>& args) const; -``` - -- `[in] args`: Vector of JavaScript values as `napi_value` representing the -arguments of the function. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -### Call - -Calls a Javascript function from a native add-on. - -```cpp -Napi::Value Napi::Function::Call(size_t argc, const napi_value* args) const; -``` - -- `[in] argc`: The number of the arguments passed to the function. -- `[in] args`: Array of JavaScript values as `napi_value` representing the -arguments of the function. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -### Call - -Calls a Javascript function from a native add-on. - -```cpp -Napi::Value Napi::Function::Call(napi_value recv, const std::initializer_list<napi_value>& args) const; -``` - -- `[in] recv`: The `this` object passed to the called function. -- `[in] args`: Initializer list of JavaScript values as `napi_value` representing -the arguments of the function. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -### Call - -Calls a Javascript function from a native add-on. - -```cpp -Napi::Value Napi::Function::Call(napi_value recv, const std::vector<napi_value>& args) const; -``` - -- `[in] recv`: The `this` object passed to the called function. -- `[in] args`: Vector of JavaScript values as `napi_value` representing the -arguments of the function. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -### Call - -Calls a Javascript function from a native add-on. - -```cpp -Napi::Value Napi::Function::Call(napi_value recv, size_t argc, const napi_value* args) const; -``` - -- `[in] recv`: The `this` object passed to the called function. -- `[in] argc`: The number of the arguments passed to the function. -- `[in] args`: Array of JavaScript values as `napi_value` representing the -arguments of the function. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -### MakeCallback - -Calls a Javascript function from a native add-on after an asynchronous operation. - -```cpp -Napi::Value Napi::Function::MakeCallback(napi_value recv, const std::initializer_list<napi_value>& args, napi_async_context context = nullptr) const; -``` - -- `[in] recv`: The `this` object passed to the called function. -- `[in] args`: Initializer list of JavaScript values as `napi_value` representing -the arguments of the function. -- `[in] context`: Context for the async operation that is invoking the callback. -This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md). -However `nullptr` is also allowed, which indicates the current async context -(if any) is to be used for the callback. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -### MakeCallback - -Calls a Javascript function from a native add-on after an asynchronous operation. - -```cpp -Napi::Value Napi::Function::MakeCallback(napi_value recv, const std::vector<napi_value>& args, napi_async_context context = nullptr) const; -``` - -- `[in] recv`: The `this` object passed to the called function. -- `[in] args`: List of JavaScript values as `napi_value` representing the -arguments of the function. -- `[in] context`: Context for the async operation that is invoking the callback. -This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md). -However `nullptr` is also allowed, which indicates the current async context -(if any) is to be used for the callback. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -### MakeCallback - -Calls a Javascript function from a native add-on after an asynchronous operation. - -```cpp -Napi::Value Napi::Function::MakeCallback(napi_value recv, size_t argc, const napi_value* args, napi_async_context context = nullptr) const; -``` - -- `[in] recv`: The `this` object passed to the called function. -- `[in] argc`: The number of the arguments passed to the function. -- `[in] args`: Array of JavaScript values as `napi_value` representing the -arguments of the function. -- `[in] context`: Context for the async operation that is invoking the callback. -This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md). -However `nullptr` is also allowed, which indicates the current async context -(if any) is to be used for the callback. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. - -## Operator - -```cpp -Napi::Value Napi::Function::operator ()(const std::initializer_list<napi_value>& args) const; -``` - -- `[in] args`: Initializer list of JavaScript values as `napi_value`. - -Returns a `Napi::Value` representing the JavaScript value returned by the function. diff --git a/node_modules/node-addon-api/doc/function_reference.md b/node_modules/node-addon-api/doc/function_reference.md deleted file mode 100644 index 7b299b9..0000000 --- a/node_modules/node-addon-api/doc/function_reference.md +++ /dev/null @@ -1,238 +0,0 @@ -# FunctionReference - -`Napi::FunctionReference` is a subclass of [`Napi::Reference`](reference.md), and -is equivalent to an instance of `Napi::Reference<Napi::Function>`. This means -that a `Napi::FunctionReference` holds a [`Napi::Function`](function.md), and a -count of the number of references to that `Napi::Function`. When the count is -greater than 0, a `Napi::FunctionReference` is not eligible for garbage collection. -This ensures that the `Function` will remain accessible, even if the original -reference to it is no longer available. -`Napi::FunctionReference` allows the referenced JavaScript function object to be -called from a native add-on with two different methods: `Call` and `MakeCallback`. -See the documentation for [`Napi::Function`](function.md) for when `Call` should -be used instead of `MakeCallback` and vice-versa. - -The `Napi::FunctionReference` class inherits its behavior from the `Napi::Reference` -class (for more info see: [`Napi::Reference`](reference.md)). - -## Methods - -### Weak - -Creates a "weak" reference to the value, in that the initial reference count is -set to 0. - -```cpp -static Napi::FunctionReference Napi::Weak(const Napi::Function& value); -``` - -- `[in] value`: The value which is to be referenced. - -Returns the newly created reference. - -### Persistent - -Creates a "persistent" reference to the value, in that the initial reference -count is set to 1. - -```cpp -static Napi::FunctionReference Napi::Persistent(const Napi::Function& value); -``` - -- `[in] value`: The value which is to be referenced. - -Returns the newly created reference. - -### Constructor - -Creates a new empty instance of `Napi::FunctionReference`. - -```cpp -Napi::FunctionReference::FunctionReference(); -``` - -### Constructor - -Creates a new instance of the `Napi::FunctionReference`. - -```cpp -Napi::FunctionReference::FunctionReference(napi_env env, napi_ref ref); -``` - -- `[in] env`: The environment in which to construct the `Napi::FunctionReference` object. -- `[in] ref`: The N-API reference to be held by the `Napi::FunctionReference`. - -Returns a newly created `Napi::FunctionReference` object. - -### New - -Constructs a new instance by calling the constructor held by this reference. - -```cpp -Napi::Object Napi::FunctionReference::New(const std::initializer_list<napi_value>& args) const; -``` - -- `[in] args`: Initializer list of JavaScript values as `napi_value` representing -the arguments of the contructor function. - -Returns a new JavaScript object. - -### New - -Constructs a new instance by calling the constructor held by this reference. - -```cpp -Napi::Object Napi::FunctionReference::New(const std::vector<napi_value>& args) const; -``` - -- `[in] args`: Vector of JavaScript values as `napi_value` representing the -arguments of the constructor function. - -Returns a new JavaScript object. - -### Call - -Calls a referenced Javascript function from a native add-on. - -```cpp -Napi::Value Napi::FunctionReference::Call(const std::initializer_list<napi_value>& args) const; -``` - -- `[in] args`: Initializer list of JavaScript values as `napi_value` representing -the arguments of the referenced function. - -Returns a `Napi::Value` representing the JavaScript object returned by the referenced -function. - -### Call - -Calls a referenced JavaScript function from a native add-on. - -```cpp -Napi::Value Napi::FunctionReference::Call(const std::vector<napi_value>& args) const; -``` - -- `[in] args`: Vector of JavaScript values as `napi_value` representing the -arguments of the referenced function. - -Returns a `Napi::Value` representing the JavaScript object returned by the referenced -function. - -### Call - -Calls a referenced JavaScript function from a native add-on. - -```cpp -Napi::Value Napi::FunctionReference::Call(napi_value recv, const std::initializer_list<napi_value>& args) const; -``` - -- `[in] recv`: The `this` object passed to the referenced function when it's called. -- `[in] args`: Initializer list of JavaScript values as `napi_value` representing -the arguments of the referenced function. - -Returns a `Napi::Value` representing the JavaScript object returned by the referenced -function. - -### Call - -Calls a referenced JavaScript function from a native add-on. - -```cpp -Napi::Value Napi::FunctionReference::Call(napi_value recv, const std::vector<napi_value>& args) const; -``` - -- `[in] recv`: The `this` object passed to the referenced function when it's called. -- `[in] args`: Vector of JavaScript values as `napi_value` representing the -arguments of the referenced function. - -Returns a `Napi::Value` representing the JavaScript object returned by the referenced -function. - -### Call - -Calls a referenced JavaScript function from a native add-on. - -```cpp -Napi::Value Napi::FunctionReference::Call(napi_value recv, size_t argc, const napi_value* args) const; -``` - -- `[in] recv`: The `this` object passed to the referenced function when it's called. -- `[in] argc`: The number of arguments passed to the referenced function. -- `[in] args`: Array of JavaScript values as `napi_value` representing the -arguments of the referenced function. - -Returns a `Napi::Value` representing the JavaScript object returned by the referenced -function. - - -### MakeCallback - -Calls a referenced JavaScript function from a native add-on after an asynchronous -operation. - -```cpp -Napi::Value Napi::FunctionReference::MakeCallback(napi_value recv, const std::initializer_list<napi_value>& args, napi_async_context = nullptr) const; -``` - -- `[in] recv`: The `this` object passed to the referenced function when it's called. -- `[in] args`: Initializer list of JavaScript values as `napi_value` representing -the arguments of the referenced function. -- `[in] context`: Context for the async operation that is invoking the callback. -This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md). -However `nullptr` is also allowed, which indicates the current async context -(if any) is to be used for the callback. - -Returns a `Napi::Value` representing the JavaScript object returned by the referenced -function. - -### MakeCallback - -Calls a referenced JavaScript function from a native add-on after an asynchronous -operation. - -```cpp -Napi::Value Napi::FunctionReference::MakeCallback(napi_value recv, const std::vector<napi_value>& args, napi_async_context context = nullptr) const; -``` - -- `[in] recv`: The `this` object passed to the referenced function when it's called. -- `[in] args`: Vector of JavaScript values as `napi_value` representing the -arguments of the referenced function. -- `[in] context`: Context for the async operation that is invoking the callback. -This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md). -However `nullptr` is also allowed, which indicates the current async context -(if any) is to be used for the callback. - -Returns a `Napi::Value` representing the JavaScript object returned by the referenced -function. - -### MakeCallback - -Calls a referenced JavaScript function from a native add-on after an asynchronous -operation. - -```cpp -Napi::Value Napi::FunctionReference::MakeCallback(napi_value recv, size_t argc, const napi_value* args, napi_async_context context = nullptr) const; -``` - -- `[in] recv`: The `this` object passed to the referenced function when it's called. -- `[in] argc`: The number of arguments passed to the referenced function. -- `[in] args`: Array of JavaScript values as `napi_value` representing the -arguments of the referenced function. -- `[in] context`: Context for the async operation that is invoking the callback. -This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md). -However `nullptr` is also allowed, which indicates the current async context -(if any) is to be used for the callback. - -Returns a `Napi::Value` representing the JavaScript object returned by the referenced -function. - -## Operator - -```cpp -Napi::Value operator ()(const std::initializer_list<napi_value>& args) const; -``` - -- `[in] args`: Initializer list of reference to JavaScript values as `napi_value` - -Returns a `Napi::Value` representing the JavaScript value returned by the referenced -function. diff --git a/node_modules/node-addon-api/doc/generator.md b/node_modules/node-addon-api/doc/generator.md deleted file mode 100644 index 9167480..0000000 --- a/node_modules/node-addon-api/doc/generator.md +++ /dev/null @@ -1,13 +0,0 @@ -# Generator - -## What is generator - -**[generator-napi-module](https://www.npmjs.com/package/generator-napi-module)** is a module to quickly generate a skeleton module using -**N-API**, the new API for Native addons. This module automatically sets up your -**gyp file** to use **node-addon-api**, the C++ wrappers for N-API and generates -a wrapper JS module. Optionally, it can even configure the generated project to -use **TypeScript** instead. - -## **generator-napi-module** reference - - - [Installation and usage](https://www.npmjs.com/package/generator-napi-module#installation) diff --git a/node_modules/node-addon-api/doc/handle_scope.md b/node_modules/node-addon-api/doc/handle_scope.md deleted file mode 100644 index 9b34fcf..0000000 --- a/node_modules/node-addon-api/doc/handle_scope.md +++ /dev/null @@ -1,65 +0,0 @@ -# HandleScope - -The HandleScope class is used to manage the lifetime of object handles -which are created through the use of node-addon-api. These handles -keep an object alive in the heap in order to ensure that the objects -are not collected while native code is using them. -A handle may be created when any new node-addon-api Value or one -of its subclasses is created or returned. For more details refer to -the section titled [Object lifetime management](object_lifetime_management.md). - -## Methods - -### Constructor - -Creates a new handle scope on the stack. - -```cpp -Napi::HandleScope::HandleScope(Napi::Env env); -``` - -- `[in] env`: The environment in which to construct the `Napi::HandleScope` object. - -Returns a new `Napi::HandleScope` - -### Constructor - -Creates a new handle scope on the stack. - -```cpp -Napi::HandleScope::HandleScope(Napi::Env env, Napi::HandleScope scope); -``` - -- `[in] env`: `Napi::Env` in which the scope passed in was created. -- `[in] scope`: pre-existing `Napi::HandleScope`. - -Returns a new `Napi::HandleScope` instance which wraps the napi_handle_scope -handle passed in. This can be used to mix usage of the C N-API -and node-addon-api. - -operator HandleScope::napi_handle_scope - -```cpp -operator Napi::HandleScope::napi_handle_scope() const -``` - -Returns the N-API napi_handle_scope wrapped by the `Napi::EscapableHandleScope` object. -This can be used to mix usage of the C N-API and node-addon-api by allowing -the class to be used be converted to a napi_handle_scope. - -### Destructor -```cpp -Napi::HandleScope::~HandleScope(); -``` - -Deletes the `Napi::HandleScope` instance and allows any objects/handles created -in the scope to be collected by the garbage collector. There is no -guarantee as to when the gargbage collector will do this. - -### Env - -```cpp -Napi::Env Napi::HandleScope::Env() const; -``` - -Returns the `Napi::Env` associated with the `Napi::HandleScope`. diff --git a/node_modules/node-addon-api/doc/memory_management.md b/node_modules/node-addon-api/doc/memory_management.md deleted file mode 100644 index afa6225..0000000 --- a/node_modules/node-addon-api/doc/memory_management.md +++ /dev/null @@ -1,27 +0,0 @@ -# MemoryManagement - -The `Napi::MemoryManagement` class contains functions that give the JavaScript engine -an indication of the amount of externally allocated memory that is kept alive by -JavaScript objects. - -## Methods - -### AdjustExternalMemory - -The function `AdjustExternalMemory` adjusts the amount of registered external -memory used to give the JavaScript engine an indication of the amount of externally -allocated memory that is kept alive by JavaScript objects. -The JavaScript engine uses this to decide when to perform global garbage collections. -Registering externally allocated memory will trigger global garbage collections -more often than it would otherwise in an attempt to garbage collect the JavaScript -objects that keep the externally allocated memory alive. - -```cpp -static int64_t Napi::MemoryManagement::AdjustExternalMemory(Napi::Env env, int64_t change_in_bytes); -``` - -- `[in] env`: The environment in which the API is invoked under. -- `[in] change_in_bytes`: The change in externally allocated memory that is kept -alive by JavaScript objects expressed in bytes. - -Returns the adjusted memory value. diff --git a/node_modules/node-addon-api/doc/node-gyp.md b/node_modules/node-addon-api/doc/node-gyp.md deleted file mode 100644 index 529aa0e..0000000 --- a/node_modules/node-addon-api/doc/node-gyp.md +++ /dev/null @@ -1,82 +0,0 @@ -# node-gyp - -C++ code needs to be compiled into executable form whether it be as an object -file to linked with others, a shared library, or a standalone executable. - -The main reason for this is that we need to link to the Node.js dependencies and -headers correctly, another reason is that we need a cross platform way to build -C++ source into binary for the target platform. - -Until now **node-gyp** is the **de-facto** standard build tool for writing -Node.js addons. It's based on Google's **gyp** build tool, which abstract away -many of the tedious issues related to cross platform building. - -**node-gyp** uses a file called ```binding.gyp``` that is located on the root of -your addon project. - -```binding.gyp``` file, contains all building configurations organized with a -JSON like syntax. The most important parameter is the **target** that must be -set to the same value used on the initialization code of the addon as in the -examples reported below: - -### **binding.gyp** - -```gyp -{ - "targets": [ - { - # myModule is the name of your native addon - "target_name": "myModule", - "sources": ["src/my_module.cc", ...], - ... - ] -} -``` - -### **my_module.cc** - -```cpp -#include <napi.h> - -// ... - -/** -* This code is our entry-point. We receive two arguments here, the first is the -* environment that represent an independent instance of the JavaScript runtime, -* the second is exports, the same as module.exports in a .js file. -* You can either add properties to the exports object passed in or create your -* own exports object. In either case you must return the object to be used as -* the exports for the module when you return from the Init function. -*/ -Napi::Object Init(Napi::Env env, Napi::Object exports) { - - // ... - - return exports; -} - -/** -* This code defines the entry-point for the Node addon, it tells Node where to go -* once the library has been loaded into active memory. The first argument must -* match the "target" in our *binding.gyp*. Using NODE_GYP_MODULE_NAME ensures -* that the argument will be correct, as long as the module is built with -* node-gyp (which is the usual way of building modules). The second argument -* points to the function to invoke. The function must not be namespaced. -*/ -NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) -``` - -## **node-gyp** reference - - - [Installation](https://www.npmjs.com/package/node-gyp#installation) - - [How to use](https://www.npmjs.com/package/node-gyp#how-to-use) - - [The binding.gyp file](https://www.npmjs.com/package/node-gyp#the-bindinggyp-file) - - [Commands](https://www.npmjs.com/package/node-gyp#commands) - - [Command options](https://www.npmjs.com/package/node-gyp#command-options) - - [Configuration](https://www.npmjs.com/package/node-gyp#configuration) - -Sometimes finding the right settings for ```binding.gyp``` is not easy so to -accomplish at most complicated task please refer to: - -- [GYP documentation](https://gyp.gsrc.io/index.md) -- [node-gyp wiki](https://github.com/nodejs/node-gyp/wiki) diff --git a/node_modules/node-addon-api/doc/number.md b/node_modules/node-addon-api/doc/number.md deleted file mode 100644 index d603101..0000000 --- a/node_modules/node-addon-api/doc/number.md +++ /dev/null @@ -1,163 +0,0 @@ -# Number - -`Napi::Number` class is a representation of the JavaScript `Number` object. The -`Napi::Number` class inherits its behavior from `Napi::Value` class -(for more info see [`Napi::Value`](value.md)) - -## Methods - -### Constructor - -Creates a new _empty_ instance of a `Napi::Number` object. - -```cpp -Napi::Number(); -``` - -Returns a new _empty_ `Napi::Number` object. - -### Contructor - -Creates a new instance of a `Napi::Number` object. - -```cpp -Napi::Number(napi_env env, napi_value value); -``` - - - `[in] env`: The `napi_env` environment in which to construct the `Napi::Number` object. - - `[in] value`: The JavaScript value holding a number. - - Returns a non-empty `Napi::Number` object. - - ### New - - Creates a new instance of a `Napi::Number` object. - -```cpp -Napi::Number Napi::Number::New(napi_env env, double value); -``` - - `[in] env`: The `napi_env` environment in which to construct the `Napi::Number` object. - - `[in] value`: The C++ primitive from which to instantiate the `Napi::Number`. - -Creates a new instance of a `Napi::Number` object. - -### Int32Value - -Converts a `Napi::Number` value to a `int32_t` primitive type. - -```cpp -Napi::Number::Int32Value() const; -``` - -Returns the `int32_t` primitive type of the corresponding `Napi::Number` object. - -### Uint32Value - -Converts a `Napi::Number` value to a `uint32_t` primitive type. - -```cpp -Napi::Number::Uint32Value() const; -``` - -Returns the `uint32_t` primitive type of the corresponding `Napi::Number` object. - -### Int64Value - -Converts a `Napi::Number` value to a `int64_t` primitive type. - -```cpp -Napi::Number::Int64Value() const; -``` - -Returns the `int64_t` primitive type of the corresponding `Napi::Number` object. - -### FloatValue - -Converts a `Napi::Number` value to a `float` primitive type. - -```cpp -Napi::Number::FloatValue() const; -``` - -Returns the `float` primitive type of the corresponding `Napi::Number` object. - -### DoubleValue - -Converts a `Napi::Number` value to a `double` primitive type. - -```cpp -Napi::Number::DoubleValue() const; -``` - -Returns the `double` primitive type of the corresponding `Napi::Number` object. - -## Operators - -The `Napi::Number` class contains a set of operators to easily cast JavaScript -`Number` object to one of the following primitive types: - - - `int32_t` - - `uint32_t` - - `int64_t` - - `float` - - `double` - -### operator int32_t - -Converts a `Napi::Number` value to a `int32_t` primitive. - -```cpp -Napi::Number::operator int32_t() const; -``` - -Returns the `int32_t` primitive type of the corresponding `Napi::Number` object. - -### operator uint32_t - -Converts a `Napi::Number` value to a `uint32_t` primitive type. - -```cpp -Napi::Number::operator uint32_t() const; -``` - -Returns the `uint32_t` primitive type of the corresponding `Napi::Number` object. - -### operator int64_t - -Converts a `Napi::Number` value to a `int64_t` primitive type. - -```cpp -Napi::Number::operator int64_t() const; -``` - -Returns the `int64_t` primitive type of the corresponding `Napi::Number` object. - -### operator float - -Converts a `Napi::Number` value to a `float` primitive type. - -```cpp -Napi::Number::operator float() const; -``` - -Returns the `float` primitive type of the corresponding `Napi::Number` object. - -### operator double - -Converts a `Napi::Number` value to a `double` primitive type. - -```cpp -Napi::Number::operator double() const; -``` - -Returns the `double` primitive type of the corresponding `Napi::Number` object. - -### Example - -The following shows an example of casting a number to an `uint32_t` value. - -```cpp -uint32_t operatorVal = Napi::Number::New(Env(), 10.0); // Number to unsigned 32 bit integer -// or -auto instanceVal = info[0].As<Napi::Number>().Uint32Value(); -``` diff --git a/node_modules/node-addon-api/doc/object.md b/node_modules/node-addon-api/doc/object.md deleted file mode 100644 index 3241054..0000000 --- a/node_modules/node-addon-api/doc/object.md +++ /dev/null @@ -1,236 +0,0 @@ -# Object - -The `Napi::Object` class corresponds to a JavaScript object. It is extended by the following node-addon-api classes that you may use when working with more specific types: - -- [`Napi::Value`](value.md) and extends [`Napi::Array`](array.md) -- [`Napi::ArrayBuffer`](array_buffer.md) -- [`Napi::Buffer<T>`](buffer.md) -- [`Napi::Function`](function.md) -- [`Napi::TypedArray`](typed_array.md). - -This class provides a number of convenience methods, most of which are used to set or get properties on a JavaScript object. For example, Set() and Get(). - -## Example -```cpp -#include <napi.h> - -using namespace Napi; - -Void Init(Env env) { - - // Create a new instance - Object obj = Object::New(env); - - // Assign values to properties - obj.Set("hello", "world"); - obj.Set(uint32_t(42), "The Answer to Life, the Universe, and Everything"); - obj.Set("Douglas Adams", true); - - // Get properties - Value val1 = obj.Get("hello"); - Value val2 = obj.Get(uint32_t(42)); - Value val3 = obj.Get("Douglas Adams"); - - // Test if objects have properties. - bool obj1 = obj.Has("hello"); // true - bool obj2 = obj.Has("world"); // false - -} -``` - -## Methods - -### Empty Constructor - -```cpp -Napi::Object::Object(); -``` -Creates a new empty Object instance. - -### Constructor - -```cpp -Napi::Object::Object(napi_env env, napi_value value); -``` -- `[in] env`: The `napi_env` environment in which to construct the Value object. - -- `[in] value`: The C++ primitive from which to instantiate the Value. `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 - -Creates a non-empty `Napi::Object` instance. - -### New() - -```cpp -Napi::Object Napi::Object::New(napi_env env); -``` -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Value` object. - -Creates a new `Napi::Object` value. - -### Set() - -```cpp -void Napi::Object::Set (____ key, ____ value); -``` -- `[in] key`: The name for the property being assigned. -- `[in] value`: The value being assigned to the property. - -Add a property with the specified key with the specified value to the object. - -The key can be any of the following types: -- `napi_value` -- [`Napi::Value`](value.md) -- `const char*` -- `const std::string&` -- `uint32_t` - -While the value must be any of the following types: -- `napi_value` -- [`Napi::Value`](value.md) -- `const char*` -- `std::string&` -- `bool` -- `double` - -### Get() - -```cpp -Napi::Value Napi::Object::Get(____ key); -``` -- `[in] key`: The name of the property to return the value for. - -Returns the [`Napi::Value`](value.md) associated with the key property. Returns the value *undefined* if the key does not exist. - -The `key` can be any of the following types: -- `napi_value` -- [`Napi::Value`](value.md) -- `const char *` -- `const std::string &` -- `uint32_t` - -### Has() - -```cpp -bool Napi::Object::Has (____ key) const; -``` -- `[in] key`: The name of the property to check. - -Returns a `bool` that is *true* if the object has a property named `key` and *false* otherwise. - -### InstanceOf() - -```cpp -bool Napi::Object::InstanceOf (const Function& constructor) const -``` -- `[in] constructor`: The constructor [`Napi::Function`](function.md) of the value that is being compared with the object. - -Returns a `bool` that is true if the `Napi::Object` is an instance created by the `constructor` and false otherwise. - -Note: This is equivalent to the JavaScript instanceof operator. - -### AddFinalizer() -```cpp -template <typename Finalizer, typename T> -inline void AddFinalizer(Finalizer finalizeCallback, T* data); -``` - -- `[in] finalizeCallback`: The function to call when the object is garbage-collected. -- `[in] data`: The data to associate with the object. - -Associates `data` with the object, calling `finalizeCallback` when the object is garbage-collected. `finalizeCallback` -has the signature -```cpp -void finalizeCallback(Napi::Env env, T* data); -``` -where `data` is the pointer that was passed into the call to `AddFinalizer()`. - -### AddFinalizer() -```cpp -template <typename Finalizer, typename T, typename Hint> -inline void AddFinalizer(Finalizer finalizeCallback, - T* data, - Hint* finalizeHint); -``` - -- `[in] data`: The data to associate with the object. -- `[in] finalizeCallback`: The function to call when the object is garbage-collected. - -Associates `data` with the object, calling `finalizeCallback` when the object is garbage-collected. An additional hint -may be given. It will also be passed to `finalizeCallback`, which has the signature -```cpp -void finalizeCallback(Napi::Env env, T* data, Hint* hint); -``` -where `data` and `hint` are the pointers that were passed into the call to `AddFinalizer()`. - -### DefineProperty() - -```cpp -void Napi::Object::DefineProperty (const Napi::PropertyDescriptor& property); -``` -- `[in] property`: A [`Napi::PropertyDescriptor`](property_descriptor.md). - -Define a property on the object. - -### DefineProperties() - -```cpp -void Napi::Object::DefineProperties (____ properties) -``` -- `[in] properties`: A list of [`Napi::PropertyDescriptor`](property_descriptor.md). Can be one of the following types: - - const std::initializer_list<Napi::PropertyDescriptor>& - - const std::vector<Napi::PropertyDescriptor>& - -Defines properties on the object. - -### Operator[]() - -```cpp -Napi::PropertyLValue<std::string> Napi::Object::operator[] (const char* utf8name); -``` -- `[in] utf8name`: UTF-8 encoded null-terminated property name. - -Returns a [`Napi::PropertyLValue`](propertylvalue.md) as the named property or sets the named property. - -```cpp -Napi::PropertyLValue<std::string> Napi::Object::operator[] (const std::string& utf8name); -``` -- `[in] utf8name`: UTF-8 encoded property name. - -Returns a [`Napi::PropertyLValue`](propertylvalue.md) as the named property or sets the named property. - -```cpp -Napi::PropertyLValue<uint32_t> Napi::Object::operator[] (uint32_t index); -``` -- `[in] index`: Element index. - -Returns a [`Napi::PropertyLValue`](propertylvalue.md) or sets an indexed property or array element. - -```cpp -Napi::Value Napi::Object::operator[] (const char* utf8name) const; -``` -- `[in] utf8name`: UTF-8 encoded null-terminated property name. - -Returns the named property as a [`Napi::Value`](value.md). - -```cpp -Napi::Value Napi::Object::operator[] (const std::string& utf8name) const; -``` -- `[in] utf8name`: UTF-8 encoded property name. - -Returns the named property as a [`Napi::Value`](value.md). - -```cpp -Napi::Value Napi::Object::operator[] (uint32_t index) const; -``` -- `[in] index`: Element index. - -Returns an indexed property or array element as a [`Napi::Value`](value.md). diff --git a/node_modules/node-addon-api/doc/object_lifetime_management.md b/node_modules/node-addon-api/doc/object_lifetime_management.md deleted file mode 100644 index 4ab19ec..0000000 --- a/node_modules/node-addon-api/doc/object_lifetime_management.md +++ /dev/null @@ -1,83 +0,0 @@ -# Object lifetime management - -A handle may be created when any new node-addon-api Value and -its subclasses is created or returned. - -As the methods and classes within the node-addon-api are used, -handles to objects in the heap for the underlying -VM may be created. A handle may be created when any new -node-addon-api Value or one of its subclasses is created or returned. -These handles must hold the objects 'live' until they are no -longer required by the native code, otherwise the objects could be -collected by the garbage collector before the native code was -finished using them. - -As handles are created they are associated with a -'scope'. The lifespan for the default scope is tied to the lifespan -of the native method call. The result is that, by default, handles -remain valid and the objects associated with these handles will be -held live for the lifespan of the native method call. - -In many cases, however, it is necessary that the handles remain valid for -either a shorter or longer lifespan than that of the native method. -The sections which follow describe the node-addon-api classes and -methods that than can be used to change the handle lifespan from -the default. - -## Making handle lifespan shorter than that of the native method - -It is often necessary to make the lifespan of handles shorter than -the lifespan of a native method. For example, consider a native method -that has a loop which creates a number of values and does something -with each of the values, one at a time: - -```C++ -for (int i = 0; i < LOOP_MAX; i++) { - std::string name = std::string("inner-scope") + std::to_string(i); - Napi::Value newValue = Napi::String::New(info.Env(), name.c_str()); - // do something with newValue -}; -``` - -This would result in a large number of handles being created, consuming -substantial resources. In addition, even though the native code could only -use the most recently created value, all of the previously created -values would also be kept alive since they all share the same scope. - -To handle this case, node-addon-api provides the ability to establish -a new 'scope' to which newly created handles will be associated. Once those -handles are no longer required, the scope can be deleted and any handles -associated with the scope are invalidated. The `Napi::HandleScope` -and `Napi::EscapableHandleScope` classes are provided by node-addon-api for -creating additional scopes. - -node-addon-api only supports a single nested hierarchy of scopes. There is -only one active scope at any time, and all new handles will be associated -with that scope while it is active. Scopes must be deleted in the reverse -order from which they are opened. In addition, all scopes created within -a native method must be deleted before returning from that method. Since -`Napi::HandleScopes` are typically stack allocated the compiler will take care of -deletion, however, care must be taken to create the scope in the right -place such that you achieve the desired lifetime. - -Taking the earlier example, creating a `Napi::HandleScope` in the innner loop -would ensure that at most a single new value is held alive throughout the -execution of the loop: - -```C -for (int i = 0; i < LOOP_MAX; i++) { - Napi::HandleScope scope(info.Env()); - std::string name = std::string("inner-scope") + std::to_string(i); - Napi::Value newValue = Napi::String::New(info.Env(), name.c_str()); - // do something with neValue -}; -``` - -When nesting scopes, there are cases where a handle from an -inner scope needs to live beyond the lifespan of that scope. node-addon-api -provides the `Napi::EscapableHandleScope` with the `Escape` method -in order to support this case. An escapable scope -allows one object to be 'promoted' so that it 'escapes' the -current scope and the lifespan of the handle changes from the current -scope to that of the outer scope. The `Escape` method can only be called -once for a given `Napi::EscapableHandleScope`. diff --git a/node_modules/node-addon-api/doc/object_reference.md b/node_modules/node-addon-api/doc/object_reference.md deleted file mode 100644 index 6e579e2..0000000 --- a/node_modules/node-addon-api/doc/object_reference.md +++ /dev/null @@ -1,117 +0,0 @@ -# Object Reference - -`Napi::ObjectReference` is a subclass of [`Napi::Reference`](reference.md), and is equivalent to an instance of `Napi::Reference<Object>`. This means that a `Napi::ObjectReference` holds a [`Napi::Object`](object.md), and a count of the number of references to that Object. When the count is greater than 0, an ObjectReference is not eligible for garbage collection. This ensures that the Object being held as a value of the ObjectReference will remain accessible, even if the original Object no longer is. However, ObjectReference is unique from a Reference since properties can be set and get to the Object itself that can be accessed through the ObjectReference. - -For more general information on references, please consult [`Napi::Reference`](reference.md). - -## Example -```cpp -#include <napi.h> - -using namescape Napi; - -void Init(Env env) { - - // Create an empty ObjectReference that has an initial reference count of 2. - ObjectReference obj_ref = Reference<Object>::New(Object::New(env), 2); - - // Set a couple of different properties on the reference. - obj_ref.Set("hello", String::New(env, "world")); - obj_ref.Set(42, "The Answer to Life, the Universe, and Everything"); - - // Get the properties using the keys. - Value val1 = obj_ref.Get("hello"); - Value val2 = obj_ref.Get(42); -} -``` - -## Methods - -### Initialization - -```cpp -static Napi::ObjectReference Napi::ObjectReference::New(const Napi::Object& value, uint32_t initialRefcount = 0); -``` - -* `[in] value`: The `Napi::Object` which is to be referenced. - -* `[in] initialRefcount`: The initial reference count. - -Returns the newly created reference. - -```cpp -static Napi::ObjectReference Napi::Weak(const Napi::Object& value); -``` - -Creates a "weak" reference to the value, in that the initial count of number of references is set to 0. - -* `[in] value`: The value which is to be referenced. - -Returns the newly created reference. - -```cpp -static Napi::ObjectReference Napi::Persistent(const Napi::Object& value); -``` - -Creates a "persistent" reference to the value, in that the initial count of number of references is set to 1. - -* `[in] value`: The value which is to be referenced. - -Returns the newly created reference. - -### Empty Constructor - -```cpp -Napi::ObjectReference::ObjectReference(); -``` - -Returns a new _empty_ `Napi::ObjectReference` instance. - -### Constructor - -```cpp -Napi::ObjectReference::ObjectReference(napi_env env, napi_value value); -``` - -* `[in] env`: The `napi_env` environment in which to construct the `Napi::ObjectReference` object. - -* `[in] value`: The N-API primitive value to be held by the `Napi::ObjectReference`. - -Returns the newly created reference. - -### Set -```cpp -void Napi::ObjectReference::Set(___ key, ___ value); -``` - -* `[in] key`: The name for the property being assigned. - -* `[in] value`: The value being assigned to the property. - -The `key` can be any of the following types: -- `const char*` -- `const std::string` -- `uint32_t` - -The `value` can be any of the following types: -- `napi_value` -- `Napi::Value` -- `const char*` -- `bool` -- `double` - -### Get - -```cpp -Napi::Value Napi::ObjectReference::Get(___ key); -``` - -* `[in] key`: The name of the property to return the value for. - -Returns the [`Napi::Value`](value.md) associated with the key property. Returns NULL if no such key exists. - -The `key` can be any of the following types: -- `const char*` -- `const std::string` -- `uint32_t` - diff --git a/node_modules/node-addon-api/doc/object_wrap.md b/node_modules/node-addon-api/doc/object_wrap.md deleted file mode 100644 index 1db658a..0000000 --- a/node_modules/node-addon-api/doc/object_wrap.md +++ /dev/null @@ -1,557 +0,0 @@ -# Object Wrap - -The `Napi::ObjectWrap` class is used to bind the lifetime of C++ code to a -JavaScript object. Once bound, each time an instance of the JavaScript object -is created, an instance of the C++ class will also be created. When a method -is called on the JavaScript object which is defined as an InstanceMethod, the -corresponding C++ method on the wrapped C++ class will be invoked. - -In order to create a wrapper it's necessary to extend the -`Napi::ObjectWrap`class which contains all the plumbing to connect JavaScript code -with a C++ object. Classes extending `Napi::ObjectWrap` can be instantiated from -JavaScript using the **new** operator, and their methods can be directly invoked -from JavaScript. The **wrap** word refers to a way of grouping methods and state -of the class because it will be necessary write custom code to bridge each of -your C++ class methods. - -## Example - -```cpp -#include <napi.h> - -class Example : public Napi::ObjectWrap<Example> { - public: - static Napi::Object Init(Napi::Env env, Napi::Object exports); - Example(const Napi::CallbackInfo &info); - - private: - static Napi::FunctionReference constructor; - double _value; - Napi::Value GetValue(const Napi::CallbackInfo &info); - Napi::Value SetValue(const Napi::CallbackInfo &info); -}; - -Napi::Object Example::Init(Napi::Env env, Napi::Object exports) { - // This method is used to hook the accessor and method callbacks - Napi::Function func = DefineClass(env, "Example", { - InstanceMethod("GetValue", &Example::GetValue), - InstanceMethod("SetValue", &Example::SetValue) - }); - - // Create a peristent reference to the class constructor. This will allow - // a function called on a class prototype and a function - // called on instance of a class to be distinguished from each other. - constructor = Napi::Persistent(func); - // Call the SuppressDestruct() method on the static data prevent the calling - // to this destructor to reset the reference when the environment is no longer - // available. - constructor.SuppressDestruct(); - exports.Set("Example", func); - return exports; -} - -Example::Example(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Example>(info) { - Napi::Env env = info.Env(); - // ... - Napi::Number value = info[0].As<Napi::Number>(); - this->_value = value.DoubleValue(); -} - -Napi::FunctionReference Example::constructor; - -Napi::Value Example::GetValue(const Napi::CallbackInfo &info){ - Napi::Env env = info.Env(); - return Napi::Number::New(env, this->_value); -} - -Napi::Value Example::SetValue(const Napi::CallbackInfo &info){ - Napi::Env env = info.Env(); - // ... - Napi::Number value = info[0].As<Napi::Number>(); - this->_value = value.DoubleValue(); - return this->GetValue(info); -} - -// Initialize native add-on -Napi::Object Init (Napi::Env env, Napi::Object exports) { - Example::Init(env, exports); - return exports; -} - -// Register and initialize native add-on -NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) -``` - -The above code can be used from JavaScript as follows: - -```js -'use strict' - -const { Example } = require('bindings')('addon') - -const example = new Example(11) -console.log(example.GetValue()) -// It prints 11 -example.SetValue(19) -console.log(example.GetValue()); -// It prints 19 -``` - -At initialization time, the `Napi::ObjectWrap::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. - -When JavaScript code invokes the constructor, the constructor callback will create -a new C++ instance and "wrap" it into the newly created JavaScript object. - -When JavaScript code invokes a method or a property accessor on the class the -corresponding C++ callback function will be executed. - -For a wrapped object it could be difficult to distinguish between a function called -on a class prototype and a function called on instance of a class. Therefore it is -good practice to save a persistent reference to the class constructor. This allows -the two cases to be distinguished from each other by checking the this object -against the class constructor. - -## Methods - -### Constructor - -Creates a new instance of a JavaScript object that wraps native instance. - -```cpp -Napi::ObjectWrap(const Napi::CallbackInfo& callbackInfo); -``` - -- `[in] callbackInfo`: The object representing the components of the JavaScript -request being made. - -### Unwrap - -Retrieves a native instance wrapped in a JavaScript object. - -```cpp -static T* Napi::ObjectWrap::Unwrap(Napi::Object wrapper); -``` - -* `[in] wrapper`: The JavaScript object that wraps the native instance. - -Returns a native instace wrapped in a JavaScript object. Given the -Napi:Object, this allows a method to get a pointer to the wrapped -C++ object and then reference fields, call methods, etc. within that class. -In many cases calling Unwrap is not required, as methods can -use the `this` field for ObjectWrap when running in a method on a -class that extends ObjectWrap. - -### DefineClass - -Defnines a JavaScript class with constructor, static and instance properties and -methods. - -```cpp -static Napi::Function Napi::ObjectWrap::DefineClass(Napi::Env env, - const char* utf8name, - const std::initializer_list<PropertyDescriptor>& properties, - void* data = nullptr); -``` - -* `[in] env`: The environment in which to construct a JavaScript class. -* `[in] utf8name`: Null-terminated string that represents the name of the -JavaScript constructor function. -* `[in] properties`: Initializer list of class property descriptor describing -static and instance properties and methods of the class. -See: [`Class property and descriptor`](class_property_descriptor.md). -* `[in] data`: User-provided data passed to the constructor callback as `data` -property of the `Napi::CallbackInfo`. - -Returns a `Napi::Function` representing the constructor function for the class. - -### DefineClass - -Defnines a JavaScript class with constructor, static and instance properties and -methods. - -```cpp -static Napi::Function Napi::ObjectWrap::DefineClass(Napi::Env env, - const char* utf8name, - const std::vector<PropertyDescriptor>& properties, - void* data = nullptr); -``` - -* `[in] env`: The environment in which to construct a JavaScript class. -* `[in] utf8name`: Null-terminated string that represents the name of the -JavaScript constructor function. -* `[in] properties`: Vector of class property descriptor describing static and -instance properties and methods of the class. -See: [`Class property and descriptor`](class_property_descriptor.md). -* `[in] data`: User-provided data passed to the constructor callback as `data` -property of the `Napi::CallbackInfo`. - -Returns a `Napi::Function` representing the constructor function for the class. - -### Finalize - -Provides an opportunity to run cleanup code that requires access to the `Napi::Env` -before the wrapped native object instance is freed. Override to implement. - -```cpp -virtual void Finalize(Napi::Env env); -``` - -- `[in] env`: `Napi::Env`. - -### StaticMethod - -Creates property descriptor that represents a static method of a JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(const char* utf8name, - StaticVoidMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] utf8name`: Null-terminated string that represents the name of a static -method for the class. -- `[in] method`: The native function that represents a static method of a -JavaScript class. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into method when it is invoked. - -Returns `Napi::PropertyDescriptor` object that represents the static method of a -JavaScript class. - -### StaticMethod - -Creates property descriptor that represents a static method of a JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(const char* utf8name, - StaticMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] utf8name`: Null-terminated string that represents the name of a static -method for the class. -- `[in] method`: The native function that represents a static method of a -JavaScript class. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into method when it is invoked. - -Returns `Napi::PropertyDescriptor` object that represents a static method of a -JavaScript class. - -### StaticMethod - -Creates property descriptor that represents a static method of a JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(Symbol name, - StaticVoidMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] name`: Napi:Symbol that represents the name of a static -method for the class. -- `[in] method`: The native function that represents a static method of a -JavaScript class. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into method when it is invoked. - -Returns `Napi::PropertyDescriptor` object that represents the static method of a -JavaScript class. - -### StaticMethod - -Creates property descriptor that represents a static method of a JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(Symbol name, - StaticMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -method for the class. -- `[in] name`: Napi:Symbol that represents the name of a static. -- `[in] method`: The native function that represents a static method of a -JavaScript class. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into method when it is invoked. - -Returns `Napi::PropertyDescriptor` object that represents a static method of a -JavaScript class. - -### StaticAccessor - -Creates property descriptor that represents a static accessor property of a -JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::StaticAccessor(const char* utf8name, - StaticGetterCallback getter, - StaticSetterCallback setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] utf8name`: Null-terminated string that represents the name of a static -accessor property for the class. -- `[in] getter`: The native function to call when a get access to the property of -a JavaScript class is performed. -- `[in] setter`: The native function to call when a set access to the property of -a JavaScript class is performed. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into getter or setter when -is invoked. - -Returns `Napi::PropertyDescriptor` object that represents a static accessor -property of a JavaScript class. - -### StaticAccessor - -Creates property descriptor that represents a static accessor property of a -JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::StaticAccessor(Symbol name, - StaticGetterCallback getter, - StaticSetterCallback setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] name`: Napi:Symbol that represents the name of a static accessor. -- `[in] getter`: The native function to call when a get access to the property of -a JavaScript class is performed. -- `[in] setter`: The native function to call when a set access to the property of -a JavaScript class is performed. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into getter or setter when -is invoked. - -Returns `Napi::PropertyDescriptor` object that represents a static accessor -property of a JavaScript class. - -### InstanceMethod - -Creates property descriptor that represents an instance method of a JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceMethod(const char* utf8name, - InstanceVoidMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] utf8name`: Null-terminated string that represents the name of an instance -method for the class. -- `[in] method`: The native function that represents an instance method of a -JavaScript class. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into method when it is invoked. - -Returns `Napi::PropertyDescriptor` object that represents an instance method of a -JavaScript class. - -### InstanceMethod - -Creates property descriptor that represents an instance method of a JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceMethod(const char* utf8name, - InstanceMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] utf8name`: Null-terminated string that represents the name of an instance -method for the class. -- `[in] method`: The native function that represents an instance method of a -JavaScript class. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into method when it is invoked. - -Returns `Napi::PropertyDescriptor` object that represents an instance method of a -JavaScript class. - -### InstanceMethod - -Creates property descriptor that represents an instance method of a JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceMethod(Napi::Symbol name, - InstanceVoidMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] name`: The `Napi::Symbol` object whose value is used to identify the -instance method for the class. -- `[in] method`: The native function that represents an instance method of a -JavaScript class. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into method when it is invoked. - -Returns `Napi::PropertyDescriptor` object that represents an instance method of a -JavaScript class. - -### InstanceMethod - -Creates property descriptor that represents an instance method of a JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceMethod(Napi::Symbol name, - InstanceMethodCallback method, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] name`: The `Napi::Symbol` object whose value is used to identify the -instance method for the class. -- `[in] method`: The native function that represents an instance method of a -JavaScript class. -- `[in] attributes`: The attributes associated with a particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into method when it is invoked. - -Returns `Napi::PropertyDescriptor` object that represents an instance method of a -JavaScript class. - -### InstanceAccessor - -Creates property descriptor that represents an instance accessor property of a -JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceAccessor(const char* utf8name, - InstanceGetterCallback getter, - InstanceSetterCallback setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] utf8name`: Null-terminated string that represents the name of an instance -accessor property for the class. -- `[in] getter`: The native function to call when a get access to the property of -a JavaScript class is performed. -- `[in] setter`: The native function to call when a set access to the property of -a JavaScript class is performed. -- `[in] attributes`: The attributes associated with the particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into getter or setter when this is invoked. - -Returns `Napi::PropertyDescriptor` object that represents an instance accessor -property of a JavaScript class. - -### InstanceAccessor - -Creates property descriptor that represents an instance accessor property of a -JavaScript class. - -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceAccessor(Symbol name, - InstanceGetterCallback getter, - InstanceSetterCallback setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -``` - -- `[in] name`: The `Napi::Symbol` object whose value is used to identify the -instance accessor. -- `[in] getter`: The native function to call when a get access to the property of -a JavaScript class is performed. -- `[in] setter`: The native function to call when a set access to the property of -a JavaScript class is performed. -- `[in] attributes`: The attributes associated with the particular property. -One or more of `napi_property_attributes`. -- `[in] data`: User-provided data passed into getter or setter when this is invoked. - -Returns `Napi::PropertyDescriptor` object that represents an instance accessor -property of a JavaScript class. - -### StaticValue - -Creates property descriptor that represents an static value property of a -JavaScript class. -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::StaticValue(const char* utf8name, - Napi::Value value, - napi_property_attributes attributes = napi_default); -``` - -- `[in] utf8name`: Null-terminated string that represents the name of the static -property. -- `[in] value`: The value that's retrieved by a get access of the property. -- `[in] attributes`: The attributes to be associated with the property in addition -to the napi_static attribute. One or more of `napi_property_attributes`. - -Returns `Napi::PropertyDescriptor` object that represents an static value -property of a JavaScript class - -### StaticValue - -Creates property descriptor that represents an static value property of a -JavaScript class. -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::StaticValue(Symbol name, - Napi::Value value, - napi_property_attributes attributes = napi_default); -``` - -- `[in] name`: The `Napi::Symbol` object whose value is used to identify the -name of the static property. -- `[in] value`: The value that's retrieved by a get access of the property. -- `[in] attributes`: The attributes to be associated with the property in addition -to the napi_static attribute. One or more of `napi_property_attributes`. - -Returns `Napi::PropertyDescriptor` object that represents an static value -property of a JavaScript class - -### InstanceValue - -Creates property descriptor that represents an instance value property of a -JavaScript class. -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceValue(const char* utf8name, - Napi::Value value, - napi_property_attributes attributes = napi_default); -``` - -- `[in] utf8name`: Null-terminated string that represents the name of the property. -- `[in] value`: The value that's retrieved by a get access of the property. -- `[in] attributes`: The attributes to be associated with the property. -One or more of `napi_property_attributes`. - -Returns `Napi::PropertyDescriptor` object that represents an instance value -property of a JavaScript class. - -### InstanceValue - -Creates property descriptor that represents an instance value property of a -JavaScript class. -```cpp -static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceValue(Symbol name, - Napi::Value value, - napi_property_attributes attributes = napi_default); -``` - -- `[in] name`: The `Napi::Symbol` object whose value is used to identify the -name of the property. -- `[in] value`: The value that's retrieved by a get access of the property. -- `[in] attributes`: The attributes to be associated with the property. -One or more of `napi_property_attributes`. - -Returns `Napi::PropertyDescriptor` object that represents an instance value diff --git a/node_modules/node-addon-api/doc/prebuild_tools.md b/node_modules/node-addon-api/doc/prebuild_tools.md deleted file mode 100644 index 573af68..0000000 --- a/node_modules/node-addon-api/doc/prebuild_tools.md +++ /dev/null @@ -1,16 +0,0 @@ -# Prebuild tools - -The distribution of a native add-on is just as important as its implementation. -In order to install a native add-on it's important to have all the necessary -dependencies installed and well configured (see the [setup](setup.md) section). -The end-user will need to compile the add-on when they will do an `npm install` -and in some cases this could create problems. To avoid the compilation process it's -possible to ditribute the native add-on in pre-built form for different platform -and architectures. The prebuild tools help to create and distrubute the pre-built -form of a native add-on. - -The following list report known tools that are compatible with **N-API**: - -- **[node-pre-gyp](https://www.npmjs.com/package/node-pre-gyp)** -- **[prebuild](https://www.npmjs.com/package/prebuild)** -- **[prebuildify](https://www.npmjs.com/package/prebuildify)** diff --git a/node_modules/node-addon-api/doc/promises.md b/node_modules/node-addon-api/doc/promises.md deleted file mode 100644 index 6252900..0000000 --- a/node_modules/node-addon-api/doc/promises.md +++ /dev/null @@ -1,74 +0,0 @@ -# Promise - -The `Napi::Promise` class, along with its `Napi::Promise::Deferred` class, implement the ability to create, resolve, and reject Promise objects. - -The basic approach is to create a `Napi::Promise::Deferred` object and return to your caller the value returned by the `Napi::Promise::Deferred::Promise` method. For example: - -```cpp -Napi::Value YourFunction(const Napi::CallbackInfo& info) { - // your code goes here... - Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(info.Env()); - // deferred needs to survive this call... - return deferred.Promise(); -} -``` - -Later, when the asynchronous process completes, call either the `Resolve` or `Reject` method on the `Napi::Promise::Deferred` object created earlier: - -```cpp - deferred.Resolve(String::New(info.Env(), "OK")); -``` - -## Promise::Deferred Methods - -### Factory Method - -```cpp -static Napi::Promise::Deferred Napi::Promise::Deferred::New(napi_env env); -``` - -* `[in] env`: The `napi_env` environment in which to create the `Napi::Promise::Deferred` object. - -### Constructor - -```cpp -Napi::Promise::Deferred(napi_env env); -``` - -* `[in] env`: The `napi_env` environment in which to construct the `Napi::Promise::Deferred` object. - -### Env - -```cpp -Napi::Env Napi::Promise::Deferred::Env() const; -``` - -Returns the Env environment this `Napi::Promise::Deferred` object is associated with. - -### Promise - -```cpp -Napi::Promise Napi::Promise::Deferred::Promise() const; -``` - -Returns the `Napi::Promise` object held by the `Napi::Promise::Deferred` object. - -### Resolve - -```cpp -void Napi::Promise::Deferred::Resolve(napi_value value) const; -``` - -Resolves the `Napi::Promise` object held by the `Napi::Promise::Deferred` object. - -* `[in] value`: The N-API primitive value with which to resolve the `Napi::Promise`. - -### Reject - -```cpp -void Napi::Promise::Deferred::Reject(napi_value value) const; -``` - -Rejects the Promise object held by the `Napi::Promise::Deferred` object. - -* `[in] value`: The N-API primitive value with which to reject the `Napi::Promise`. diff --git a/node_modules/node-addon-api/doc/property_descriptor.md b/node_modules/node-addon-api/doc/property_descriptor.md deleted file mode 100644 index 324b62f..0000000 --- a/node_modules/node-addon-api/doc/property_descriptor.md +++ /dev/null @@ -1,231 +0,0 @@ -# Property Descriptor - -A [`Napi::Object`](object.md) can be assigned properites via its [`DefineProperty`](object.md#defineproperty) and [`DefineProperties`](object.md#defineproperties) functions, which take PropertyDescrptor(s) as their parameters. The `Napi::PropertyDescriptor` can contain either values or functions, which are then assigned to the `Napi::Object`. Note that a single instance of a `Napi::PropertyDescriptor` class can only contain either one value, or at most two functions. PropertyDescriptors can only be created through the class methods [`Accessor`](#accessor), [`Function`](#function), or [`Value`](#value), each of which return a new static instance of a `Napi::PropertyDescriptor`. - -## Example - -```cpp -#include <napi.h> - -using namespace Napi; - -Value TestGetter(const CallbackInfo& info) { - return Boolean::New(info.Env(), testValue); -} - -void TestSetter(const CallbackInfo& info) { - testValue = info[0].As<Boolean>(); -} - -Value TestFunction(const CallbackInfo& info) { - return Boolean::New(info.Env(), true); -} - -Void Init(Env env) { - // Create an object. - Object obj = Object::New(env); - - // Accessor - PropertyDescriptor pd1 = PropertyDescriptor::Accessor(env, - obj, - "pd1", - TestGetter); - PropertyDescriptor pd2 = PropertyDescriptor::Accessor(env, - obj, - "pd2", - TestGetter, - TestSetter); - // Function - PropertyDescriptor pd3 = PropertyDescriptor::Function(env, - "function", - TestFunction); - // Value - Boolean true_bool = Boolean::New(env, true); - PropertyDescriptor pd4 = - PropertyDescriptor::Value("boolean value", - Napi::Boolean::New(env, true), - napi_writable); - - // Assign properties to the object. - obj.DefineProperties({pd1, pd2, pd3, pd4}); -} -``` - -## Methods - -### Constructor - -```cpp -Napi::PropertyDescriptor::PropertyDescriptor (napi_property_descriptor desc); -``` - -* `[in] desc`: A PropertyDescriptor that is needed in order to create another PropertyDescriptor. - -### Accessor - -```cpp -static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor (___ name, - Getter getter, - napi_property_attributes attributes = napi_default, - void *data = nullptr); -``` - -* `[in] name`: The name used for the getter function. -* `[in] getter`: A getter function. -* `[in] attributes`: Potential attributes for the getter function. -* `[in] data`: A pointer to data of any type, default is a null pointer. - -Returns a PropertyDescriptor that contains a function. - -The name of the property can be any of the following types: -- `const char*` -- `const std::string &` -- `napi_value value` -- `Napi::Name` - -**This signature is deprecated. It will result in a memory leak if used.** - -```cpp -static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor ( - Napi::Env env, - Napi::Object object, - ___ name, - Getter getter, - napi_property_attributes attributes = napi_default, - void *data = nullptr); -``` - -* `[in] env`: The environemnt in which to create this accessor. -* `[in] object`: The object on which the accessor will be defined. -* `[in] name`: The name used for the getter function. -* `[in] getter`: A getter function. -* `[in] attributes`: Potential attributes for the getter function. -* `[in] data`: A pointer to data of any type, default is a null pointer. - -Returns a `Napi::PropertyDescriptor` that contains a `Getter` accessor. - -The name of the property can be any of the following types: -- `const char*` -- `const std::string &` -- `Napi::Name` - -```cpp -static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor (___ name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void *data = nullptr); -``` - -* `[in] name`: The name of the getter and setter function. -* `[in] getter`: The getter function. -* `[in] setter`: The setter function. -* `[in] attributes`: Potential attributes for the getter function. -* `[in] data`: A pointer to data of any type, default is a null pointer. - -Returns a `Napi::PropertyDescriptor` that contains a `Getter` and `Setter` function. - -The name of the property can be any of the following types: -- `const char*` -- `const std::string &` -- `napi_value value` -- `Napi::Name` - -**This signature is deprecated. It will result in a memory leak if used.** - -```cpp -static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor ( - Napi::Env env, - Napi::Object object, - ___ name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void *data = nullptr); -``` - -* `[in] env`: The environemnt in which to create this accessor. -* `[in] object`: The object on which the accessor will be defined. -* `[in] name`: The name of the getter and setter function. -* `[in] getter`: The getter function. -* `[in] setter`: The setter function. -* `[in] attributes`: Potential attributes for the getter function. -* `[in] data`: A pointer to data of any type, default is a null pointer. - -Returns a `Napi::PropertyDescriptor` that contains a `Getter` and `Setter` function. - -The name of the property can be any of the following types: -- `const char*` -- `const std::string &` -- `Napi::Name` - -### Function - -```cpp -static Napi::PropertyDescriptor Napi::PropertyDescriptor::Function (___ name, - Callable cb, - napi_property_attributes attributes = napi_default, - void *data = nullptr); -``` - -* `[in] name`: The name of the Callable function. -* `[in] cb`: The function -* `[in] attributes`: Potential attributes for the getter function. -* `[in] data`: A pointer to data of any type, default is a null pointer. - -Returns a `Napi::PropertyDescriptor` that contains a callable `Napi::Function`. - -The name of the property can be any of the following types: -- `const char*` -- `const std::string &` -- `napi_value value` -- `Napi::Name` - -**This signature is deprecated. It will result in a memory leak if used.** - -```cpp -static Napi::PropertyDescriptor Napi::PropertyDescriptor::Function ( - Napi::Env env, - ___ name, - Callable cb, - napi_property_attributes attributes = napi_default, - void *data = nullptr); -``` - -* `[in] env`: The environment in which to create this accessor. -* `[in] name`: The name of the Callable function. -* `[in] cb`: The function -* `[in] attributes`: Potential attributes for the getter function. -* `[in] data`: A pointer to data of any type, default is a null pointer. - -Returns a `Napi::PropertyDescriptor` that contains a callable `Napi::Function`. - -The name of the property can be any of the following types: -- `const char*` -- `const std::string &` -- `Napi::Name` - -### Value - -```cpp -static Napi::PropertyDescriptor Napi::PropertyDescriptor::Value (___ name, - napi_value value, - napi_property_attributes attributes = napi_default); -``` - -The name of the property can be any of the following types: -- `const char*` -- `const std::string &` -- `napi_value value` -- `Napi::Name` - -## Related Information - -### napi\_property\_attributes -`napi_property_attributes` are flags used to indicate to JavaScript certain permissions that the property is meant to have. The following are the flag options: -- napi\_default, -- napi\_writable, -- napi\_enumerable, -- napi\_configurable -For more information on the flags and on napi\_property\_attributes, please read the documentation [here](https://github.com/nodejs/node/blob/master/doc/api/n-api.md#napi_property_attributes). - diff --git a/node_modules/node-addon-api/doc/range_error.md b/node_modules/node-addon-api/doc/range_error.md deleted file mode 100644 index e134a40..0000000 --- a/node_modules/node-addon-api/doc/range_error.md +++ /dev/null @@ -1,59 +0,0 @@ -# RangeError - -The `Napi::RangeError` class is a representation of the JavaScript `RangeError` that is -thrown when trying to pass a value as an argument to a function that does not allow -a range that includes the value. - -The `Napi::RangeError` class inherits its behaviors from the `Napi::Error` class (for -more info see: [`Napi::Error`](error.md)). - -For more details about error handling refer to the section titled [Error handling](error_handling.md). - -## Methods - -### New - -Creates a new instance of a `Napi::RangeError` object. - -```cpp -Napi::RangeError::New(Napi::Env env, const char* message); -``` - -- `[in] Env`: The environment in which to construct the `Napi::RangeError` object. -- `[in] message`: Null-terminated string to be used as the message for the `Napi::RangeError`. - -Returns an instance of a `Napi::RangeError` object. - -### New - -Creates a new instance of a `Napi::RangeError` object. - -```cpp -Napi::RangeError::New(Napi::Env env, const std::string& message); -``` - -- `[in] Env`: The environment in which to construct the `Napi::RangeError` object. -- `[in] message`: Reference string to be used as the message for the `Napi::RangeError`. - -Returns an instance of a `Napi::RangeError` object. - -### Constructor - -Creates a new empty instance of a `Napi::RangeError`. - -```cpp -Napi::RangeError::RangeError(); -``` - -### Constructor - -Initializes a `Napi::RangeError` instance from an existing Javascript error object. - -```cpp -Napi::RangeError::RangeError(napi_env env, napi_value value); -``` - -- `[in] Env`: The environment in which to construct the `Napi::RangeError` object. -- `[in] value`: The `Napi::Error` reference to wrap. - -Returns an instance of a `Napi::RangeError` object. diff --git a/node_modules/node-addon-api/doc/reference.md b/node_modules/node-addon-api/doc/reference.md deleted file mode 100644 index 108c009..0000000 --- a/node_modules/node-addon-api/doc/reference.md +++ /dev/null @@ -1,111 +0,0 @@ -# Reference (template) - -Holds a counted reference to a [`Napi::Value`](value.md) object; initially a weak reference unless otherwise specified, may be changed to/from a strong reference by adjusting the refcount. - -The referenced `Napi::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 `Napi::Value`. - -`Napi::Reference` objects allocated in static space, such as a global static instance, must call the `SuppressDestruct` method to prevent its destructor, running at program shutdown time, from attempting to reset the reference when the environment is no longer valid. - -The following classes inherit, either directly or indirectly, from `Napi::Reference`: - -* [`Napi::ObjectWrap`](object_wrap.md) -* [`Napi::ObjectReference`](object_reference.md) -* [`Napi::FunctionReference`](function_reference.md) - -## Methods - -### Factory Method - -```cpp -static Napi::Reference<T> Napi::Reference::New(const T& value, uint32_t initialRefcount = 0); -``` - -* `[in] value`: The value which is to be referenced. - -* `[in] initialRefcount`: The initial reference count. - -### Empty Constructor - -```cpp -Napi::Reference::Reference(); -``` - -Creates a new _empty_ `Napi::Reference` instance. - -### Constructor - -```cpp -Napi::Reference::Reference(napi_env env, napi_value value); -``` - -* `[in] env`: The `napi_env` environment in which to construct the `Napi::Reference` object. - -* `[in] value`: The N-API primitive value to be held by the `Napi::Reference`. - -### Env - -```cpp -Napi::Env Napi::Reference::Env() const; -``` - -Returns the `Napi::Env` value in which the `Napi::Reference` was instantiated. - -### IsEmpty - -```cpp -bool Napi::Reference::IsEmpty() const; -``` - -Determines whether the value held by the `Napi::Reference` is empty. - -### Value - -```cpp -T Napi::Reference::Value() const; -``` - -Returns the value held by the `Napi::Reference`. - -### Ref - -```cpp -uint32_t Napi::Reference::Ref(); -``` - -Increments the reference count for the `Napi::Reference` and returns the resulting reference count. Throws an error if the increment fails. - -### Unref - -```cpp -uint32_t Napi::Reference::Unref(); -``` - -Decrements the reference count for the `Napi::Reference` and returns the resulting reference count. Throws an error if the decrement fails. - -### Reset (Empty) - -```cpp -void Napi::Reference::Reset(); -``` - -Sets the value held by the `Napi::Reference` to be empty. - -### Reset - -```cpp -void Napi::Reference::Reset(const T& value, uint32_t refcount = 0); -``` - -* `[in] value`: The value which is to be referenced. - -* `[in] initialRefcount`: The initial reference count. - -Sets the value held by the `Napi::Reference`. - -### SuppressDestruct - -```cpp -void Napi::Reference::SuppressDestruct(); -``` - -Call this method on a `Napi::Reference` that is declared as static data to prevent its destructor, running at program shutdown time, from attempting to reset the reference when the environment is no longer valid. diff --git a/node_modules/node-addon-api/doc/setup.md b/node_modules/node-addon-api/doc/setup.md deleted file mode 100644 index 3135bf1..0000000 --- a/node_modules/node-addon-api/doc/setup.md +++ /dev/null @@ -1,82 +0,0 @@ -# Setup - -## Prerequisites - -Before starting to use **N-API** you need to assure you have the following -prerequisites: - -* **Node.JS** see: [Installing Node.js](https://nodejs.org/) - -* **Node.js native addon build tool** - - - **[node-gyp](node-gyp.md)** - -## Installation and usage - -To use **N-API** in a native module: - - 1. Add a dependency on this package to `package.json`: - -```json - "dependencies": { - "node-addon-api": "*", - } -``` - - 2. Reference this package's include directory and gyp file in `binding.gyp`: - -```gyp - 'include_dirs': ["<!@(node -p \"require('node-addon-api').include\")"], - 'dependencies': ["<!(node -p \"require('node-addon-api').gyp\")"], -``` - - 3. Decide whether the package will enable C++ exceptions in the N-API wrapper. - The base ABI-stable C APIs do not throw or handle C++ exceptions, but the - N-API C++ wrapper classes may _optionally_ - [integrate C++ and JavaScript exception-handling - ](https://nodejs.github.io/node-addon-api/class_napi_1_1_error.html). - To enable that capability, C++ exceptions must be enabled in `binding.gyp`: - -```gyp - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', - 'CLANG_CXX_LIBRARY': 'libc++', - 'MACOSX_DEPLOYMENT_TARGET': '10.7', - }, - 'msvs_settings': { - 'VCCLCompilerTool': { 'ExceptionHandling': 1 }, - }, -``` - - Alternatively, disable use of C++ exceptions in N-API: - -```gyp - 'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ], -``` - 4. If you would like your native addon to support OSX, please also add the - following settings in the `binding.gyp` file: - - ```gyp - ['OS=="mac"', { - 'cflags+': ['-fvisibility=hidden'], - 'xcode_settings': { - 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden - } - }] - ``` - - 5. Include `napi.h` in the native module code. - To ensure only ABI-stable APIs are used, DO NOT include - `node.h`, `nan.h`, or `v8.h`. - -```C++ -#include "napi.h" -``` - -At build time, the N-API back-compat library code will be used only when the -targeted node version *does not* have N-API built-in. - -The preprocessor directive `NODE_ADDON_API_DISABLE_DEPRECATED` can be defined at -compile time before including `napi.h` to skip the definition of deprecated APIs. diff --git a/node_modules/node-addon-api/doc/string.md b/node_modules/node-addon-api/doc/string.md deleted file mode 100644 index bf78ac7..0000000 --- a/node_modules/node-addon-api/doc/string.md +++ /dev/null @@ -1,89 +0,0 @@ -# String - -## Constructor - -```cpp -Napi::String::String(); -``` - -Returns a new **empty** `Napi::String` instance. - -If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not -being used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -```cpp -Napi::String::String(napi_env env, napi_value value); ///< Wraps a N-API value primitive. -``` -- `[in] env` - The environment in which to create the string. -- `[in] value` - The primitive to wrap. - -Returns a `Napi::String` wrapping a `napi_value`. - -If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not -being used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -## Operators - -### operator std::string - -```cpp -Napi::String::operator std::string() const; -``` - -Returns a UTF-8 encoded C++ string. - -### operator std::u16string -```cpp -Napi::String::operator std::u16string() const; -``` - -Returns a UTF-16 encoded C++ string. - -## Methods - -### New -```cpp -Napi::String::New(); -``` - -Returns a new empty `Napi::String`. - -### New -```cpp -Napi::String::New(napi_env env, const std::string& value); -Napi::String::New(napi_env env, const std::u16::string& value); -Napi::String::New(napi_env env, const char* value); -Napi::String::New(napi_env env, const char16_t* value); -Napi::String::New(napi_env env, const char* value, size_t length); -Napi::String::New(napi_env env, const char16_t* value, size_t length); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Value` object. -- `[in] value`: The C++ primitive from which to instantiate the `Napi::Value`. `value` may be any of: - - `std::string&` - represents an ANSI string. - - `std::u16string&` - represents a UTF16-LE string. - - `const char*` - represents a UTF8 string. - - `const char16_t*` - represents a UTF16-LE string. -- `[in] length`: The length of the string (not necessarily null-terminated) in code units. - -Returns a new `Napi::String` that represents the passed in C++ string. - -If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not -being used, callers should check the result of `Env::IsExceptionPending` before -attempting to use the returned value. - -### Utf8Value -```cpp -std::string Napi::String::Utf8Value() const; -``` - -Returns a UTF-8 encoded C++ string. - -### Utf16Value -```cpp -std::u16string Napi::String::Utf16Value() const; -``` - -Returns a UTF-16 encoded C++ string. diff --git a/node_modules/node-addon-api/doc/symbol.md b/node_modules/node-addon-api/doc/symbol.md deleted file mode 100644 index 13abe3e..0000000 --- a/node_modules/node-addon-api/doc/symbol.md +++ /dev/null @@ -1,44 +0,0 @@ -# Symbol - -## Methods - -### Constructor - -Instantiates a new `Napi::Symbol` value. - -```cpp -Napi::Symbol::Symbol(); -``` - -Returns a new empty `Napi::Symbol`. - -### New -```cpp -Napi::Symbol::New(napi_env env, const std::string& description); -Napi::Symbol::New(napi_env env, const char* description); -Napi::Symbol::New(napi_env env, Napi::String description); -Napi::Symbol::New(napi_env env, napi_value description); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Symbol` object. -- `[in] value`: The C++ primitive which represents the description hint for the `Napi::Symbol`. - `description` may be any of: - - `std::string&` - ANSI string description. - - `const char*` - represents a UTF8 string description. - - `String` - Node addon API String description. - - `napi_value` - N-API `napi_value` description. - -If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not -being used, callers should check the result of `Napi::Env::IsExceptionPending` before -attempting to use the returned value. - -### Utf8Value -```cpp -static Napi::Symbol Napi::Symbol::WellKnown(napi_env env, const std::string& name); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Symbol` object. -- `[in] name`: The C++ string representing the `Napi::Symbol` to retrieve. - -Returns a `Napi::Symbol` representing a well-known `Symbol` from the -`Symbol` registry. diff --git a/node_modules/node-addon-api/doc/threadsafe_function.md b/node_modules/node-addon-api/doc/threadsafe_function.md deleted file mode 100644 index 2bd8b67..0000000 --- a/node_modules/node-addon-api/doc/threadsafe_function.md +++ /dev/null @@ -1,320 +0,0 @@ -# ThreadSafeFunction - -JavaScript functions can normally only be called from a native addon's main -thread. If an addon creates additional threads, then node-addon-api functions -that require a `Napi::Env`, `Napi::Value`, or `Napi::Reference` must not be -called from those threads. - -When an addon has additional threads and JavaScript functions need to be invoked -based on the processing completed by those threads, those threads must -communicate with the addon's main thread so that the main thread can invoke the -JavaScript function on their behalf. The thread-safe function APIs provide an -easy way to do this. - -These APIs provide the type `Napi::ThreadSafeFunction` as well as APIs to -create, destroy, and call objects of this type. -`Napi::ThreadSafeFunction::New()` creates a persistent reference that holds a -JavaScript function which can be called from multiple threads. The calls happen -asynchronously. This means that values with which the JavaScript callback is to -be called will be placed in a queue, and, for each value in the queue, a call -will eventually be made to the JavaScript function. - -`Napi::ThreadSafeFunction` objects are destroyed when every thread which uses -the object has called `Release()` or has received a return status of -`napi_closing` in response to a call to `BlockingCall()` or `NonBlockingCall()`. -The queue is emptied before the `Napi::ThreadSafeFunction` is destroyed. It is -important that `Release()` be the last API call made in conjunction with a given -`Napi::ThreadSafeFunction`, because after the call completes, there is no -guarantee that the `Napi::ThreadSafeFunction` is still allocated. For the same -reason it is also important that no more use be made of a thread-safe function -after receiving a return value of `napi_closing` in response to a call to -`BlockingCall()` or `NonBlockingCall()`. Data associated with the -`Napi::ThreadSafeFunction` can be freed in its `Finalizer` callback which was -passed to `ThreadSafeFunction::New()`. - -Once the number of threads making use of a `Napi::ThreadSafeFunction` reaches -zero, no further threads can start making use of it by calling `Acquire()`. In -fact, all subsequent API calls associated with it, except `Release()`, will -return an error value of `napi_closing`. - -## Methods - -### Constructor - -Creates a new empty instance of `Napi::ThreadSafeFunction`. - -```cpp -Napi::Function::ThreadSafeFunction(); -``` - -### Constructor - -Creates a new instance of the `Napi::ThreadSafeFunction` object. - -```cpp -Napi::ThreadSafeFunction::ThreadSafeFunction(napi_threadsafe_function tsfn); -``` - -- `tsfn`: The `napi_threadsafe_function` which is a handle for an existing - thread-safe function. - -Returns a non-empty `Napi::ThreadSafeFunction` instance. When using this -constructor, only use the `Blocking(void*)` / `NonBlocking(void*)` overloads; -the `Callback` and templated `data*` overloads should _not_ be used. See below -for additional details. - -### New - -Creates a new instance of the `Napi::ThreadSafeFunction` object. The `New` -function has several overloads for the various optional parameters: skip the -optional parameter for that specific overload. - -```cpp -New(napi_env env, - const Function& callback, - const Object& resource, - ResourceString resourceName, - size_t maxQueueSize, - size_t initialThreadCount, - ContextType* context, - Finalizer finalizeCallback, - FinalizerDataType* data); -``` - -- `env`: The `napi_env` environment in which to construct the - `Napi::ThreadSafeFunction` object. -- `callback`: The `Function` to call from another thread. -- `[optional] resource`: An object associated with the async work that will be - passed to possible async_hooks init hooks. -- `resourceName`: A JavaScript string to provide an identifier for the kind of - resource that is being provided for diagnostic information exposed by the - async_hooks API. -- `maxQueueSize`: Maximum size of the queue. `0` for no limit. -- `initialThreadCount`: The initial number of threads, including the main - thread, which will be making use of this function. -- `[optional] context`: Data to attach to the resulting `ThreadSafeFunction`. -- `[optional] finalizeCallback`: Function to call when the `ThreadSafeFunction` - is being destroyed. This callback will be invoked on the main thread when the - thread-safe function is about to be destroyed. It receives the context and the - finalize data given during construction (if given), and provides an - opportunity for cleaning up after the threads e.g. by calling - `uv_thread_join()`. It is important that, aside from the main loop thread, - there be no threads left using the thread-safe function after the finalize - callback completes. Must implement `void operator()(Env env, DataType* data, - Context* hint)`, skipping `data` or `hint` if they are not provided. - Can be retreived via `GetContext()`. -- `[optional] data`: Data to be passed to `finalizeCallback`. - -Returns a non-empty `Napi::ThreadSafeFunction` instance. - -### Acquire - -Add a thread to this thread-safe function object, indicating that a new thread -will start making use of the thread-safe function. - -```cpp -napi_status Napi::ThreadSafeFunction::Acquire() -``` - -Returns one of: -- `napi_ok`: The thread has successfully acquired the thread-safe function -for its use. -- `napi_closing`: The thread-safe function has been marked as closing via a -previous call to `Abort()`. - -### Release - -Indicate that an existing thread will stop making use of the thread-safe -function. A thread should call this API when it stops making use of this -thread-safe function. Using any thread-safe APIs after having called this API -has undefined results in the current thread, as it may have been destroyed. - -```cpp -napi_status Napi::ThreadSafeFunction::Release() -``` - -Returns one of: -- `napi_ok`: The thread-safe function has been successfully released. -- `napi_invalid_arg`: The thread-safe function's thread-count is zero. -- `napi_generic_failure`: A generic error occurred when attemping to release -the thread-safe function. - -### Abort - -"Abort" the thread-safe function. This will cause all subsequent APIs associated -with the thread-safe function except `Release()` to return `napi_closing` even -before its reference count reaches zero. In particular, `BlockingCall` and -`NonBlockingCall()` will return `napi_closing`, thus informing the threads that -it is no longer possible to make asynchronous calls to the thread-safe function. -This can be used as a criterion for terminating the thread. Upon receiving a -return value of `napi_closing` from a thread-safe function call a thread must -make no further use of the thread-safe function because it is no longer -guaranteed to be allocated. - -```cpp -napi_status Napi::ThreadSafeFunction::Abort() -``` - -Returns one of: -- `napi_ok`: The thread-safe function has been successfully aborted. -- `napi_invalid_arg`: The thread-safe function's thread-count is zero. -- `napi_generic_failure`: A generic error occurred when attemping to abort -the thread-safe function. - -### BlockingCall / NonBlockingCall - -Calls the Javascript function in either a blocking or non-blocking fashion. -- `BlockingCall()`: the API blocks until space becomes available in the queue. - Will never block if the thread-safe function was created with a maximum queue - size of `0`. -- `NonBlockingCall()`: will return `napi_queue_full` if the queue was full, - preventing data from being successfully added to the queue. - -There are several overloaded implementations of `BlockingCall()` and -`NonBlockingCall()` for use with optional parameters: skip the optional -parameter for that specific overload. - -**These specific function overloads should only be used on a `ThreadSafeFunction` -created via `ThreadSafeFunction::New`.** - -```cpp -napi_status Napi::ThreadSafeFunction::BlockingCall(DataType* data, Callback callback) const - -napi_status Napi::ThreadSafeFunction::NonBlockingCall(DataType* data, Callback callback) const -``` - -- `[optional] data`: Data to pass to `callback`. -- `[optional] callback`: C++ function that is invoked on the main thread. The - callback receives the `ThreadSafeFunction`'s JavaScript callback function to - call as an `Napi::Function` in its parameters and the `DataType*` data pointer - (if provided). Must implement `void operator()(Napi::Env env, Function - jsCallback, DataType* data)`, skipping `data` if not provided. It is not - necessary to call into JavaScript via `MakeCallback()` because N-API runs - `callback` in a context appropriate for callbacks. - -**These specific function overloads should only be used on a `ThreadSafeFunction` -created via `ThreadSafeFunction(napi_threadsafe_function)`.** - -```cpp -napi_status Napi::ThreadSafeFunction::BlockingCall(void* data) const - -napi_status Napi::ThreadSafeFunction::NonBlockingCall(void* data) const -``` -- `data`: Data to pass to `call_js_cb` specified when creating the thread-safe - function via `napi_create_threadsafe_function`. - -Returns one of: -- `napi_ok`: The call was successfully added to the queue. -- `napi_queue_full`: The queue was full when trying to call in a non-blocking - method. -- `napi_closing`: The thread-safe function is aborted and cannot accept more - calls. -- `napi_invalid_arg`: The thread-safe function is closed. -- `napi_generic_failure`: A generic error occurred when attemping to add to the - queue. - -## Example - -```cpp -#include <chrono> -#include <thread> -#include <napi.h> - -using namespace Napi; - -std::thread nativeThread; -ThreadSafeFunction tsfn; - -Value Start( const CallbackInfo& info ) -{ - Napi::Env env = info.Env(); - - if ( info.Length() < 2 ) - { - throw TypeError::New( env, "Expected two arguments" ); - } - else if ( !info[0].IsFunction() ) - { - throw TypeError::New( env, "Expected first arg to be function" ); - } - else if ( !info[1].IsNumber() ) - { - throw TypeError::New( env, "Expected second arg to be number" ); - } - - int count = info[1].As<Number>().Int32Value(); - - // Create a ThreadSafeFunction - tsfn = ThreadSafeFunction::New( - env, - info[0].As<Function>(), // JavaScript function called asynchronously - "Resource Name", // Name - 0, // Unlimited queue - 1, // Only one thread will use this initially - []( Napi::Env ) { // Finalizer used to clean threads up - nativeThread.join(); - } ); - - // Create a native thread - nativeThread = std::thread( [count] { - auto callback = []( Napi::Env env, Function jsCallback, int* value ) { - // Transform native data into JS data, passing it to the provided - // `jsCallback` -- the TSFN's JavaScript function. - jsCallback.Call( {Number::New( env, *value )} ); - - // We're finished with the data. - delete value; - }; - - for ( int i = 0; i < count; i++ ) - { - // Create new data - int* value = new int( clock() ); - - // Perform a blocking call - napi_status status = tsfn.BlockingCall( value, callback ); - if ( status != napi_ok ) - { - // Handle error - break; - } - - std::this_thread::sleep_for( std::chrono::seconds( 1 ) ); - } - - // Release the thread-safe function - tsfn.Release(); - } ); - - return Boolean::New(env, true); -} - -Napi::Object Init( Napi::Env env, Object exports ) -{ - exports.Set( "start", Function::New( env, Start ) ); - return exports; -} - -NODE_API_MODULE( clock, Init ) -``` - -The above code can be used from JavaScript as follows: - -```js -const { start } = require('bindings')('clock'); - -start(function () { - console.log("JavaScript callback called with arguments", Array.from(arguments)); -}, 5); -``` - -When executed, the output will show the value of `clock()` five times at one -second intervals: - -``` -JavaScript callback called with arguments [ 84745 ] -JavaScript callback called with arguments [ 103211 ] -JavaScript callback called with arguments [ 104516 ] -JavaScript callback called with arguments [ 105104 ] -JavaScript callback called with arguments [ 105691 ] -``` diff --git a/node_modules/node-addon-api/doc/type_error.md b/node_modules/node-addon-api/doc/type_error.md deleted file mode 100644 index 24bbf8e..0000000 --- a/node_modules/node-addon-api/doc/type_error.md +++ /dev/null @@ -1,59 +0,0 @@ -# TypeError - -The `Napi::TypeError` class is a representation of the JavaScript `TypeError` that is -thrown when an operand or argument passed to a function is incompatible with the -type expected by the operator or function. - -The `Napi::TypeError` class inherits its behaviors from the `Napi::Error` class (for more info -see: [`Napi::Error`](error.md)). - -For more details about error handling refer to the section titled [Error handling](error_handling.md). - -## Methods - -### New - -Creates a new instance of the `Napi::TypeError` object. - -```cpp -Napi::TypeError::New(Napi:Env env, const char* message); -``` - -- `[in] Env`: The environment in which to construct the `Napi::TypeError` object. -- `[in] message`: Null-terminated string to be used as the message for the `Napi::TypeError`. - -Returns an instance of a `Napi::TypeError` object. - -### New - -Creates a new instance of a `Napi::TypeError` object. - -```cpp -Napi::TypeError::New(Napi:Env env, const std::string& message); -``` - -- `[in] Env`: The environment in which to construct the `Napi::TypeError` object. -- `[in] message`: Reference string to be used as the message for the `Napi::TypeError`. - -Returns an instance of a `Napi::TypeError` object. - -### Constructor - -Creates a new empty instance of a `Napi::TypeError`. - -```cpp -Napi::TypeError::TypeError(); -``` - -### Constructor - -Initializes a `Napi::TypeError` instance from an existing JavaScript error object. - -```cpp -Napi::TypeError::TypeError(napi_env env, napi_value value); -``` - -- `[in] Env`: The environment in which to construct the `Napi::TypeError` object. -- `[in] value`: The `Napi::Error` reference to wrap. - -Returns an instance of a `Napi::TypeError` object. diff --git a/node_modules/node-addon-api/doc/typed_array.md b/node_modules/node-addon-api/doc/typed_array.md deleted file mode 100644 index ced67d8..0000000 --- a/node_modules/node-addon-api/doc/typed_array.md +++ /dev/null @@ -1,74 +0,0 @@ -# TypedArray - -The `Napi::TypedArray` class corresponds to the -[JavaScript `TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) -class. - -## Methods - -### Constructor - -Initializes an empty instance of the `Napi::TypedArray` class. - -```cpp -Napi::TypedArray::TypedArray(); -``` - -### Constructor - -Initializes a wrapper instance of an existing `Napi::TypedArray` instance. - -```cpp -Napi::TypedArray::TypedArray(napi_env env, napi_value value); -``` - -- `[in] env`: The environment in which to create the `Napi::TypedArray` instance. -- `[in] value`: The `Napi::TypedArray` reference to wrap. - -### TypedArrayType - -```cpp -napi_typedarray_type Napi::TypedArray::TypedArrayType() const; -``` - -Returns the type of this instance. - -### ArrayBuffer - -```cpp -Napi::ArrayBuffer Napi::TypedArray::ArrayBuffer() const; -``` - -Returns the backing array buffer. - -### ElementSize - -```cpp -uint8_t Napi::TypedArray::ElementSize() const; -``` - -Returns the size of one element, in bytes. - -### ElementLength - -```cpp -size_t Napi::TypedArray::ElementLength() const; -``` - -Returns the number of elements. - -### ByteOffset - -```cpp -size_t Napi::TypedArray::ByteOffset() const; -``` - -Returns the offset into the `Napi::ArrayBuffer` where the array starts, in bytes. - -### ByteLength - -```cpp -size_t Napi::TypedArray::ByteLength() const; -``` - -Returns the length of the array, in bytes. diff --git a/node_modules/node-addon-api/doc/typed_array_of.md b/node_modules/node-addon-api/doc/typed_array_of.md deleted file mode 100644 index fc30218..0000000 --- a/node_modules/node-addon-api/doc/typed_array_of.md +++ /dev/null @@ -1,133 +0,0 @@ -# TypedArrayOf - -The `Napi::TypedArrayOf` class corresponds to the various -[JavaScript `TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) -classes. - -## Typedefs - -The common JavaScript `TypedArray` types are pre-defined for each of use: - -```cpp -typedef Napi::TypedArrayOf<int8_t> Int8Array; -typedef Napi::TypedArrayOf<uint8_t> Uint8Array; -typedef Napi::TypedArrayOf<int16_t> Int16Array; -typedef Napi::TypedArrayOf<uint16_t> Uint16Array; -typedef Napi::TypedArrayOf<int32_t> Int32Array; -typedef Napi::TypedArrayOf<uint32_t> Uint32Array; -typedef Napi::TypedArrayOf<float> Float32Array; -typedef Napi::TypedArrayOf<double> Float64Array; -``` - -The one exception is the `Uint8ClampedArray` which requires explicit -initialization: - -```cpp -Uint8Array::New(env, length, napi_uint8_clamped_array) -``` - -Note that while it's possible to create a "clamped" array the _clamping_ -behavior is only applied in JavaScript. - -## Methods - -### New - -Allocates a new `Napi::TypedArray` instance with a given length. The underlying -`Napi::ArrayBuffer` is allocated automatically to the desired number of elements. - -The array type parameter can normally be omitted (because it is inferred from -the template parameter T), except when creating a "clamped" array. - -```cpp -static Napi::TypedArrayOf Napi::TypedArrayOf::New(napi_env env, - size_t elementLength, - napi_typedarray_type type); -``` - -- `[in] env`: The environment in which to create the `Napi::TypedArrayOf` instance. -- `[in] elementLength`: The length to be allocated, in elements. -- `[in] type`: The type of array to allocate (optional). - -Returns a new `Napi::TypedArrayOf` instance. - -### New - -Wraps the provided `Napi::ArrayBuffer` into a new `Napi::TypedArray` instance. - -The array `type` parameter can normally be omitted (because it is inferred from -the template parameter `T`), except when creating a "clamped" array. - -```cpp -static Napi::TypedArrayOf Napi::TypedArrayOf::New(napi_env env, - size_t elementLength, - Napi::ArrayBuffer arrayBuffer, - size_t bufferOffset, - napi_typedarray_type type); -``` - -- `[in] env`: The environment in which to create the `Napi::TypedArrayOf` instance. -- `[in] elementLength`: The length to array, in elements. -- `[in] arrayBuffer`: The backing `Napi::ArrayBuffer` instance. -- `[in] bufferOffset`: The offset into the `Napi::ArrayBuffer` where the array starts, - in bytes. -- `[in] type`: The type of array to allocate (optional). - -Returns a new `Napi::TypedArrayOf` instance. - -### Constructor - -Initializes an empty instance of the `Napi::TypedArrayOf` class. - -```cpp -Napi::TypedArrayOf::TypedArrayOf(); -``` - -### Constructor - -Initializes a wrapper instance of an existing `Napi::TypedArrayOf` object. - -```cpp -Napi::TypedArrayOf::TypedArrayOf(napi_env env, napi_value value); -``` - -- `[in] env`: The environment in which to create the `Napi::TypedArrayOf` object. -- `[in] value`: The `Napi::TypedArrayOf` reference to wrap. - -### operator [] - -```cpp -T& Napi::TypedArrayOf::operator [](size_t index); -``` - -- `[in] index: The element index into the array. - -Returns the element found at the given index. - -### operator [] - -```cpp -const T& Napi::TypedArrayOf::operator [](size_t index) const; -``` - -- `[in] index: The element index into the array. - -Returns the element found at the given index. - -### Data - -```cpp -T* Napi::TypedArrayOf::Data() const; -``` - -Returns a pointer into the backing `Napi::ArrayBuffer` which is offset to point to the -start of the array. - -### Data - -```cpp -const T* Napi::TypedArrayOf::Data() const -``` - -Returns a pointer into the backing `Napi::ArrayBuffer` which is offset to point to the -start of the array. diff --git a/node_modules/node-addon-api/doc/value.md b/node_modules/node-addon-api/doc/value.md deleted file mode 100644 index 2d25eb7..0000000 --- a/node_modules/node-addon-api/doc/value.md +++ /dev/null @@ -1,278 +0,0 @@ -# Value - -`Napi::Value` is the C++ manifestation of a JavaScript value. - -Value is a the base class upon which other JavaScript values such as Number, Boolean, String, and Object are based. - -The following classes inherit, either directly or indirectly, from `Napi::Value`: - -- [`Napi::Array`](array.md) -- [`Napi::ArrayBuffer`](array_buffer.md) -- [`Napi::Boolean`](boolean.md) -- [`Napi::Buffer`](buffer.md) -- [`Napi::Date`](date.md) -- [`Napi::External`](external.md) -- [`Napi::Function`](function.md) -- [`Napi::Name`](name.md) -- [`Napi::Number`](number.md) -- [`Napi::Object`](object.md) -- [`Napi::String`](string.md) -- [`Napi::Symbol`](symbol.md) -- [`Napi::TypedArray`](typed_array.md) -- [`Napi::TypedArrayOf`](typed_array_of.md) - -## Methods - -### Empty Constructor - -```cpp -Napi::Value::Value(); -``` - -Creates a new *empty* `Napi::Value` instance. - -### Constructor - -```cpp -Napi::Value::Value(napi_env env, napi_value value); -``` - -- `[in] env`: The `napi_env` environment in which to construct the `Napi::Value` object. - -- `[in] value`: The C++ primitive from which to instantiate the `Napi::Value`. `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` - -### From - -```cpp -template <typename T> static Napi::Value Napi::Value::From(napi_env env, const T& value); -``` - -- `[in] env`: The `napi_env` environment in which to create the `Napi::Value` object. - -- `[in] value`: The N-API primitive value from which to create the `Napi::Value` object. - -Returns a `Napi::Value` object from an N-API primitive value. - -### operator napi_value - -```cpp -operator napi_value() const; -``` - -Returns this Value's N-API value primitive. - -Returns `nullptr` if this `Napi::Value` is *empty*. - -### operator == - -```cpp - -bool Napi::Value::operator ==(const Napi::Value& other) const; -``` - -- `[in] other`: The `Napi::Value` object to be compared. - -Returns a `bool` indicating if this `Napi::Value` strictly equals another `Napi::Value`. - -### operator != - -```cpp -bool Napi::Value::operator !=(const Napi::Value& other) const; -``` - -- `[in] other`: The `Napi::Value` object to be compared. - -Returns a `bool` indicating if this `Napi::Value` does not strictly equal another `Napi::Value`. - -### StrictEquals - -```cpp -bool Napi::Value::StrictEquals(const Napi::Value& other) const; -``` -- `[in] other`: The `Napi::Value` object to be compared. - -Returns a `bool` indicating if this `Napi::Value` strictly equals another `Napi::Value`. - -### Env - -```cpp -Napi::Env Napi::Value::Env() const; -``` - -Returns the `Napi::Env` environment this value is associated with. - -### IsEmpty - -```cpp -bool Napi::Value::IsEmpty() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is *empty* (uninitialized). - -An empty `Napi::Value` is invalid, and most attempts to perform an operation on an empty Value will result in an exception. -Note an empty `Napi::Value` is distinct from JavaScript `null` or `undefined`, which are valid values. - -When C++ exceptions are disabled at compile time, a method with a `Napi::Value` return type may return an empty Value to indicate a pending exception. So when not using C++ exceptions, callers should check whether this `Napi::Value` is empty before attempting to use it. - -### Type - -```cpp -napi_valuetype Napi::Value::Type() const; -``` - -Returns the `napi_valuetype` type of the `Napi::Value`. - -### IsUndefined - -```cpp -bool Napi::Value::IsUndefined() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is an undefined JavaScript value. - -### IsNull - -```cpp -bool Napi::Value::IsNull() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a null JavaScript value. - -### IsBoolean - -```cpp -bool Napi::Value::IsBoolean() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript boolean. - -### IsNumber - -```cpp -bool Napi::Value::IsNumber() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript number. - -### IsString - -```cpp -bool Napi::Value::IsString() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript string. - -### IsSymbol - -```cpp -bool Napi::Value::IsSymbol() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript symbol. - -### IsArray - -```cpp -bool Napi::Value::IsArray() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript array. - -### IsArrayBuffer - -```cpp -bool Napi::Value::IsArrayBuffer() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript array buffer. - -### IsTypedArray - -```cpp -bool Napi::Value::IsTypedArray() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript typed array. - -### IsObject - -```cpp -bool Napi::Value::IsObject() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is JavaScript object. - -### IsFunction - -```cpp -bool Napi::Value::IsFunction() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript function. - -### IsBuffer - -```cpp -bool Napi::Value::IsBuffer() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a Node buffer. - -### IsDate - -```cpp -bool Napi::Value::IsDate() const; -``` - -Returns a `bool` indicating if this `Napi::Value` is a JavaScript date. - -### As - -```cpp -template <typename T> T Napi::Value::As() const; -``` - -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`. - -### ToBoolean - -```cpp -Napi::Boolean Napi::Value::ToBoolean() const; -``` - -Returns the `Napi::Value` coerced to a JavaScript boolean. - -### ToNumber - -```cpp -Napi::Number Napi::Value::ToNumber() const; -``` - -Returns the `Napi::Value` coerced to a JavaScript number. - -### ToString - -```cpp -Napi::String Napi::Value::ToString() const; -``` - -Returns the `Napi::Value` coerced to a JavaScript string. - -### ToObject - -```cpp -Napi::Object Napi::Value::ToObject() const; -``` - -Returns the `Napi::Value` coerced to a JavaScript object. diff --git a/node_modules/node-addon-api/doc/version_management.md b/node_modules/node-addon-api/doc/version_management.md deleted file mode 100644 index 6d6c7fa..0000000 --- a/node_modules/node-addon-api/doc/version_management.md +++ /dev/null @@ -1,43 +0,0 @@ -# VersionManagement - -The `Napi::VersionManagement` class contains methods that allow information -to be retrieved about the version of N-API and Node.js. In some cases it is -important to make decisions based on different versions of the system. - -## Methods - -### GetNapiVersion - -Retrieves the highest N-API version supported by Node.js runtime. - -```cpp -static uint32_t Napi::VersionManagement::GetNapiVersion(Env env); -``` - -- `[in] env`: The environment in which the API is invoked under. - -Returns the highest N-API version supported by Node.js runtime. - -### GetNodeVersion - -Retrives information about Node.js version present on the system. All the -information is stored in the `napi_node_version` structrue that is defined as -shown below: - -```cpp -typedef struct { - uint32_t major; - uint32_t minor; - uint32_t patch; - const char* release; -} napi_node_version; -```` - -```cpp -static const napi_node_version* Napi::VersionManagement::GetNodeVersion(Env env); -``` - -- `[in] env`: The environment in which the API is invoked under. - -Returns the structure a pointer to the structure `napi_node_version` populated by -the version information of Node.js runtime. diff --git a/node_modules/node-addon-api/doc/working_with_javascript_values.md b/node_modules/node-addon-api/doc/working_with_javascript_values.md deleted file mode 100644 index 00dad25..0000000 --- a/node_modules/node-addon-api/doc/working_with_javascript_values.md +++ /dev/null @@ -1,14 +0,0 @@ -# Working with JavaScript Values - -`node-addon-api` provides a set of classes that allow to create and manage -JavaScript object: - -- [Function](function.md) - - [FunctionReference](function_reference.md) -- [ObjectWrap](object_wrap.md) - - [ClassPropertyDescriptor](class_property_descriptor.md) -- [Buffer](buffer.md) -- [ArrayBuffer](array_buffer.md) -- [TypedArray](typed_array.md) - - [TypedArrayOf](typed_array_of.md) -- [DataView](dataview.md) diff --git a/node_modules/node-addon-api/external-napi/node_api.h b/node_modules/node-addon-api/external-napi/node_api.h deleted file mode 100644 index 52c45f6..0000000 --- a/node_modules/node-addon-api/external-napi/node_api.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef EXTERNAL_NODE_API_H_ -#define EXTERNAL_NODE_API_H_ - -#define EXTERNAL_NAPI -#include "../src/node_api.h" - -#endif diff --git a/node_modules/node-addon-api/index.js b/node_modules/node-addon-api/index.js deleted file mode 100644 index 74e90e8..0000000 --- a/node_modules/node-addon-api/index.js +++ /dev/null @@ -1,45 +0,0 @@ -var path = require('path'); - -var versionArray = process.version - .substr(1) - .replace(/-.*$/, '') - .split('.') - .map(function(item) { - return +item; - }); - -// TODO: Check if the main node semantic version is within multiple ranges, -// or detect presence of built-in N-API by some other mechanism TBD. - -// We know which version of Node.js first shipped the incarnation of the API -// available in *this* package. So, if we find that the Node.js version is below -// that, we indicate that the API is missing from Node.js. -var isNodeApiBuiltin = ( - versionArray[0] > 8 || - (versionArray[0] == 8 && versionArray[1] >= 6) || - (versionArray[0] == 6 && versionArray[1] >= 15) || - (versionArray[0] == 6 && versionArray[1] >= 14 && versionArray[2] >= 2)); - -// The flag is not needed when the Node version is not 8, nor if the API is -// built-in, because we removed the flag at the same time as creating the final -// incarnation of the built-in API. -var needsFlag = (!isNodeApiBuiltin && versionArray[0] == 8); - -var include = [__dirname]; -var gyp = path.join(__dirname, 'src', 'node_api.gyp'); - -if (isNodeApiBuiltin) { - gyp += ':nothing'; -} else { - gyp += ':node-api'; - include.unshift(path.join(__dirname, 'external-napi')); -} - -module.exports = { - include: include.map(function(item) { - return '"' + item + '"'; - }).join(' '), - gyp: gyp, - isNodeApiBuiltin: isNodeApiBuiltin, - needsFlag: needsFlag -}; diff --git a/node_modules/node-addon-api/napi-inl.deprecated.h b/node_modules/node-addon-api/napi-inl.deprecated.h deleted file mode 100644 index f19aca7..0000000 --- a/node_modules/node-addon-api/napi-inl.deprecated.h +++ /dev/null @@ -1,192 +0,0 @@ -#ifndef SRC_NAPI_INL_DEPRECATED_H_ -#define SRC_NAPI_INL_DEPRECATED_H_ - -//////////////////////////////////////////////////////////////////////////////// -// PropertyDescriptor class -//////////////////////////////////////////////////////////////////////////////// - -template <typename Getter> -inline PropertyDescriptor -PropertyDescriptor::Accessor(const char* utf8name, - Getter getter, - napi_property_attributes attributes, - void* /*data*/) { - typedef details::CallbackData<Getter, Napi::Value> CbData; - // 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 <typename Getter> -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 <typename Getter> -inline PropertyDescriptor PropertyDescriptor::Accessor(napi_value name, - Getter getter, - napi_property_attributes attributes, - void* /*data*/) { - typedef details::CallbackData<Getter, Napi::Value> CbData; - // 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 <typename Getter> -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 <typename Getter, typename Setter> -inline PropertyDescriptor PropertyDescriptor::Accessor(const char* utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* /*data*/) { - typedef details::AccessorCallbackData<Getter, Setter> CbData; - // 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 <typename Getter, typename Setter> -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 <typename Getter, typename Setter> -inline PropertyDescriptor PropertyDescriptor::Accessor(napi_value name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* /*data*/) { - typedef details::AccessorCallbackData<Getter, Setter> CbData; - // 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 <typename Getter, typename Setter> -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 <typename Callable> -inline PropertyDescriptor PropertyDescriptor::Function(const char* utf8name, - Callable cb, - napi_property_attributes attributes, - void* /*data*/) { - typedef decltype(cb(CallbackInfo(nullptr, nullptr))) ReturnType; - typedef details::CallbackData<Callable, ReturnType> CbData; - // 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 <typename Callable> -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 <typename Callable> -inline PropertyDescriptor PropertyDescriptor::Function(napi_value name, - Callable cb, - napi_property_attributes attributes, - void* /*data*/) { - typedef decltype(cb(CallbackInfo(nullptr, nullptr))) ReturnType; - typedef details::CallbackData<Callable, ReturnType> CbData; - // 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 <typename Callable> -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/node_modules/node-addon-api/napi-inl.h b/node_modules/node-addon-api/napi-inl.h deleted file mode 100644 index f72e1da..0000000 --- a/node_modules/node-addon-api/napi-inl.h +++ /dev/null @@ -1,4367 +0,0 @@ -#ifndef SRC_NAPI_INL_H_ -#define SRC_NAPI_INL_H_ - -//////////////////////////////////////////////////////////////////////////////// -// N-API C++ Wrapper Classes -// -// Inline header-only implementations for "N-API" ABI-stable C APIs for Node.js. -//////////////////////////////////////////////////////////////////////////////// - -// Note: Do not include this file directly! Include "napi.h" instead. - -#include <algorithm> -#include <cstring> -#include <mutex> -#include <type_traits> - -namespace Napi { - -// Helpers to handle functions exposed from C++. -namespace details { - -// 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> -static inline napi_status AttachData(napi_env env, - napi_value obj, - FreeType* data, - napi_finalize finalizer = nullptr, - void* hint = nullptr) { - napi_status status; - if (finalizer == nullptr) { - finalizer = [](napi_env /*env*/, void* data, void* /*hint*/) { - delete static_cast<FreeType*>(data); - }; - } -#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 <typename Callable> -inline napi_value WrapCallback(Callable callback) { -#ifdef NAPI_CPP_EXCEPTIONS - try { - return callback(); - } catch (const Error& e) { - e.ThrowAsJavaScriptException(); - return nullptr; - } -#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. - return callback(); -#endif // NAPI_CPP_EXCEPTIONS -} - -template <typename Callable, typename Return> -struct CallbackData { - static inline - napi_value Wrapper(napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - CallbackData* callbackData = - static_cast<CallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - return callbackData->callback(callbackInfo); - }); - } - - Callable callback; - void* data; -}; - -template <typename Callable> -struct CallbackData<Callable, void> { - static inline - napi_value Wrapper(napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - CallbackData* callbackData = - static_cast<CallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - callbackData->callback(callbackInfo); - return nullptr; - }); - } - - Callable callback; - void* data; -}; - -template <typename T, typename Finalizer, typename Hint = void> -struct FinalizeData { - static inline - void Wrapper(napi_env env, void* data, void* finalizeHint) { - FinalizeData* finalizeData = static_cast<FinalizeData*>(finalizeHint); - finalizeData->callback(Env(env), static_cast<T*>(data)); - delete finalizeData; - } - - static inline - void WrapperWithHint(napi_env env, void* data, void* finalizeHint) { - FinalizeData* finalizeData = static_cast<FinalizeData*>(finalizeHint); - finalizeData->callback(Env(env), static_cast<T*>(data), finalizeData->hint); - delete finalizeData; - } - - Finalizer callback; - Hint* hint; -}; - -#if (NAPI_VERSION > 3) -template <typename ContextType=void, - typename Finalizer=std::function<void(Env, void*, ContextType*)>, - typename FinalizerDataType=void> -struct ThreadSafeFinalize { - static inline - void Wrapper(napi_env env, void* rawFinalizeData, void* /* rawContext */) { - if (rawFinalizeData == nullptr) - return; - - ThreadSafeFinalize* finalizeData = - static_cast<ThreadSafeFinalize*>(rawFinalizeData); - finalizeData->callback(Env(env)); - if (finalizeData->tsfn) { - *finalizeData->tsfn = nullptr; - } - delete finalizeData; - } - - static inline - void FinalizeWrapperWithData(napi_env env, - void* rawFinalizeData, - void* /* rawContext */) { - if (rawFinalizeData == nullptr) - return; - - ThreadSafeFinalize* finalizeData = - static_cast<ThreadSafeFinalize*>(rawFinalizeData); - finalizeData->callback(Env(env), finalizeData->data); - if (finalizeData->tsfn) { - *finalizeData->tsfn = nullptr; - } - delete finalizeData; - } - - static inline - void FinalizeWrapperWithContext(napi_env env, - void* rawFinalizeData, - void* rawContext) { - if (rawFinalizeData == nullptr) - return; - - ThreadSafeFinalize* finalizeData = - static_cast<ThreadSafeFinalize*>(rawFinalizeData); - finalizeData->callback(Env(env), static_cast<ContextType*>(rawContext)); - if (finalizeData->tsfn) { - *finalizeData->tsfn = nullptr; - } - delete finalizeData; - } - - static inline - void FinalizeFinalizeWrapperWithDataAndContext(napi_env env, - void* rawFinalizeData, - void* rawContext) { - if (rawFinalizeData == nullptr) - return; - - ThreadSafeFinalize* finalizeData = - static_cast<ThreadSafeFinalize*>(rawFinalizeData); - finalizeData->callback(Env(env), finalizeData->data, - static_cast<ContextType*>(rawContext)); - if (finalizeData->tsfn) { - *finalizeData->tsfn = nullptr; - } - delete finalizeData; - } - - FinalizerDataType* data; - Finalizer callback; - napi_threadsafe_function* tsfn; -}; -#endif - -template <typename Getter, typename Setter> -struct AccessorCallbackData { - static inline - napi_value GetterWrapper(napi_env env, napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - AccessorCallbackData* callbackData = - static_cast<AccessorCallbackData*>(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([&] { - CallbackInfo callbackInfo(env, info); - AccessorCallbackData* callbackData = - static_cast<AccessorCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - callbackData->setterCallback(callbackInfo); - return nullptr; - }); - } - - Getter getterCallback; - Setter setterCallback; - void* data; -}; - -} // namespace details - -#ifndef NODE_ADDON_API_DISABLE_DEPRECATED -# include "napi-inl.deprecated.h" -#endif // !NODE_ADDON_API_DISABLE_DEPRECATED - -//////////////////////////////////////////////////////////////////////////////// -// Module registration -//////////////////////////////////////////////////////////////////////////////// - -#define NODE_API_MODULE(modname, regfunc) \ - napi_value __napi_ ## regfunc(napi_env env, \ - napi_value exports) { \ - return Napi::RegisterModule(env, exports, regfunc); \ - } \ - NAPI_MODULE(modname, __napi_ ## regfunc) - -// 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([&] { - return napi_value(registerCallback(Napi::Env(env), - Napi::Object(env, exports))); - }); -} - -//////////////////////////////////////////////////////////////////////////////// -// Env class -//////////////////////////////////////////////////////////////////////////////// - -inline Env::Env(napi_env env) : _env(env) { -} - -inline Env::operator napi_env() const { - return _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(_env, &result); - if (status != napi_ok) result = false; // Checking for a pending exception shouldn't throw. - return result; -} - -inline Error Env::GetAndClearPendingException() { - napi_value value; - napi_status status = napi_get_and_clear_last_exception(_env, &value); - if (status != napi_ok) { - // Don't throw another exception when failing to get the exception! - return Error(); - } - return Error(_env, value); -} - -//////////////////////////////////////////////////////////////////////////////// -// 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; -} - -// Currently experimental guard with the definition of NAPI_EXPERIMENTAL. -// Once it is no longer experimental guard with the NAPI_VERSION in which it is -// released instead. -#ifdef NAPI_EXPERIMENTAL -inline bool Value::IsBigInt() const { - return Type() == napi_bigint; -} -#endif // NAPI_EXPERIMENTAL - -#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; -} - -template <typename T> -inline T Value::As() const { - return T(_env, _value); -} - -inline Boolean Value::ToBoolean() const { - napi_value result; - napi_status status = napi_coerce_to_bool(_env, _value, &result); - NAPI_THROW_IF_FAILED(_env, status, Boolean()); - return Boolean(_env, result); -} - -inline Number Value::ToNumber() const { - napi_value result; - napi_status status = napi_coerce_to_number(_env, _value, &result); - NAPI_THROW_IF_FAILED(_env, status, Number()); - return Number(_env, result); -} - -inline String Value::ToString() const { - napi_value result; - napi_status status = napi_coerce_to_string(_env, _value, &result); - NAPI_THROW_IF_FAILED(_env, status, String()); - return String(_env, result); -} - -inline Object Value::ToObject() const { - napi_value result; - napi_status status = napi_coerce_to_object(_env, _value, &result); - NAPI_THROW_IF_FAILED(_env, status, Object()); - return Object(_env, result); -} - -//////////////////////////////////////////////////////////////////////////////// -// 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 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 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<float>(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; -} - -// Currently experimental guard with the definition of NAPI_EXPERIMENTAL. -// Once it is no longer experimental guard with the NAPI_VERSION in which it is -// released instead. -#ifdef NAPI_EXPERIMENTAL -//////////////////////////////////////////////////////////////////////////////// -// 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 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_EXPERIMENTAL - -#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() : 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 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, const char* val) { - 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; - 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 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<napi_value>(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, 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 Symbol Symbol::WellKnown(napi_env env, const std::string& name) { - return Napi::Env(env).Global().Get("Symbol").As<Object>().Get(name).As<Symbol>(); -} - -inline Symbol::Symbol() : Name() { -} - -inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) { -} - -//////////////////////////////////////////////////////////////////////////////// -// Automagic value creation -//////////////////////////////////////////////////////////////////////////////// - -namespace details { -template <typename T> -struct vf_number { - static Number From(napi_env env, T value) { - return Number::New(env, static_cast<double>(value)); - } -}; - -template<> -struct vf_number<bool> { - 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 <typename T> -struct vf_fallback { - static Value From(napi_env env, const T& value) { - return Value(env, value); - } -}; - -template <typename...> struct disjunction : std::false_type {}; -template <typename B> struct disjunction<B> : B {}; -template <typename B, typename... Bs> -struct disjunction<B, Bs...> - : std::conditional<bool(B::value), B, disjunction<Bs...>>::type {}; - -template <typename T> -struct can_make_string - : disjunction<typename std::is_convertible<T, const char *>::type, - typename std::is_convertible<T, const char16_t *>::type, - typename std::is_convertible<T, std::string>::type, - typename std::is_convertible<T, std::u16string>::type> {}; -} - -template <typename T> -Value Value::From(napi_env env, const T& value) { - using Helper = typename std::conditional< - std::is_integral<T>::value || std::is_floating_point<T>::value, - details::vf_number<T>, - typename std::conditional< - details::can_make_string<T>::value, - String, - details::vf_fallback<T> - >::type - >::type; - return Helper::From(env, value); -} - -template <typename T> -String String::From(napi_env env, const T& value) { - struct Dummy {}; - using Helper = typename std::conditional< - std::is_convertible<T, const char*>::value, - details::vf_utf8_charp, - typename std::conditional< - std::is_convertible<T, const char16_t*>::value, - details::vf_utf16_charp, - typename std::conditional< - std::is_convertible<T, std::string>::value, - details::vf_utf8_string, - typename std::conditional< - std::is_convertible<T, std::u16string>::value, - details::vf_utf16_string, - Dummy - >::type - >::type - >::type - >::type; - return Helper::From(env, value); -} - -//////////////////////////////////////////////////////////////////////////////// -// Object class -//////////////////////////////////////////////////////////////////////////////// - -template <typename Key> -inline Object::PropertyLValue<Key>::operator Value() const { - return Object(_env, _object).Get(_key); -} - -template <typename Key> template <typename ValueType> -inline Object::PropertyLValue<Key>& Object::PropertyLValue<Key>::operator =(ValueType value) { - Object(_env, _object).Set(_key, value); - return *this; -} - -template <typename Key> -inline Object::PropertyLValue<Key>::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 Object::Object() : Value() { -} - -inline Object::Object(napi_env env, napi_value value) : Value(env, value) { -} - -inline Object::PropertyLValue<std::string> Object::operator [](const char* utf8name) { - return PropertyLValue<std::string>(*this, utf8name); -} - -inline Object::PropertyLValue<std::string> Object::operator [](const std::string& utf8name) { - return PropertyLValue<std::string>(*this, utf8name); -} - -inline Object::PropertyLValue<uint32_t> Object::operator [](uint32_t index) { - return PropertyLValue<uint32_t>(*this, index); -} - -inline Value Object::operator [](const char* utf8name) const { - return Get(utf8name); -} - -inline Value Object::operator [](const std::string& utf8name) const { - return Get(utf8name); -} - -inline Value Object::operator [](uint32_t index) const { - return Get(index); -} - -inline bool Object::Has(napi_value key) const { - bool result; - napi_status status = napi_has_property(_env, _value, key, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline bool Object::Has(Value key) const { - bool result; - napi_status status = napi_has_property(_env, _value, key, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline bool Object::Has(const char* utf8name) const { - bool result; - napi_status status = napi_has_named_property(_env, _value, utf8name, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline bool Object::Has(const std::string& utf8name) const { - return Has(utf8name.c_str()); -} - -inline bool Object::HasOwnProperty(napi_value key) const { - bool result; - napi_status status = napi_has_own_property(_env, _value, key, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline bool Object::HasOwnProperty(Value key) const { - bool result; - napi_status status = napi_has_own_property(_env, _value, key, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline bool Object::HasOwnProperty(const char* utf8name) const { - napi_value key; - napi_status status = napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key); - NAPI_THROW_IF_FAILED(_env, status, false); - return HasOwnProperty(key); -} - -inline bool Object::HasOwnProperty(const std::string& utf8name) const { - return HasOwnProperty(utf8name.c_str()); -} - -inline Value Object::Get(napi_value key) const { - napi_value result; - napi_status status = napi_get_property(_env, _value, key, &result); - NAPI_THROW_IF_FAILED(_env, status, Value()); - return Value(_env, result); -} - -inline Value Object::Get(Value key) const { - napi_value result; - napi_status status = napi_get_property(_env, _value, key, &result); - NAPI_THROW_IF_FAILED(_env, status, Value()); - return Value(_env, result); -} - -inline Value Object::Get(const char* utf8name) const { - napi_value result; - napi_status status = napi_get_named_property(_env, _value, utf8name, &result); - NAPI_THROW_IF_FAILED(_env, status, Value()); - return Value(_env, result); -} - -inline Value Object::Get(const std::string& utf8name) const { - return Get(utf8name.c_str()); -} - -template <typename ValueType> -inline void Object::Set(napi_value key, const ValueType& value) { - napi_status status = - napi_set_property(_env, _value, key, Value::From(_env, value)); - NAPI_THROW_IF_FAILED_VOID(_env, status); -} - -template <typename ValueType> -inline void Object::Set(Value key, const ValueType& value) { - napi_status status = - napi_set_property(_env, _value, key, Value::From(_env, value)); - NAPI_THROW_IF_FAILED_VOID(_env, status); -} - -template <typename ValueType> -inline void Object::Set(const char* utf8name, const ValueType& value) { - napi_status status = - napi_set_named_property(_env, _value, utf8name, Value::From(_env, value)); - NAPI_THROW_IF_FAILED_VOID(_env, status); -} - -template <typename ValueType> -inline void Object::Set(const std::string& utf8name, const ValueType& value) { - Set(utf8name.c_str(), value); -} - -inline bool Object::Delete(napi_value key) { - bool result; - napi_status status = napi_delete_property(_env, _value, key, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline bool Object::Delete(Value key) { - bool result; - napi_status status = napi_delete_property(_env, _value, key, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline bool Object::Delete(const char* utf8name) { - return Delete(String::New(_env, utf8name)); -} - -inline bool Object::Delete(const std::string& utf8name) { - return Delete(String::New(_env, utf8name)); -} - -inline bool Object::Has(uint32_t index) const { - bool result; - napi_status status = napi_has_element(_env, _value, index, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline Value Object::Get(uint32_t index) const { - napi_value value; - napi_status status = napi_get_element(_env, _value, index, &value); - NAPI_THROW_IF_FAILED(_env, status, Value()); - return Value(_env, value); -} - -template <typename ValueType> -inline void Object::Set(uint32_t index, const ValueType& value) { - napi_status status = - napi_set_element(_env, _value, index, Value::From(_env, value)); - NAPI_THROW_IF_FAILED_VOID(_env, status); -} - -inline bool Object::Delete(uint32_t index) { - bool result; - napi_status status = napi_delete_element(_env, _value, index, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -inline Array Object::GetPropertyNames() const { - napi_value result; - napi_status status = napi_get_property_names(_env, _value, &result); - NAPI_THROW_IF_FAILED(_env, status, Array()); - return Array(_env, result); -} - -inline void Object::DefineProperty(const PropertyDescriptor& property) { - napi_status status = napi_define_properties(_env, _value, 1, - reinterpret_cast<const napi_property_descriptor*>(&property)); - NAPI_THROW_IF_FAILED_VOID(_env, status); -} - -inline void Object::DefineProperties(const std::initializer_list<PropertyDescriptor>& properties) { - napi_status status = napi_define_properties(_env, _value, properties.size(), - reinterpret_cast<const napi_property_descriptor*>(properties.begin())); - NAPI_THROW_IF_FAILED_VOID(_env, status); -} - -inline void Object::DefineProperties(const std::vector<PropertyDescriptor>& properties) { - napi_status status = napi_define_properties(_env, _value, properties.size(), - reinterpret_cast<const napi_property_descriptor*>(properties.data())); - NAPI_THROW_IF_FAILED_VOID(_env, status); -} - -inline bool Object::InstanceOf(const Function& constructor) const { - bool result; - napi_status status = napi_instanceof(_env, _value, constructor, &result); - NAPI_THROW_IF_FAILED(_env, status, false); - return result; -} - -template <typename Finalizer, typename T> -inline void Object::AddFinalizer(Finalizer finalizeCallback, T* data) { - details::FinalizeData<T, Finalizer>* finalizeData = - new details::FinalizeData<T, Finalizer>({ finalizeCallback, nullptr }); - napi_status status = - details::AttachData(_env, - *this, - data, - details::FinalizeData<T, Finalizer>::Wrapper, - finalizeData); - if (status != napi_ok) { - delete finalizeData; - NAPI_THROW_IF_FAILED_VOID(_env, status); - } -} - -template <typename Finalizer, typename T, typename Hint> -inline void Object::AddFinalizer(Finalizer finalizeCallback, - T* data, - Hint* finalizeHint) { - details::FinalizeData<T, Finalizer, Hint>* finalizeData = - new details::FinalizeData<T, Finalizer, Hint>({ finalizeCallback, finalizeHint }); - napi_status status = - details::AttachData(_env, - *this, - data, - details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint, - finalizeData); - if (status != napi_ok) { - delete finalizeData; - NAPI_THROW_IF_FAILED_VOID(_env, status); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// External class -//////////////////////////////////////////////////////////////////////////////// - -template <typename T> -inline External<T> External<T>::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 <typename T> -template <typename Finalizer> -inline External<T> External<T>::New(napi_env env, - T* data, - Finalizer finalizeCallback) { - napi_value value; - details::FinalizeData<T, Finalizer>* finalizeData = - new details::FinalizeData<T, Finalizer>({ finalizeCallback, nullptr }); - napi_status status = napi_create_external( - env, - data, - details::FinalizeData<T, Finalizer>::Wrapper, - finalizeData, - &value); - if (status != napi_ok) { - delete finalizeData; - NAPI_THROW_IF_FAILED(env, status, External()); - } - return External(env, value); -} - -template <typename T> -template <typename Finalizer, typename Hint> -inline External<T> External<T>::New(napi_env env, - T* data, - Finalizer finalizeCallback, - Hint* finalizeHint) { - napi_value value; - details::FinalizeData<T, Finalizer, Hint>* finalizeData = - new details::FinalizeData<T, Finalizer, Hint>({ finalizeCallback, finalizeHint }); - napi_status status = napi_create_external( - env, - data, - details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint, - finalizeData, - &value); - if (status != napi_ok) { - delete finalizeData; - NAPI_THROW_IF_FAILED(env, status, External()); - } - return External(env, value); -} - -template <typename T> -inline External<T>::External() : Value() { -} - -template <typename T> -inline External<T>::External(napi_env env, napi_value value) : Value(env, value) { -} - -template <typename T> -inline T* External<T>::Data() const { - void* data; - napi_status status = napi_get_value_external(_env, _value, &data); - NAPI_THROW_IF_FAILED(_env, status, nullptr); - return reinterpret_cast<T*>(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 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; -} - -//////////////////////////////////////////////////////////////////////////////// -// 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, data, byteLength); -} - -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, externalData, byteLength); -} - -template <typename Finalizer> -inline ArrayBuffer ArrayBuffer::New(napi_env env, - void* externalData, - size_t byteLength, - Finalizer finalizeCallback) { - napi_value value; - details::FinalizeData<void, Finalizer>* finalizeData = - new details::FinalizeData<void, Finalizer>({ finalizeCallback, nullptr }); - napi_status status = napi_create_external_arraybuffer( - env, - externalData, - byteLength, - details::FinalizeData<void, Finalizer>::Wrapper, - finalizeData, - &value); - if (status != napi_ok) { - delete finalizeData; - NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); - } - - return ArrayBuffer(env, value, externalData, byteLength); -} - -template <typename Finalizer, typename Hint> -inline ArrayBuffer ArrayBuffer::New(napi_env env, - void* externalData, - size_t byteLength, - Finalizer finalizeCallback, - Hint* finalizeHint) { - napi_value value; - details::FinalizeData<void, Finalizer, Hint>* finalizeData = - new details::FinalizeData<void, Finalizer, Hint>({ finalizeCallback, finalizeHint }); - napi_status status = napi_create_external_arraybuffer( - env, - externalData, - byteLength, - details::FinalizeData<void, Finalizer, Hint>::WrapperWithHint, - finalizeData, - &value); - if (status != napi_ok) { - delete finalizeData; - NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); - } - - return ArrayBuffer(env, value, externalData, byteLength); -} - -inline ArrayBuffer::ArrayBuffer() : Object(), _data(nullptr), _length(0) { -} - -inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value) - : Object(env, value), _data(nullptr), _length(0) { -} - -inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value, void* data, size_t length) - : Object(env, value), _data(data), _length(length) { -} - -inline void* ArrayBuffer::Data() { - EnsureInfo(); - return _data; -} - -inline size_t ArrayBuffer::ByteLength() { - EnsureInfo(); - return _length; -} - -inline void ArrayBuffer::EnsureInfo() const { - // The ArrayBuffer instance may have been constructed from a napi_value whose - // length/data are not yet known. Fetch and cache these values just once, - // since they can never change during the lifetime of the ArrayBuffer. - if (_data == nullptr) { - napi_status status = napi_get_arraybuffer_info(_env, _value, &_data, &_length); - NAPI_THROW_IF_FAILED_VOID(_env, status); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// 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); -} - -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 { - 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::ArrayBuffer()); - return Napi::ArrayBuffer(_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<float>(byteOffset); -} - -inline double DataView::GetFloat64(size_t byteOffset) const { - return ReadData<double>(byteOffset); -} - -inline int8_t DataView::GetInt8(size_t byteOffset) const { - return ReadData<int8_t>(byteOffset); -} - -inline int16_t DataView::GetInt16(size_t byteOffset) const { - return ReadData<int16_t>(byteOffset); -} - -inline int32_t DataView::GetInt32(size_t byteOffset) const { - return ReadData<int32_t>(byteOffset); -} - -inline uint8_t DataView::GetUint8(size_t byteOffset) const { - return ReadData<uint8_t>(byteOffset); -} - -inline uint16_t DataView::GetUint16(size_t byteOffset) const { - return ReadData<uint16_t>(byteOffset); -} - -inline uint32_t DataView::GetUint32(size_t byteOffset) const { - return ReadData<uint32_t>(byteOffset); -} - -inline void DataView::SetFloat32(size_t byteOffset, float value) const { - WriteData<float>(byteOffset, value); -} - -inline void DataView::SetFloat64(size_t byteOffset, double value) const { - WriteData<double>(byteOffset, value); -} - -inline void DataView::SetInt8(size_t byteOffset, int8_t value) const { - WriteData<int8_t>(byteOffset, value); -} - -inline void DataView::SetInt16(size_t byteOffset, int16_t value) const { - WriteData<int16_t>(byteOffset, value); -} - -inline void DataView::SetInt32(size_t byteOffset, int32_t value) const { - WriteData<int32_t>(byteOffset, value); -} - -inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const { - WriteData<uint8_t>(byteOffset, value); -} - -inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const { - WriteData<uint16_t>(byteOffset, value); -} - -inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const { - WriteData<uint32_t>(byteOffset, value); -} - -template <typename T> -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<T*>(static_cast<uint8_t*>(_data) + byteOffset); -} - -template <typename T> -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<T*>(static_cast<uint8_t*>(_data) + byteOffset) = value; -} - -//////////////////////////////////////////////////////////////////////////////// -// TypedArray class -//////////////////////////////////////////////////////////////////////////////// - -inline TypedArray::TypedArray() - : Object(), _type(TypedArray::unknown_array_type), _length(0) { -} - -inline TypedArray::TypedArray(napi_env env, napi_value value) - : Object(env, value), _type(TypedArray::unknown_array_type), _length(0) { -} - -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 { - if (_type == TypedArray::unknown_array_type) { - napi_status status = napi_get_typedarray_info(_env, _value, - &const_cast<TypedArray*>(this)->_type, &const_cast<TypedArray*>(this)->_length, - nullptr, nullptr, nullptr); - NAPI_THROW_IF_FAILED(_env, status, napi_int8_array); - } - - return _type; -} - -inline uint8_t TypedArray::ElementSize() const { - switch (TypedArrayType()) { - 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: - return 8; - default: - return 0; - } -} - -inline size_t TypedArray::ElementLength() const { - if (_type == TypedArray::unknown_array_type) { - napi_status status = napi_get_typedarray_info(_env, _value, - &const_cast<TypedArray*>(this)->_type, &const_cast<TypedArray*>(this)->_length, - nullptr, nullptr, nullptr); - NAPI_THROW_IF_FAILED(_env, status, 0); - } - - 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); -} - -//////////////////////////////////////////////////////////////////////////////// -// TypedArrayOf<T> class -//////////////////////////////////////////////////////////////////////////////// - -template <typename T> -inline TypedArrayOf<T> TypedArrayOf<T>::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 <typename T> -inline TypedArrayOf<T> TypedArrayOf<T>::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<T>()); - - return TypedArrayOf<T>( - env, value, type, elementLength, - reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(arrayBuffer.Data()) + bufferOffset)); -} - -template <typename T> -inline TypedArrayOf<T>::TypedArrayOf() : TypedArray(), _data(nullptr) { -} - -template <typename T> -inline TypedArrayOf<T>::TypedArrayOf(napi_env env, napi_value value) - : TypedArray(env, value), _data(nullptr) { - napi_status status = napi_get_typedarray_info( - _env, _value, &_type, &_length, reinterpret_cast<void**>(&_data), nullptr, nullptr); - NAPI_THROW_IF_FAILED_VOID(_env, status); -} - -template <typename T> -inline TypedArrayOf<T>::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<T>() || - (type == napi_uint8_clamped_array && std::is_same<T, uint8_t>::value))) { - NAPI_THROW_VOID(TypeError::New(env, "Array type must match the template parameter. " - "(Uint8 arrays may optionally have the \"clamped\" array type.)")); - } -} - -template <typename T> -inline T& TypedArrayOf<T>::operator [](size_t index) { - return _data[index]; -} - -template <typename T> -inline const T& TypedArrayOf<T>::operator [](size_t index) const { - return _data[index]; -} - -template <typename T> -inline T* TypedArrayOf<T>::Data() { - return _data; -} - -template <typename T> -inline const T* TypedArrayOf<T>::Data() const { - return _data; -} - -//////////////////////////////////////////////////////////////////////////////// -// Function class -//////////////////////////////////////////////////////////////////////////////// - -template <typename CbData> -static 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 <typename Callable> -inline Function Function::New(napi_env env, - Callable cb, - const char* utf8name, - void* data) { - typedef decltype(cb(CallbackInfo(nullptr, nullptr))) ReturnType; - typedef details::CallbackData<Callable, ReturnType> CbData; - auto callbackData = new CbData({ 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 <typename Callable> -inline Function Function::New(napi_env env, - Callable cb, - const std::string& utf8name, - void* data) { - return New(env, cb, utf8name.c_str(), data); -} - -inline Function::Function() : Object() { -} - -inline Function::Function(napi_env env, napi_value value) : Object(env, value) { -} - -inline Value Function::operator ()(const std::initializer_list<napi_value>& args) const { - return Call(Env().Undefined(), args); -} - -inline Value Function::Call(const std::initializer_list<napi_value>& args) const { - return Call(Env().Undefined(), args); -} - -inline Value Function::Call(const std::vector<napi_value>& args) const { - return Call(Env().Undefined(), args); -} - -inline Value Function::Call(size_t argc, const napi_value* args) const { - return Call(Env().Undefined(), argc, args); -} - -inline Value Function::Call(napi_value recv, const std::initializer_list<napi_value>& args) const { - return Call(recv, args.size(), args.begin()); -} - -inline Value Function::Call(napi_value recv, const std::vector<napi_value>& args) const { - return Call(recv, args.size(), args.data()); -} - -inline Value 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_THROW_IF_FAILED(_env, status, Value()); - return Value(_env, result); -} - -inline Value Function::MakeCallback( - napi_value recv, - const std::initializer_list<napi_value>& args, - napi_async_context context) const { - return MakeCallback(recv, args.size(), args.begin(), context); -} - -inline Value Function::MakeCallback( - napi_value recv, - const std::vector<napi_value>& args, - napi_async_context context) const { - return MakeCallback(recv, args.size(), args.data(), context); -} - -inline Value 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_THROW_IF_FAILED(_env, status, Value()); - return Value(_env, result); -} - -inline Object Function::New(const std::initializer_list<napi_value>& args) const { - return New(args.size(), args.begin()); -} - -inline Object Function::New(const std::vector<napi_value>& args) const { - return New(args.size(), args.data()); -} - -inline Object 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_THROW_IF_FAILED(_env, status, Object()); - return Object(_env, result); -} - -//////////////////////////////////////////////////////////////////////////////// -// 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 Promise::Promise(napi_env env, napi_value value) : Object(env, value) { -} - -//////////////////////////////////////////////////////////////////////////////// -// Buffer<T> class -//////////////////////////////////////////////////////////////////////////////// - -template <typename T> -inline Buffer<T> Buffer<T>::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<T>()); - return Buffer(env, value, length, static_cast<T*>(data)); -} - -template <typename T> -inline Buffer<T> Buffer<T>::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<T>()); - return Buffer(env, value, length, data); -} - -template <typename T> -template <typename Finalizer> -inline Buffer<T> Buffer<T>::New(napi_env env, - T* data, - size_t length, - Finalizer finalizeCallback) { - napi_value value; - details::FinalizeData<T, Finalizer>* finalizeData = - new details::FinalizeData<T, Finalizer>({ finalizeCallback, nullptr }); - napi_status status = napi_create_external_buffer( - env, - length * sizeof (T), - data, - details::FinalizeData<T, Finalizer>::Wrapper, - finalizeData, - &value); - if (status != napi_ok) { - delete finalizeData; - NAPI_THROW_IF_FAILED(env, status, Buffer()); - } - return Buffer(env, value, length, data); -} - -template <typename T> -template <typename Finalizer, typename Hint> -inline Buffer<T> Buffer<T>::New(napi_env env, - T* data, - size_t length, - Finalizer finalizeCallback, - Hint* finalizeHint) { - napi_value value; - details::FinalizeData<T, Finalizer, Hint>* finalizeData = - new details::FinalizeData<T, Finalizer, Hint>({ finalizeCallback, finalizeHint }); - napi_status status = napi_create_external_buffer( - env, - length * sizeof (T), - data, - details::FinalizeData<T, Finalizer, Hint>::WrapperWithHint, - finalizeData, - &value); - if (status != napi_ok) { - delete finalizeData; - NAPI_THROW_IF_FAILED(env, status, Buffer()); - } - return Buffer(env, value, length, data); -} - -template <typename T> -inline Buffer<T> Buffer<T>::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<T>()); - return Buffer<T>(env, value); -} - -template <typename T> -inline Buffer<T>::Buffer() : Uint8Array(), _length(0), _data(nullptr) { -} - -template <typename T> -inline Buffer<T>::Buffer(napi_env env, napi_value value) - : Uint8Array(env, value), _length(0), _data(nullptr) { -} - -template <typename T> -inline Buffer<T>::Buffer(napi_env env, napi_value value, size_t length, T* data) - : Uint8Array(env, value), _length(length), _data(data) { -} - -template <typename T> -inline size_t Buffer<T>::Length() const { - EnsureInfo(); - return _length; -} - -template <typename T> -inline T* Buffer<T>::Data() const { - EnsureInfo(); - return _data; -} - -template <typename T> -inline void Buffer<T>::EnsureInfo() const { - // The Buffer instance may have been constructed from a napi_value whose - // length/data are not yet known. Fetch and cache these values just once, - // since they can never change during the lifetime of the Buffer. - if (_data == nullptr) { - size_t byteLength; - void* voidData; - napi_status status = napi_get_buffer_info(_env, _value, &voidData, &byteLength); - NAPI_THROW_IF_FAILED_VOID(_env, status); - _length = byteLength / sizeof (T); - _data = static_cast<T*>(voidData); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// Error class -//////////////////////////////////////////////////////////////////////////////// - -inline Error Error::New(napi_env env) { - napi_status status; - napi_value error = nullptr; - - const napi_extended_error_info* info; - status = napi_get_last_error_info(env, &info); - NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info"); - - if (info->error_code == napi_pending_exception) { - 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 = info->error_message != nullptr ? - info->error_message : "Error in native callback"; - - bool isExceptionPending; - status = napi_is_exception_pending(env, &isExceptionPending); - NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending"); - - if (isExceptionPending) { - status = napi_get_and_clear_last_exception(env, &error); - NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_and_clear_last_exception"); - } - - 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 (info->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<Error>(env, message, std::strlen(message), napi_create_error); -} - -inline Error Error::New(napi_env env, const std::string& message) { - return Error::New<Error>(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) { - napi_status status = napi_create_reference(env, value, 1, &_ref); - - // Avoid infinite recursion in the failure case. - // Don't try to construct & throw another Error instance. - NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference"); - } -} - -inline Error::Error(Error&& other) : ObjectReference(std::move(other)) { -} - -inline Error& Error::operator =(Error&& other) { - static_cast<Reference<Object>*>(this)->operator=(std::move(other)); - return *this; -} - -inline Error::Error(const Error& other) : ObjectReference(other) { -} - -inline Error& Error::operator =(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 NAPI_CPP_EXCEPTIONS - try { - _message = Get("message").As<String>(); - } - 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 // NAPI_CPP_EXCEPTIONS - _message = Get("message").As<String>(); -#endif // NAPI_CPP_EXCEPTIONS - } - return _message; -} - -inline void Error::ThrowAsJavaScriptException() const { - HandleScope scope(_env); - if (!IsEmpty()) { - - // 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()); - -#ifdef NAPI_CPP_EXCEPTIONS - if (status != napi_ok) { - throw Error::New(_env); - } -#else // NAPI_CPP_EXCEPTIONS - NAPI_FATAL_IF_FAILED(status, "Error::ThrowAsJavaScriptException", "napi_throw"); -#endif // NAPI_CPP_EXCEPTIONS - } -} - -#ifdef NAPI_CPP_EXCEPTIONS - -inline const char* Error::what() const NAPI_NOEXCEPT { - return Message().c_str(); -} - -#endif // NAPI_CPP_EXCEPTIONS - -template <typename TError> -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<TypeError>(env, message, std::strlen(message), napi_create_type_error); -} - -inline TypeError TypeError::New(napi_env env, const std::string& message) { - return Error::New<TypeError>(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<RangeError>(env, message, std::strlen(message), napi_create_range_error); -} - -inline RangeError RangeError::New(napi_env env, const std::string& message) { - return Error::New<RangeError>(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) { -} - -//////////////////////////////////////////////////////////////////////////////// -// Reference<T> class -//////////////////////////////////////////////////////////////////////////////// - -template <typename T> -inline Reference<T> Reference<T>::New(const T& value, uint32_t initialRefcount) { - napi_env env = value.Env(); - napi_value val = value; - - if (val == nullptr) { - return Reference<T>(env, nullptr); - } - - napi_ref ref; - napi_status status = napi_create_reference(env, value, initialRefcount, &ref); - NAPI_THROW_IF_FAILED(env, status, Reference<T>()); - - return Reference<T>(env, ref); -} - - -template <typename T> -inline Reference<T>::Reference() : _env(nullptr), _ref(nullptr), _suppressDestruct(false) { -} - -template <typename T> -inline Reference<T>::Reference(napi_env env, napi_ref ref) - : _env(env), _ref(ref), _suppressDestruct(false) { -} - -template <typename T> -inline Reference<T>::~Reference() { - if (_ref != nullptr) { - if (!_suppressDestruct) { - napi_delete_reference(_env, _ref); - } - - _ref = nullptr; - } -} - -template <typename T> -inline Reference<T>::Reference(Reference<T>&& other) - : _env(other._env), _ref(other._ref), _suppressDestruct(other._suppressDestruct) { - other._env = nullptr; - other._ref = nullptr; - other._suppressDestruct = false; -} - -template <typename T> -inline Reference<T>& Reference<T>::operator =(Reference<T>&& other) { - Reset(); - _env = other._env; - _ref = other._ref; - _suppressDestruct = other._suppressDestruct; - other._env = nullptr; - other._ref = nullptr; - other._suppressDestruct = false; - return *this; -} - -template <typename T> -inline Reference<T>::Reference(const Reference<T>& 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<T>::Reference", "napi_create_reference"); - } -} - -template <typename T> -inline Reference<T>::operator napi_ref() const { - return _ref; -} - -template <typename T> -inline bool Reference<T>::operator ==(const Reference<T> &other) const { - HandleScope scope(_env); - return this->Value().StrictEquals(other.Value()); -} - -template <typename T> -inline bool Reference<T>::operator !=(const Reference<T> &other) const { - return !this->operator ==(other); -} - -template <typename T> -inline Napi::Env Reference<T>::Env() const { - return Napi::Env(_env); -} - -template <typename T> -inline bool Reference<T>::IsEmpty() const { - return _ref == nullptr; -} - -template <typename T> -inline T Reference<T>::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 <typename T> -inline uint32_t Reference<T>::Ref() { - uint32_t result; - napi_status status = napi_reference_ref(_env, _ref, &result); - NAPI_THROW_IF_FAILED(_env, status, 1); - return result; -} - -template <typename T> -inline uint32_t Reference<T>::Unref() { - uint32_t result; - napi_status status = napi_reference_unref(_env, _ref, &result); - NAPI_THROW_IF_FAILED(_env, status, 1); - return result; -} - -template <typename T> -inline void Reference<T>::Reset() { - if (_ref != nullptr) { - napi_status status = napi_delete_reference(_env, _ref); - NAPI_THROW_IF_FAILED_VOID(_env, status); - _ref = nullptr; - } -} - -template <typename T> -inline void Reference<T>::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 <typename T> -inline void Reference<T>::SuppressDestruct() { - _suppressDestruct = true; -} - -template <typename T> -inline Reference<T> Weak(T value) { - return Reference<T>::New(value, 0); -} - -inline ObjectReference Weak(Object value) { - return Reference<Object>::New(value, 0); -} - -inline FunctionReference Weak(Function value) { - return Reference<Function>::New(value, 0); -} - -template <typename T> -inline Reference<T> Persistent(T value) { - return Reference<T>::New(value, 1); -} - -inline ObjectReference Persistent(Object value) { - return Reference<Object>::New(value, 1); -} - -inline FunctionReference Persistent(Function value) { - return Reference<Function>::New(value, 1); -} - -//////////////////////////////////////////////////////////////////////////////// -// ObjectReference class -//////////////////////////////////////////////////////////////////////////////// - -inline ObjectReference::ObjectReference(): Reference<Object>() { -} - -inline ObjectReference::ObjectReference(napi_env env, napi_ref ref): Reference<Object>(env, ref) { -} - -inline ObjectReference::ObjectReference(Reference<Object>&& other) - : Reference<Object>(std::move(other)) { -} - -inline ObjectReference& ObjectReference::operator =(Reference<Object>&& other) { - static_cast<Reference<Object>*>(this)->operator=(std::move(other)); - return *this; -} - -inline ObjectReference::ObjectReference(ObjectReference&& other) - : Reference<Object>(std::move(other)) { -} - -inline ObjectReference& ObjectReference::operator =(ObjectReference&& other) { - static_cast<Reference<Object>*>(this)->operator=(std::move(other)); - return *this; -} - -inline ObjectReference::ObjectReference(const ObjectReference& other) - : Reference<Object>(other) { -} - -inline Napi::Value ObjectReference::Get(const char* utf8name) const { - EscapableHandleScope scope(_env); - return scope.Escape(Value().Get(utf8name)); -} - -inline Napi::Value ObjectReference::Get(const std::string& utf8name) const { - EscapableHandleScope scope(_env); - return scope.Escape(Value().Get(utf8name)); -} - -inline void ObjectReference::Set(const char* utf8name, napi_value value) { - HandleScope scope(_env); - Value().Set(utf8name, value); -} - -inline void ObjectReference::Set(const char* utf8name, Napi::Value value) { - HandleScope scope(_env); - Value().Set(utf8name, value); -} - -inline void ObjectReference::Set(const char* utf8name, const char* utf8value) { - HandleScope scope(_env); - Value().Set(utf8name, utf8value); -} - -inline void ObjectReference::Set(const char* utf8name, bool boolValue) { - HandleScope scope(_env); - Value().Set(utf8name, boolValue); -} - -inline void ObjectReference::Set(const char* utf8name, double numberValue) { - HandleScope scope(_env); - Value().Set(utf8name, numberValue); -} - -inline void ObjectReference::Set(const std::string& utf8name, napi_value value) { - HandleScope scope(_env); - Value().Set(utf8name, value); -} - -inline void ObjectReference::Set(const std::string& utf8name, Napi::Value value) { - HandleScope scope(_env); - Value().Set(utf8name, value); -} - -inline void ObjectReference::Set(const std::string& utf8name, std::string& utf8value) { - HandleScope scope(_env); - Value().Set(utf8name, utf8value); -} - -inline void ObjectReference::Set(const std::string& utf8name, bool boolValue) { - HandleScope scope(_env); - Value().Set(utf8name, boolValue); -} - -inline void ObjectReference::Set(const std::string& utf8name, double numberValue) { - HandleScope scope(_env); - Value().Set(utf8name, numberValue); -} - -inline Napi::Value ObjectReference::Get(uint32_t index) const { - EscapableHandleScope scope(_env); - return scope.Escape(Value().Get(index)); -} - -inline void ObjectReference::Set(uint32_t index, napi_value value) { - HandleScope scope(_env); - Value().Set(index, value); -} - -inline void ObjectReference::Set(uint32_t index, Napi::Value value) { - HandleScope scope(_env); - Value().Set(index, value); -} - -inline void ObjectReference::Set(uint32_t index, const char* utf8value) { - HandleScope scope(_env); - Value().Set(index, utf8value); -} - -inline void ObjectReference::Set(uint32_t index, const std::string& utf8value) { - HandleScope scope(_env); - Value().Set(index, utf8value); -} - -inline void ObjectReference::Set(uint32_t index, bool boolValue) { - HandleScope scope(_env); - Value().Set(index, boolValue); -} - -inline void ObjectReference::Set(uint32_t index, double numberValue) { - HandleScope scope(_env); - Value().Set(index, numberValue); -} - -//////////////////////////////////////////////////////////////////////////////// -// FunctionReference class -//////////////////////////////////////////////////////////////////////////////// - -inline FunctionReference::FunctionReference(): Reference<Function>() { -} - -inline FunctionReference::FunctionReference(napi_env env, napi_ref ref) - : Reference<Function>(env, ref) { -} - -inline FunctionReference::FunctionReference(Reference<Function>&& other) - : Reference<Function>(std::move(other)) { -} - -inline FunctionReference& FunctionReference::operator =(Reference<Function>&& other) { - static_cast<Reference<Function>*>(this)->operator=(std::move(other)); - return *this; -} - -inline FunctionReference::FunctionReference(FunctionReference&& other) - : Reference<Function>(std::move(other)) { -} - -inline FunctionReference& FunctionReference::operator =(FunctionReference&& other) { - static_cast<Reference<Function>*>(this)->operator=(std::move(other)); - return *this; -} - -inline Napi::Value FunctionReference::operator ()( - const std::initializer_list<napi_value>& args) const { - EscapableHandleScope scope(_env); - return scope.Escape(Value()(args)); -} - -inline Napi::Value FunctionReference::Call(const std::initializer_list<napi_value>& args) const { - EscapableHandleScope scope(_env); - Napi::Value result = Value().Call(args); - if (scope.Env().IsExceptionPending()) { - return Value(); - } - return scope.Escape(result); -} - -inline Napi::Value FunctionReference::Call(const std::vector<napi_value>& args) const { - EscapableHandleScope scope(_env); - Napi::Value result = Value().Call(args); - if (scope.Env().IsExceptionPending()) { - return Value(); - } - return scope.Escape(result); -} - -inline Napi::Value FunctionReference::Call( - napi_value recv, const std::initializer_list<napi_value>& args) const { - EscapableHandleScope scope(_env); - Napi::Value result = Value().Call(recv, args); - if (scope.Env().IsExceptionPending()) { - return Value(); - } - return scope.Escape(result); -} - -inline Napi::Value FunctionReference::Call( - napi_value recv, const std::vector<napi_value>& args) const { - EscapableHandleScope scope(_env); - Napi::Value result = Value().Call(recv, args); - if (scope.Env().IsExceptionPending()) { - return Value(); - } - return scope.Escape(result); -} - -inline Napi::Value FunctionReference::Call( - napi_value recv, size_t argc, const napi_value* args) const { - EscapableHandleScope scope(_env); - Napi::Value result = Value().Call(recv, argc, args); - if (scope.Env().IsExceptionPending()) { - return Value(); - } - return scope.Escape(result); -} - -inline Napi::Value FunctionReference::MakeCallback( - napi_value recv, - const std::initializer_list<napi_value>& args, - napi_async_context context) const { - EscapableHandleScope scope(_env); - Napi::Value result = Value().MakeCallback(recv, args, context); - if (scope.Env().IsExceptionPending()) { - return Value(); - } - return scope.Escape(result); -} - -inline Napi::Value FunctionReference::MakeCallback( - napi_value recv, - const std::vector<napi_value>& args, - napi_async_context context) const { - EscapableHandleScope scope(_env); - Napi::Value result = Value().MakeCallback(recv, args, context); - if (scope.Env().IsExceptionPending()) { - return Value(); - } - return scope.Escape(result); -} - -inline Napi::Value FunctionReference::MakeCallback( - napi_value recv, - size_t argc, - const napi_value* args, - napi_async_context context) const { - EscapableHandleScope scope(_env); - Napi::Value result = Value().MakeCallback(recv, argc, args, context); - if (scope.Env().IsExceptionPending()) { - return Value(); - } - return scope.Escape(result); -} - -inline Object FunctionReference::New(const std::initializer_list<napi_value>& args) const { - EscapableHandleScope scope(_env); - return scope.Escape(Value().New(args)).As<Object>(); -} - -inline Object FunctionReference::New(const std::vector<napi_value>& args) const { - EscapableHandleScope scope(_env); - return scope.Escape(Value().New(args)).As<Object>(); -} - -//////////////////////////////////////////////////////////////////////////////// -// 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 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 <typename Getter> -inline PropertyDescriptor -PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - const char* utf8name, - Getter getter, - napi_property_attributes attributes, - void* data) { - typedef details::CallbackData<Getter, Napi::Value> CbData; - 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 <typename Getter> -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 <typename Getter> -inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - Name name, - Getter getter, - napi_property_attributes attributes, - void* data) { - typedef details::CallbackData<Getter, Napi::Value> CbData; - 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 <typename Getter, typename Setter> -inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - const char* utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* data) { - typedef details::AccessorCallbackData<Getter, Setter> CbData; - 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 <typename Getter, typename Setter> -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 <typename Getter, typename Setter> -inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, - Napi::Object object, - Name name, - Getter getter, - Setter setter, - napi_property_attributes attributes, - void* data) { - typedef details::AccessorCallbackData<Getter, Setter> CbData; - 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 <typename Callable> -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 <typename Callable> -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 <typename Callable> -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; -} - -//////////////////////////////////////////////////////////////////////////////// -// ObjectWrap<T> class -//////////////////////////////////////////////////////////////////////////////// - -template <typename T> -inline ObjectWrap<T>::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<T*>(this); - status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref); - NAPI_THROW_IF_FAILED_VOID(env, status); - - Reference<Object>* instanceRef = instance; - *instanceRef = Reference<Object>(env, ref); -} - -template<typename T> -inline ObjectWrap<T>::~ObjectWrap() {} - -template<typename T> -inline T* ObjectWrap<T>::Unwrap(Object wrapper) { - T* unwrapped; - napi_status status = napi_unwrap(wrapper.Env(), wrapper, reinterpret_cast<void**>(&unwrapped)); - NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr); - return unwrapped; -} - -template <typename T> -inline Function -ObjectWrap<T>::DefineClass(Napi::Env env, - const char* utf8name, - const size_t props_count, - const napi_property_descriptor* descriptors, - void* data) { - napi_status status; - std::vector<napi_property_descriptor> 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<StaticMethodCallbackData*>(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<StaticVoidMethodCallbackData*>(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<StaticAccessorCallbackData*>(prop->data)); - NAPI_THROW_IF_FAILED(env, status, Function()); - } else if (prop->getter == T::InstanceGetterCallbackWrapper || - prop->setter == T::InstanceSetterCallbackWrapper) { - status = Napi::details::AttachData(env, - value, - static_cast<InstanceAccessorCallbackData*>(prop->data)); - NAPI_THROW_IF_FAILED(env, status, Function()); - } else if (prop->method != nullptr && !(prop->attributes & napi_static)) { - if (prop->method == T::InstanceVoidMethodCallbackWrapper) { - status = Napi::details::AttachData(env, - value, - static_cast<InstanceVoidMethodCallbackData*>(prop->data)); - NAPI_THROW_IF_FAILED(env, status, Function()); - } else if (prop->method == T::InstanceMethodCallbackWrapper) { - status = Napi::details::AttachData(env, - value, - static_cast<InstanceMethodCallbackData*>(prop->data)); - NAPI_THROW_IF_FAILED(env, status, Function()); - } - } - } - - return Function(env, value); -} - -template <typename T> -inline Function ObjectWrap<T>::DefineClass( - Napi::Env env, - const char* utf8name, - const std::initializer_list<ClassPropertyDescriptor<T>>& properties, - void* data) { - return DefineClass(env, - utf8name, - properties.size(), - reinterpret_cast<const napi_property_descriptor*>(properties.begin()), - data); -} - -template <typename T> -inline Function ObjectWrap<T>::DefineClass( - Napi::Env env, - const char* utf8name, - const std::vector<ClassPropertyDescriptor<T>>& properties, - void* data) { - return DefineClass(env, - utf8name, - properties.size(), - reinterpret_cast<const napi_property_descriptor*>(properties.data()), - data); -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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<napi_property_attributes>(attributes | napi_static); - return desc; -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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<napi_property_attributes>(attributes | napi_static); - return desc; -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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<napi_property_attributes>(attributes | napi_static); - return desc; -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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<napi_property_attributes>(attributes | napi_static); - return desc; -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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<napi_property_attributes>(attributes | napi_static); - return desc; -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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<napi_property_attributes>(attributes | napi_static); - return desc; -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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 <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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 <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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 <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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 <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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 <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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 <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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<napi_property_attributes>(attributes | napi_static); - return desc; -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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<napi_property_attributes>(attributes | napi_static); - return desc; -} - -template <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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 <typename T> -inline ClassPropertyDescriptor<T> ObjectWrap<T>::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 <typename T> -inline void ObjectWrap<T>::Finalize(Napi::Env /*env*/) {} - -template <typename T> -inline napi_value ObjectWrap<T>::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) { - napi_throw_type_error(env, nullptr, "Class constructors cannot be invoked without 'new'"); - return nullptr; - } - - T* instance; - napi_value wrapper = details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - instance = new T(callbackInfo); - return callbackInfo.This(); - }); - - return wrapper; -} - -template <typename T> -inline napi_value ObjectWrap<T>::StaticVoidMethodCallbackWrapper( - napi_env env, - napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - StaticVoidMethodCallbackData* callbackData = - reinterpret_cast<StaticVoidMethodCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - callbackData->callback(callbackInfo); - return nullptr; - }); -} - -template <typename T> -inline napi_value ObjectWrap<T>::StaticMethodCallbackWrapper( - napi_env env, - napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - StaticMethodCallbackData* callbackData = - reinterpret_cast<StaticMethodCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - return callbackData->callback(callbackInfo); - }); -} - -template <typename T> -inline napi_value ObjectWrap<T>::StaticGetterCallbackWrapper( - napi_env env, - napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - StaticAccessorCallbackData* callbackData = - reinterpret_cast<StaticAccessorCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - return callbackData->getterCallback(callbackInfo); - }); -} - -template <typename T> -inline napi_value ObjectWrap<T>::StaticSetterCallbackWrapper( - napi_env env, - napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - StaticAccessorCallbackData* callbackData = - reinterpret_cast<StaticAccessorCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - callbackData->setterCallback(callbackInfo, callbackInfo[0]); - return nullptr; - }); -} - -template <typename T> -inline napi_value ObjectWrap<T>::InstanceVoidMethodCallbackWrapper( - napi_env env, - napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - InstanceVoidMethodCallbackData* callbackData = - reinterpret_cast<InstanceVoidMethodCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - T* instance = Unwrap(callbackInfo.This().As<Object>()); - auto cb = callbackData->callback; - (instance->*cb)(callbackInfo); - return nullptr; - }); -} - -template <typename T> -inline napi_value ObjectWrap<T>::InstanceMethodCallbackWrapper( - napi_env env, - napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - InstanceMethodCallbackData* callbackData = - reinterpret_cast<InstanceMethodCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - T* instance = Unwrap(callbackInfo.This().As<Object>()); - auto cb = callbackData->callback; - return (instance->*cb)(callbackInfo); - }); -} - -template <typename T> -inline napi_value ObjectWrap<T>::InstanceGetterCallbackWrapper( - napi_env env, - napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - InstanceAccessorCallbackData* callbackData = - reinterpret_cast<InstanceAccessorCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - T* instance = Unwrap(callbackInfo.This().As<Object>()); - auto cb = callbackData->getterCallback; - return (instance->*cb)(callbackInfo); - }); -} - -template <typename T> -inline napi_value ObjectWrap<T>::InstanceSetterCallbackWrapper( - napi_env env, - napi_callback_info info) { - return details::WrapCallback([&] { - CallbackInfo callbackInfo(env, info); - InstanceAccessorCallbackData* callbackData = - reinterpret_cast<InstanceAccessorCallbackData*>(callbackInfo.Data()); - callbackInfo.SetData(callbackData->data); - T* instance = Unwrap(callbackInfo.This().As<Object>()); - auto cb = callbackData->setterCallback; - (instance->*cb)(callbackInfo, callbackInfo[0]); - return nullptr; - }); -} - -template <typename T> -inline void ObjectWrap<T>::FinalizeCallback(napi_env env, void* data, void* /*hint*/) { - T* instance = reinterpret_cast<T*>(data); - instance->Finalize(Napi::Env(env)); - delete instance; -} - -//////////////////////////////////////////////////////////////////////////////// -// 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 -//////////////////////////////////////////////////////////////////////////////// - -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, OnExecute, - OnWorkComplete, 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, OnExecute, - OnWorkComplete, 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::AsyncWorker(AsyncWorker&& other) { - _env = other._env; - other._env = nullptr; - _work = other._work; - other._work = nullptr; - _receiver = std::move(other._receiver); - _callback = std::move(other._callback); - _error = std::move(other._error); - _suppress_destruct = other._suppress_destruct; -} - -inline AsyncWorker& AsyncWorker::operator =(AsyncWorker&& other) { - _env = other._env; - other._env = nullptr; - _work = other._work; - other._work = nullptr; - _receiver = std::move(other._receiver); - _callback = std::move(other._callback); - _error = std::move(other._error); - _suppress_destruct = other._suppress_destruct; - return *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<napi_value>{ e.Value() }); - } -} - -inline void AsyncWorker::SetError(const std::string& error) { - _error = error; -} - -inline std::vector<napi_value> AsyncWorker::GetResult(Napi::Env /*env*/) { - return {}; -} -// The OnExecute method receives an napi_env argument. However, do NOT -// use it within this method, as it does not run on the main 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*/, void* this_pointer) { - AsyncWorker* self = static_cast<AsyncWorker*>(this_pointer); -#ifdef NAPI_CPP_EXCEPTIONS - try { - self->Execute(); - } catch (const std::exception& e) { - self->SetError(e.what()); - } -#else // NAPI_CPP_EXCEPTIONS - self->Execute(); -#endif // NAPI_CPP_EXCEPTIONS -} - -inline void AsyncWorker::OnWorkComplete( - napi_env /*env*/, napi_status status, void* this_pointer) { - AsyncWorker* self = static_cast<AsyncWorker*>(this_pointer); - if (status != napi_cancelled) { - HandleScope scope(self->_env); - details::WrapCallback([&] { - if (self->_error.size() == 0) { - self->OnOK(); - } - else { - self->OnError(Error::New(self->_env, self->_error)); - } - return nullptr; - }); - } - if (!self->_suppress_destruct) { - self->Destroy(); - } -} - -#if (NAPI_VERSION > 3) -//////////////////////////////////////////////////////////////////////////////// -// ThreadSafeFunction class -//////////////////////////////////////////////////////////////////////////////// - -// static -template <typename ResourceString> -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 <typename ResourceString, typename ContextType> -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 <typename ResourceString, typename Finalizer> -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 <typename ResourceString, typename Finalizer, - typename FinalizerDataType> -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 <typename ResourceString, typename ContextType, typename Finalizer> -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 <typename ResourceString, typename ContextType, - typename Finalizer, typename FinalizerDataType> -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 <typename ResourceString> -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<void*>(nullptr) /* context */); -} - -// static -template <typename ResourceString, typename ContextType> -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 <typename ResourceString, typename Finalizer> -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<void*>(nullptr) /* context */, - finalizeCallback, static_cast<void*>(nullptr) /* data */, - details::ThreadSafeFinalize<void, Finalizer>::Wrapper); -} - -// static -template <typename ResourceString, typename Finalizer, - typename FinalizerDataType> -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<void*>(nullptr) /* context */, - finalizeCallback, data, - details::ThreadSafeFinalize< - void, Finalizer, FinalizerDataType>::FinalizeWrapperWithData); -} - -// static -template <typename ResourceString, typename ContextType, typename Finalizer> -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<void*>(nullptr) /* data */, - details::ThreadSafeFinalize< - ContextType, Finalizer>::FinalizeWrapperWithContext); -} - -// static -template <typename ResourceString, typename ContextType, - typename Finalizer, typename FinalizerDataType> -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<ContextType, Finalizer, - FinalizerDataType>::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 <typename Callback> -inline napi_status ThreadSafeFunction::BlockingCall( - Callback callback) const { - return CallInternal(new CallbackWrapper(callback), napi_tsfn_blocking); -} - -template <typename DataType, typename Callback> -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 <typename Callback> -inline napi_status ThreadSafeFunction::NonBlockingCall( - Callback callback) const { - return CallInternal(new CallbackWrapper(callback), napi_tsfn_nonblocking); -} - -template <typename DataType, typename Callback> -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() { - return napi_release_threadsafe_function(_tsfn, napi_tsfn_release); -} - -inline napi_status ThreadSafeFunction::Abort() { - 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 <typename ResourceString, typename ContextType, - typename Finalizer, typename FinalizerDataType> -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<ResourceString>::value - || std::is_convertible<ResourceString, napi_value>::value, - "Resource name should be convertible to the string type"); - - ThreadSafeFunction tsfn; - auto* finalizeData = new details::ThreadSafeFinalize<ContextType, Finalizer, - FinalizerDataType>({ data, finalizeCallback, &tsfn._tsfn }); - 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; - } - - if (data != nullptr) { - auto* callbackWrapper = static_cast<CallbackWrapper*>(data); - (*callbackWrapper)(env, Function(env, jsCallback)); - delete callbackWrapper; - } else if (jsCallback != nullptr) { - Function(env, jsCallback).Call({}); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// Async Progress Worker class -//////////////////////////////////////////////////////////////////////////////// - -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback) - : AsyncProgressWorker(callback, "generic") { -} - -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback, - const char* resource_name) - : AsyncProgressWorker(callback, resource_name, Object::New(callback.Env())) { -} - -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(const Function& callback, - const char* resource_name, - const Object& resource) - : AsyncProgressWorker(Object::New(callback.Env()), - callback, - resource_name, - resource) { -} - -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver, - const Function& callback) - : AsyncProgressWorker(receiver, callback, "generic") { -} - -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver, - const Function& callback, - const char* resource_name) - : AsyncProgressWorker(receiver, - callback, - resource_name, - Object::New(callback.Env())) { -} - -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(const Object& receiver, - const Function& callback, - const char* resource_name, - const Object& resource) - : AsyncWorker(receiver, callback, resource_name, resource), - _asyncdata(nullptr), - _asyncsize(0) { - _tsfn = ThreadSafeFunction::New(callback.Env(), callback, resource_name, 1, 1); -} - -#if NAPI_VERSION > 4 -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env) - : AsyncProgressWorker(env, "generic") { -} - -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env, - const char* resource_name) - : AsyncProgressWorker(env, resource_name, Object::New(env)) { -} - -template<class T> -inline AsyncProgressWorker<T>::AsyncProgressWorker(Napi::Env env, - const char* resource_name, - const Object& resource) - : AsyncWorker(env, resource_name, resource), - _asyncdata(nullptr), - _asyncsize(0) { - // TODO: Once the changes to make the callback optional for threadsafe - // functions are no longer optional we can remove the dummy Function here. - Function callback; - _tsfn = ThreadSafeFunction::New(env, callback, resource_name, 1, 1); -} -#endif - -template<class T> -inline AsyncProgressWorker<T>::~AsyncProgressWorker() { - // Abort pending tsfn call. - // Don't send progress events after we've already completed. - _tsfn.Abort(); - { - std::lock_guard<std::mutex> lock(_mutex); - _asyncdata = nullptr; - _asyncsize = 0; - } - _tsfn.Release(); -} - -template<class T> -inline void AsyncProgressWorker<T>::Execute() { - ExecutionProgress progress(this); - Execute(progress); -} - -template<class T> -inline void AsyncProgressWorker<T>::WorkProgress_(Napi::Env /* env */, Napi::Function /* jsCallback */, void* _data) { - AsyncProgressWorker* self = static_cast<AsyncProgressWorker*>(_data); - - T* data; - size_t size; - { - std::lock_guard<std::mutex> lock(self->_mutex); - data = self->_asyncdata; - size = self->_asyncsize; - self->_asyncdata = nullptr; - self->_asyncsize = 0; - } - - self->OnProgress(data, size); - delete[] data; -} - -template<class T> -inline void AsyncProgressWorker<T>::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<std::mutex> lock(_mutex); - old_data = _asyncdata; - _asyncdata = new_data; - _asyncsize = count; - } - _tsfn.NonBlockingCall(this, WorkProgress_); - - delete[] old_data; -} - -template<class T> -inline void AsyncProgressWorker<T>::Signal() const { - _tsfn.NonBlockingCall(this, WorkProgress_); -} - -template<class T> -inline void AsyncProgressWorker<T>::ExecutionProgress::Signal() const { - _worker->Signal(); -} - -template<class T> -inline void AsyncProgressWorker<T>::ExecutionProgress::Send(const T* data, size_t count) const { - _worker->SendProgress_(data, count); -} - -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Memory Management class -//////////////////////////////////////////////////////////////////////////////// - -inline int64_t MemoryManagement::AdjustExternalMemory(Env env, int64_t change_in_bytes) { - int64_t result; - napi_status status = napi_adjust_external_memory(env, change_in_bytes, &result); - NAPI_THROW_IF_FAILED(env, status, 0); - return result; -} - -//////////////////////////////////////////////////////////////////////////////// -// Version Management class -//////////////////////////////////////////////////////////////////////////////// - -inline uint32_t VersionManagement::GetNapiVersion(Env env) { - uint32_t result; - napi_status status = napi_get_version(env, &result); - NAPI_THROW_IF_FAILED(env, status, 0); - return result; -} - -inline const napi_node_version* VersionManagement::GetNodeVersion(Env env) { - const napi_node_version* result; - napi_status status = napi_get_node_version(env, &result); - NAPI_THROW_IF_FAILED(env, status, 0); - return result; -} - -} // namespace Napi - -#endif // SRC_NAPI_INL_H_ diff --git a/node_modules/node-addon-api/napi.h b/node_modules/node-addon-api/napi.h deleted file mode 100644 index 2fc9b10..0000000 --- a/node_modules/node-addon-api/napi.h +++ /dev/null @@ -1,2171 +0,0 @@ -#ifndef SRC_NAPI_H_ -#define SRC_NAPI_H_ - -#include <node_api.h> -#include <functional> -#include <initializer_list> -#include <memory> -#include <mutex> -#include <string> -#include <vector> - -// 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<char16_t*>(L ## x) -#else -#define NAPI_WIDE_TEXT(x) u ## x -#endif - -// If C++ exceptions are not explicitly enabled or disabled, enable them -// if exceptions were enabled in the compiler settings. -#if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS) - #if defined(_CPPUNWIND) || defined (__EXCEPTIONS) - #define NAPI_CPP_EXCEPTIONS - #else - #error Exception support not detected. \ - Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS. - #endif -#endif - -#ifdef _NOEXCEPT - #define NAPI_NOEXCEPT _NOEXCEPT -#else - #define NAPI_NOEXCEPT noexcept -#endif - -#ifdef NAPI_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 // NAPI_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 // NAPI_CPP_EXCEPTIONS - -#define NAPI_FATAL_IF_FAILED(status, location, message) \ - do { \ - if ((status) != napi_ok) { \ - Napi::Error::Fatal((location), (message)); \ - } \ - } while (0) - -//////////////////////////////////////////////////////////////////////////////// -/// N-API C++ Wrapper Classes -/// -/// These classes wrap the "N-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 { - - // Forward declarations - class Env; - class Value; - class Boolean; - class Number; -// Currently experimental guard with the definition of NAPI_EXPERIMENTAL. -// Once it is no longer experimental guard with the NAPI_VERSION in which it is -// released instead. -#ifdef NAPI_EXPERIMENTAL - class BigInt; -#endif // NAPI_EXPERIMENTAL -#if (NAPI_VERSION > 4) - class Date; -#endif - class String; - class Object; - class Array; - class Function; - template <typename T> class Buffer; - class Error; - class PropertyDescriptor; - class CallbackInfo; - template <typename T> class Reference; - class TypedArray; - template <typename T> class TypedArrayOf; - - typedef TypedArrayOf<int8_t> Int8Array; ///< Typed-array of signed 8-bit integers - typedef TypedArrayOf<uint8_t> Uint8Array; ///< Typed-array of unsigned 8-bit integers - typedef TypedArrayOf<int16_t> Int16Array; ///< Typed-array of signed 16-bit integers - typedef TypedArrayOf<uint16_t> Uint16Array; ///< Typed-array of unsigned 16-bit integers - typedef TypedArrayOf<int32_t> Int32Array; ///< Typed-array of signed 32-bit integers - typedef TypedArrayOf<uint32_t> Uint32Array; ///< Typed-array of unsigned 32-bit integers - typedef TypedArrayOf<float> Float32Array; ///< Typed-array of 32-bit floating-point values - typedef TypedArrayOf<double> Float64Array; ///< Typed-array of 64-bit floating-point values -// Currently experimental guard with the definition of NAPI_EXPERIMENTAL. -// Once it is no longer experimental guard with the NAPI_VERSION in which it is -// released instead. -#ifdef NAPI_EXPERIMENTAL - typedef TypedArrayOf<int64_t> BigInt64Array; ///< Typed array of signed 64-bit integers - typedef TypedArrayOf<uint64_t> BigUint64Array; ///< Typed array of unsigned 64-bit integers -#endif // NAPI_EXPERIMENTAL - - /// Defines the signature of a N-API C++ module's registration callback (init) function. - typedef Object (*ModuleRegisterCallback)(Env env, Object exports); - - class MemoryManagement; - - /// Environment for N-API values and operations. - /// - /// All N-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 N-API values or other N-API operations within the callback. (Many methods infer - /// the environment from the `this` instance that the method is called on.) - /// - /// In the future, multiple environments per process may be supported, although current - /// implementations only support one environment per process. - /// - /// In the V8 JavaScript engine, a N-API environment approximately corresponds to an Isolate. - class Env { - public: - Env(napi_env env); - - operator napi_env() const; - - Object Global() const; - Value Undefined() const; - Value Null() const; - - bool IsExceptionPending() const; - Error GetAndClearPendingException(); - - private: - napi_env _env; - }; - - /// 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<Napi::String>(); // 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 N-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 <typename T> - static Value From(napi_env env, const T& value); - - /// Converts to a N-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. -// Currently experimental guard with the definition of NAPI_EXPERIMENTAL. -// Once it is no longer experimental guard with the NAPI_VERSION in which it is -// released instead. -#ifdef NAPI_EXPERIMENTAL - bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint. -#endif // NAPI_EXPERIMENTAL -#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. - - /// 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`. - template <typename T> T As() const; - - Boolean ToBoolean() const; ///< Coerces a value to a JavaScript boolean. - Number ToNumber() const; ///< Coerces a value to a JavaScript number. - String ToString() const; ///< Coerces a value to a JavaScript string. - Object 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, ///< N-API environment - bool value ///< Boolean value - ); - - Boolean(); ///< Creates a new _empty_ Boolean instance. - Boolean(napi_env env, napi_value value); ///< Wraps a N-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, ///< N-API environment - double value ///< Number value - ); - - Number(); ///< Creates a new _empty_ Number instance. - Number(napi_env env, napi_value value); ///< Wraps a N-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. - }; - -// Currently experimental guard with the definition of NAPI_EXPERIMENTAL. -// Once it is no longer experimental guard with the NAPI_VERSION in which it is -// released instead. -#ifdef NAPI_EXPERIMENTAL - /// A JavaScript bigint value. - class BigInt : public Value { - public: - static BigInt New( - napi_env env, ///< N-API environment - int64_t value ///< Number value - ); - static BigInt New( - napi_env env, ///< N-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, ///< N-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 - ); - - BigInt(); ///< Creates a new _empty_ BigInt instance. - BigInt(napi_env env, napi_value value); ///< Wraps a N-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_EXPERIMENTAL - -#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, ///< N-API environment - double value ///< Number value - ); - - Date(); ///< Creates a new _empty_ Date instance. - Date(napi_env env, napi_value value); ///< Wraps a N-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: - Name(); ///< Creates a new _empty_ Name instance. - Name(napi_env env, napi_value value); ///< Wraps a N-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, ///< N-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, ///< N-API environment - const std::u16string& value ///< UTF-16 encoded C++ string - ); - - /// Creates a new String value from a UTF-8 encoded C string. - static String New( - napi_env env, ///< N-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, ///< N-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, ///< N-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, ///< N-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 <typename T> - static String From(napi_env env, const T& value); - - String(); ///< Creates a new _empty_ String instance. - String(napi_env env, napi_value value); ///< Wraps a N-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. - }; - - /// A JavaScript symbol value. - class Symbol : public Name { - public: - /// Creates a new Symbol value with an optional description. - static Symbol New( - napi_env env, ///< N-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, ///< N-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, ///< N-API environment - String description ///< String value describing the symbol - ); - - /// Creates a new Symbol value with a description. - static Symbol New( - napi_env env, ///< N-API environment - napi_value description ///< String value describing the symbol - ); - - /// Get a public Symbol (e.g. Symbol.iterator). - static Symbol WellKnown(napi_env, const std::string& name); - - Symbol(); ///< Creates a new _empty_ Symbol instance. - Symbol(napi_env env, napi_value value); ///< Wraps a N-API value primitive. - }; - - /// A JavaScript object value. - class Object : public Value { - public: - /// Enables property and element assignments using indexing syntax. - /// - /// Example: - /// - /// Napi::Value propertyValue = object1['A']; - /// object2['A'] = propertyValue; - /// Napi::Value elementValue = array[0]; - /// array[1] = elementValue; - template <typename Key> - 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 <typename ValueType> - PropertyLValue& operator =(ValueType value); - - 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 ///< N-API environment - ); - - Object(); ///< Creates a new _empty_ Object instance. - Object(napi_env env, napi_value value); ///< Wraps a N-API value primitive. - - /// Gets or sets a named property. - PropertyLValue<std::string> operator []( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ); - - /// Gets or sets a named property. - PropertyLValue<std::string> operator []( - const std::string& utf8name ///< UTF-8 encoded property name - ); - - /// Gets or sets an indexed property or array element. - PropertyLValue<uint32_t> operator []( - uint32_t index /// Property / element index - ); - - /// Gets a named property. - Value operator []( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Gets a named property. - Value operator []( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Gets an indexed property or array element. - Value operator []( - uint32_t index ///< Property / element index - ) const; - - /// Checks whether a property is present. - bool Has( - napi_value key ///< Property key primitive - ) const; - - /// Checks whether a property is present. - bool Has( - Value key ///< Property key - ) const; - - /// Checks whether a named property is present. - bool Has( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Checks whether a named property is present. - bool Has( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Checks whether a own property is present. - bool HasOwnProperty( - napi_value key ///< Property key primitive - ) const; - - /// Checks whether a own property is present. - bool HasOwnProperty( - Value key ///< Property key - ) const; - - /// Checks whether a own property is present. - bool HasOwnProperty( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Checks whether a own property is present. - bool HasOwnProperty( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Gets a property. - Value Get( - napi_value key ///< Property key primitive - ) const; - - /// Gets a property. - Value Get( - Value key ///< Property key - ) const; - - /// Gets a named property. - Value Get( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ) const; - - /// Gets a named property. - Value Get( - const std::string& utf8name ///< UTF-8 encoded property name - ) const; - - /// Sets a property. - template <typename ValueType> - void Set( - napi_value key, ///< Property key primitive - const ValueType& value ///< Property value primitive - ); - - /// Sets a property. - template <typename ValueType> - void Set( - Value key, ///< Property key - const ValueType& value ///< Property value - ); - - /// Sets a named property. - template <typename ValueType> - void Set( - const char* utf8name, ///< UTF-8 encoded null-terminated property name - const ValueType& value - ); - - /// Sets a named property. - template <typename ValueType> - void Set( - const std::string& utf8name, ///< UTF-8 encoded property name - const ValueType& value ///< Property value primitive - ); - - /// Delete property. - bool Delete( - napi_value key ///< Property key primitive - ); - - /// Delete property. - bool Delete( - Value key ///< Property key - ); - - /// Delete property. - bool Delete( - const char* utf8name ///< UTF-8 encoded null-terminated property name - ); - - /// Delete property. - bool Delete( - const std::string& utf8name ///< UTF-8 encoded property name - ); - - /// Checks whether an indexed property is present. - bool Has( - uint32_t index ///< Property / element index - ) const; - - /// Gets an indexed property or array element. - Value Get( - uint32_t index ///< Property / element index - ) const; - - /// Sets an indexed property or array element. - template <typename ValueType> - void Set( - uint32_t index, ///< Property / element index - const ValueType& value ///< Property value primitive - ); - - /// Deletes an indexed property or array element. - bool Delete( - uint32_t index ///< Property / element index - ); - - Array GetPropertyNames() const; ///< Get all property names - - /// Defines a property on the object. - void DefineProperty( - const PropertyDescriptor& property ///< Descriptor for the property to be defined - ); - - /// Defines properties on the object. - void DefineProperties( - const std::initializer_list<PropertyDescriptor>& properties - ///< List of descriptors for the properties to be defined - ); - - /// Defines properties on the object. - void DefineProperties( - const std::vector<PropertyDescriptor>& properties - ///< Vector of descriptors for the properties to be defined - ); - - /// Checks if an object is an instance created by a constructor function. - /// - /// This is equivalent to the JavaScript `instanceof` operator. - bool InstanceOf( - const Function& constructor ///< Constructor function - ) const; - - template <typename Finalizer, typename T> - inline void AddFinalizer(Finalizer finalizeCallback, T* data); - - template <typename Finalizer, typename T, typename Hint> - inline void AddFinalizer(Finalizer finalizeCallback, - T* data, - Hint* finalizeHint); - }; - - template <typename T> - class External : public Value { - public: - static External New(napi_env env, T* data); - - // Finalizer must implement `void operator()(Env env, T* data)`. - template <typename Finalizer> - static External New(napi_env env, - T* data, - Finalizer finalizeCallback); - // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. - template <typename Finalizer, typename Hint> - static External New(napi_env env, - T* data, - Finalizer finalizeCallback, - Hint* finalizeHint); - - 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); - - Array(); - Array(napi_env env, napi_value value); - - uint32_t Length() const; - }; - - /// 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, ///< N-API environment - size_t byteLength ///< Length of the buffer to be allocated, in bytes - ); - - /// Creates a new ArrayBuffer instance, using an external buffer with specified byte length. - static ArrayBuffer New( - napi_env env, ///< N-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 <typename Finalizer> - static ArrayBuffer New( - napi_env env, ///< N-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 <typename Finalizer, typename Hint> - static ArrayBuffer New( - napi_env env, ///< N-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 - ); - - ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. - ArrayBuffer(napi_env env, napi_value value); ///< Wraps a N-API value primitive. - - void* Data(); ///< Gets a pointer to the data buffer. - size_t ByteLength(); ///< Gets the length of the array buffer in bytes. - - private: - mutable void* _data; - mutable size_t _length; - - ArrayBuffer(napi_env env, napi_value value, void* data, size_t length); - void EnsureInfo() const; - }; - - /// A JavaScript typed-array value with unknown array type. - /// - /// For type-specific operations, cast to a `TypedArrayOf<T>` instance using the `As()` - /// method: - /// - /// Napi::TypedArray array = ... - /// if (t.TypedArrayType() == napi_int32_array) { - /// Napi::Int32Array int32Array = t.As<Napi::Int32Array>(); - /// } - class TypedArray : public Object { - public: - TypedArray(); ///< Creates a new _empty_ TypedArray instance. - TypedArray(napi_env env, napi_value value); ///< Wraps a N-API value primitive. - - napi_typedarray_type TypedArrayType() const; ///< Gets the type of this typed-array. - Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. - - 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); - - static const napi_typedarray_type unknown_array_type = static_cast<napi_typedarray_type>(-1); - - template <typename T> - static -#if defined(NAPI_HAS_CONSTEXPR) - constexpr -#endif - napi_typedarray_type TypedArrayTypeForPrimitiveType() { - return std::is_same<T, int8_t>::value ? napi_int8_array - : std::is_same<T, uint8_t>::value ? napi_uint8_array - : std::is_same<T, int16_t>::value ? napi_int16_array - : std::is_same<T, uint16_t>::value ? napi_uint16_array - : std::is_same<T, int32_t>::value ? napi_int32_array - : std::is_same<T, uint32_t>::value ? napi_uint32_array - : std::is_same<T, float>::value ? napi_float32_array - : std::is_same<T, double>::value ? napi_float64_array -// Currently experimental guard with the definition of NAPI_EXPERIMENTAL. -// Once it is no longer experimental guard with the NAPI_VERSION in which it is -// released instead. -#ifdef NAPI_EXPERIMENTAL - : std::is_same<T, int64_t>::value ? napi_bigint64_array - : std::is_same<T, uint64_t>::value ? napi_biguint64_array -#endif // NAPI_EXPERIMENTAL - : unknown_array_type; - } - /// !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 <typename T> - 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, ///< N-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<T>() -#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, ///< N-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<T>() -#else - napi_typedarray_type type -#endif - ///< Type of array, if different from the default array type for the template parameter T. - ); - - TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. - TypedArrayOf(napi_env env, napi_value value); ///< Wraps a N-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); - - DataView(); ///< Creates a new _empty_ DataView instance. - DataView(napi_env env, napi_value value); ///< Wraps a N-API value primitive. - - Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. - 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 <typename T> - T ReadData(size_t byteOffset) const; - - template <typename T> - void WriteData(size_t byteOffset, T value) const; - - void* _data; - size_t _length; - }; - - class Function : public Object { - public: - /// Callable must implement operator() accepting a const CallbackInfo& - /// and return either void or Value. - template <typename Callable> - 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 <typename Callable> - static Function New(napi_env env, - Callable cb, - const std::string& utf8name, - void* data = nullptr); - - Function(); - Function(napi_env env, napi_value value); - - Value operator ()(const std::initializer_list<napi_value>& args) const; - - Value Call(const std::initializer_list<napi_value>& args) const; - Value Call(const std::vector<napi_value>& args) const; - Value Call(size_t argc, const napi_value* args) const; - Value Call(napi_value recv, const std::initializer_list<napi_value>& args) const; - Value Call(napi_value recv, const std::vector<napi_value>& args) const; - Value Call(napi_value recv, size_t argc, const napi_value* args) const; - - Value MakeCallback(napi_value recv, - const std::initializer_list<napi_value>& args, - napi_async_context context = nullptr) const; - Value MakeCallback(napi_value recv, - const std::vector<napi_value>& args, - napi_async_context context = nullptr) const; - Value MakeCallback(napi_value recv, - size_t argc, - const napi_value* args, - napi_async_context context = nullptr) const; - - Object New(const std::initializer_list<napi_value>& args) const; - Object New(const std::vector<napi_value>& args) const; - Object 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; - }; - - Promise(napi_env env, napi_value value); - }; - - template <typename T> - class Buffer : public Uint8Array { - public: - static Buffer<T> New(napi_env env, size_t length); - static Buffer<T> New(napi_env env, T* data, size_t length); - - // Finalizer must implement `void operator()(Env env, T* data)`. - template <typename Finalizer> - static Buffer<T> New(napi_env env, T* data, - size_t length, - Finalizer finalizeCallback); - // Finalizer must implement `void operator()(Env env, T* data, Hint* hint)`. - template <typename Finalizer, typename Hint> - static Buffer<T> New(napi_env env, T* data, - size_t length, - Finalizer finalizeCallback, - Hint* finalizeHint); - - static Buffer<T> Copy(napi_env env, const T* data, size_t length); - - Buffer(); - Buffer(napi_env env, napi_value value); - size_t Length() const; - T* Data() const; - - private: - mutable size_t _length; - mutable T* _data; - - Buffer(napi_env env, napi_value value, size_t length, T* data); - void EnsureInfo() const; - }; - - /// 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 <typename T> - class Reference { - public: - static Reference<T> 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<T>&& other); - Reference<T>& operator =(Reference<T>&& other); - Reference<T>& operator =(Reference<T>&) = delete; - - operator napi_ref() const; - bool operator ==(const Reference<T> &other) const; - bool operator !=(const Reference<T> &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(); - uint32_t Unref(); - 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. - void SuppressDestruct(); - - protected: - Reference(const Reference<T>&); - - /// !cond INTERNAL - napi_env _env; - napi_ref _ref; - /// !endcond - - private: - bool _suppressDestruct; - }; - - class ObjectReference: public Reference<Object> { - public: - ObjectReference(); - ObjectReference(napi_env env, napi_ref ref); - - // A reference can be moved but cannot be copied. - ObjectReference(Reference<Object>&& other); - ObjectReference& operator =(Reference<Object>&& other); - ObjectReference(ObjectReference&& other); - ObjectReference& operator =(ObjectReference&& other); - ObjectReference& operator =(ObjectReference&) = delete; - - Napi::Value Get(const char* utf8name) const; - Napi::Value Get(const std::string& utf8name) const; - void Set(const char* utf8name, napi_value value); - void Set(const char* utf8name, Napi::Value value); - void Set(const char* utf8name, const char* utf8value); - void Set(const char* utf8name, bool boolValue); - void Set(const char* utf8name, double numberValue); - void Set(const std::string& utf8name, napi_value value); - void Set(const std::string& utf8name, Napi::Value value); - void Set(const std::string& utf8name, std::string& utf8value); - void Set(const std::string& utf8name, bool boolValue); - void Set(const std::string& utf8name, double numberValue); - - Napi::Value Get(uint32_t index) const; - void Set(uint32_t index, const napi_value value); - void Set(uint32_t index, const Napi::Value value); - void Set(uint32_t index, const char* utf8value); - void Set(uint32_t index, const std::string& utf8value); - void Set(uint32_t index, bool boolValue); - void Set(uint32_t index, double numberValue); - - protected: - ObjectReference(const ObjectReference&); - }; - - class FunctionReference: public Reference<Function> { - public: - FunctionReference(); - FunctionReference(napi_env env, napi_ref ref); - - // A reference can be moved but cannot be copied. - FunctionReference(Reference<Function>&& other); - FunctionReference& operator =(Reference<Function>&& other); - FunctionReference(FunctionReference&& other); - FunctionReference& operator =(FunctionReference&& other); - FunctionReference(const FunctionReference&) = delete; - FunctionReference& operator =(FunctionReference&) = delete; - - Napi::Value operator ()(const std::initializer_list<napi_value>& args) const; - - Napi::Value Call(const std::initializer_list<napi_value>& args) const; - Napi::Value Call(const std::vector<napi_value>& args) const; - Napi::Value Call(napi_value recv, const std::initializer_list<napi_value>& args) const; - Napi::Value Call(napi_value recv, const std::vector<napi_value>& args) const; - Napi::Value Call(napi_value recv, size_t argc, const napi_value* args) const; - - Napi::Value MakeCallback(napi_value recv, - const std::initializer_list<napi_value>& args, - napi_async_context context = nullptr) const; - Napi::Value MakeCallback(napi_value recv, - const std::vector<napi_value>& args, - napi_async_context context = nullptr) const; - Napi::Value MakeCallback(napi_value recv, - size_t argc, - const napi_value* args, - napi_async_context context = nullptr) const; - - Object New(const std::initializer_list<napi_value>& args) const; - Object New(const std::vector<napi_value>& args) const; - }; - - // Shortcuts to creating a new reference with inferred type and refcount = 0. - template <typename T> Reference<T> Weak(T value); - ObjectReference Weak(Object value); - FunctionReference Weak(Function value); - - // Shortcuts to creating a new reference with inferred type and refcount = 1. - template <typename T> Reference<T> 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 N-API call fails without executing any JavaScript code (for example due to an invalid - /// argument), then the N-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 N-API - /// throws a JavaScript exception, then the N-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 N-API C++ callback, then the N-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 propataged as a JavaScript exception when the callback returns to JavaScript. - /// - /// #### Example 2A - Propagating a N-API C++ exception: - /// - /// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>(); - /// 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 N-API C++ exception: - /// - /// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>(); - /// 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 `NAPI_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 N-API JS exception: - /// - /// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>(); - /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); - /// if (result.IsEmpty()) return; - /// - /// An empty value result from a N-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 N-API JS exception: - /// - /// Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>(); - /// 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 NAPI_CPP_EXCEPTIONS - , public std::exception -#endif // NAPI_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 =(Error&); - - const std::string& Message() const NAPI_NOEXCEPT; - void ThrowAsJavaScriptException() const; - -#ifdef NAPI_CPP_EXCEPTIONS - const char* what() const NAPI_NOEXCEPT override; -#endif // NAPI_CPP_EXCEPTIONS - - protected: - /// !cond INTERNAL - typedef napi_status (*create_error_fn)(napi_env envb, napi_value code, napi_value msg, napi_value* result); - - template <typename TError> - static TError New(napi_env env, - const char* message, - size_t length, - create_error_fn create_error); - /// !endcond - - private: - 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); - }; - - class CallbackInfo { - public: - CallbackInfo(napi_env env, napi_callback_info info); - ~CallbackInfo(); - - // Disallow copying to prevent multiple free of _dynamicArgs - CallbackInfo(CallbackInfo const &) = delete; - void operator=(CallbackInfo const &) = delete; - - 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); - - 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: -#ifndef NODE_ADDON_API_DISABLE_DEPRECATED - template <typename Getter> - static PropertyDescriptor Accessor(const char* utf8name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter> - static PropertyDescriptor Accessor(const std::string& utf8name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter> - static PropertyDescriptor Accessor(napi_value name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter> - static PropertyDescriptor Accessor(Name name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter, typename Setter> - static PropertyDescriptor Accessor(const char* utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter, typename Setter> - static PropertyDescriptor Accessor(const std::string& utf8name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter, typename Setter> - static PropertyDescriptor Accessor(napi_value name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter, typename Setter> - static PropertyDescriptor Accessor(Name name, - Getter getter, - Setter setter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Callable> - static PropertyDescriptor Function(const char* utf8name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Callable> - static PropertyDescriptor Function(const std::string& utf8name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Callable> - static PropertyDescriptor Function(napi_value name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Callable> - static PropertyDescriptor Function(Name name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); -#endif // !NODE_ADDON_API_DISABLE_DEPRECATED - - template <typename Getter> - static PropertyDescriptor Accessor(Napi::Env env, - Napi::Object object, - const char* utf8name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter> - 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 <typename Getter> - static PropertyDescriptor Accessor(Napi::Env env, - Napi::Object object, - Name name, - Getter getter, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Getter, typename Setter> - 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 <typename Getter, typename Setter> - 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 <typename Getter, typename Setter> - 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 <typename Callable> - static PropertyDescriptor Function(Napi::Env env, - Napi::Object object, - const char* utf8name, - Callable cb, - napi_property_attributes attributes = napi_default, - void* data = nullptr); - template <typename Callable> - 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 <typename Callable> - 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<T>` subclass. This prevents using descriptors from a different class when - /// defining a new class (preventing the callbacks from having incorrect `this` pointers). - template <typename T> - 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; - }; - - /// 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<Example> { - /// public: - /// static void Initialize(Napi::Env& env, Napi::Object& target) { - /// Napi::Function constructor = DefineClass(env, "Example", { - /// InstanceAccessor("value", &Example::GetSomething, &Example::SetSomething), - /// InstanceMethod("doSomething", &Example::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 <typename T> - class ObjectWrap : public Reference<Object> { - public: - ObjectWrap(const CallbackInfo& callbackInfo); - virtual ~ObjectWrap(); - - static T* Unwrap(Object wrapper); - - // Methods exposed to JavaScript must conform to one of these callback signatures. - typedef void (*StaticVoidMethodCallback)(const CallbackInfo& info); - typedef Napi::Value (*StaticMethodCallback)(const CallbackInfo& info); - typedef Napi::Value (*StaticGetterCallback)(const CallbackInfo& info); - typedef void (*StaticSetterCallback)(const CallbackInfo& info, const Napi::Value& value); - typedef void (T::*InstanceVoidMethodCallback)(const CallbackInfo& info); - typedef Napi::Value (T::*InstanceMethodCallback)(const CallbackInfo& info); - typedef Napi::Value (T::*InstanceGetterCallback)(const CallbackInfo& info); - typedef void (T::*InstanceSetterCallback)(const CallbackInfo& info, const Napi::Value& value); - - typedef ClassPropertyDescriptor<T> PropertyDescriptor; - - static Function DefineClass(Napi::Env env, - const char* utf8name, - const std::initializer_list<PropertyDescriptor>& properties, - void* data = nullptr); - static Function DefineClass(Napi::Env env, - const char* utf8name, - const std::vector<PropertyDescriptor>& 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); - 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); - 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); - 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); - 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 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); - virtual void Finalize(Napi::Env env); - - private: - 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 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); - static void FinalizeCallback(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); - - template <typename TCallback> - struct MethodCallbackData { - TCallback callback; - void* data; - }; - typedef MethodCallbackData<StaticVoidMethodCallback> StaticVoidMethodCallbackData; - typedef MethodCallbackData<StaticMethodCallback> StaticMethodCallbackData; - typedef MethodCallbackData<InstanceVoidMethodCallback> InstanceVoidMethodCallbackData; - typedef MethodCallbackData<InstanceMethodCallback> InstanceMethodCallbackData; - - template <typename TGetterCallback, typename TSetterCallback> - struct AccessorCallbackData { - TGetterCallback getterCallback; - TSetterCallback setterCallback; - void* data; - }; - typedef AccessorCallbackData<StaticGetterCallback, StaticSetterCallback> - StaticAccessorCallbackData; - typedef AccessorCallbackData<InstanceGetterCallback, InstanceSetterCallback> - InstanceAccessorCallbackData; - }; - - 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 - HandleScope(HandleScope const &) = delete; - void operator=(HandleScope const &) = delete; - - 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 - EscapableHandleScope(EscapableHandleScope const &) = delete; - void operator=(EscapableHandleScope const &) = delete; - - 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 - CallbackScope(CallbackScope const &) = delete; - void operator=(CallbackScope const &) = delete; - - 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); - AsyncContext(const AsyncContext&) = delete; - AsyncContext& operator =(AsyncContext&) = delete; - - operator napi_async_context() const; - - Napi::Env Env() const; - - private: - napi_env _env; - napi_async_context _context; - }; - - class AsyncWorker { - public: - virtual ~AsyncWorker(); - - // An async worker can be moved but cannot be copied. - AsyncWorker(AsyncWorker&& other); - AsyncWorker& operator =(AsyncWorker&& other); - AsyncWorker(const AsyncWorker&) = delete; - AsyncWorker& operator =(AsyncWorker&) = delete; - - operator napi_async_work() const; - - Napi::Env Env() const; - - void Queue(); - void Cancel(); - void SuppressDestruct(); - - ObjectReference& Receiver(); - FunctionReference& Callback(); - - 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<napi_value> GetResult(Napi::Env env); - - void SetError(const std::string& error); - - private: - static void OnExecute(napi_env env, void* this_pointer); - static void OnWorkComplete(napi_env env, - napi_status status, - void* this_pointer); - - napi_env _env; - napi_async_work _work; - ObjectReference _receiver; - FunctionReference _callback; - std::string _error; - bool _suppress_destruct; - }; - - #if (NAPI_VERSION > 3) - class ThreadSafeFunction { - public: - // This API may only be called from the main thread. - template <typename ResourceString> - 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 <typename ResourceString, typename ContextType> - 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 <typename ResourceString, typename Finalizer> - 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 <typename ResourceString, typename Finalizer, - typename FinalizerDataType> - 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 <typename ResourceString, typename ContextType, typename Finalizer> - 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 <typename ResourceString, typename ContextType, - typename Finalizer, typename FinalizerDataType> - 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 <typename ResourceString> - 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 <typename ResourceString, typename ContextType> - 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 <typename ResourceString, typename Finalizer> - 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 <typename ResourceString, typename Finalizer, - typename FinalizerDataType> - 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 <typename ResourceString, typename ContextType, typename Finalizer> - 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 <typename ResourceString, typename ContextType, - typename Finalizer, typename FinalizerDataType> - 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 <typename Callback> - napi_status BlockingCall(Callback callback) const; - - // This API may be called from any thread. - template <typename DataType, typename Callback> - 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 <typename Callback> - napi_status NonBlockingCall(Callback callback) const; - - // This API may be called from any thread. - template <typename DataType, typename Callback> - 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(); - - // This API may be called from any thread. - napi_status Abort(); - - struct ConvertibleContext - { - template <class T> - operator T*() { return static_cast<T*>(context); } - void* context; - }; - - // This API may be called from any thread. - ConvertibleContext GetContext() const; - - private: - using CallbackWrapper = std::function<void(Napi::Env, Napi::Function)>; - - template <typename ResourceString, typename ContextType, - typename Finalizer, typename FinalizerDataType> - 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; - }; - - template<class T> - class AsyncProgressWorker : public AsyncWorker { - 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; - }; - - 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: - static void WorkProgress_(Napi::Env env, Napi::Function jsCallback, void* data); - - void Execute() override; - void Signal() const; - void SendProgress_(const T* data, size_t count); - - std::mutex _mutex; - T* _asyncdata; - size_t _asyncsize; - ThreadSafeFunction _tsfn; - }; - #endif - - // Memory management. - class MemoryManagement { - public: - static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes); - }; - - // Version management - class VersionManagement { - public: - static uint32_t GetNapiVersion(Env env); - static const napi_node_version* GetNodeVersion(Env env); - }; - -} // namespace Napi - -// Inline implementations of all the above class methods are included here. -#include "napi-inl.h" - -#endif // SRC_NAPI_H_ diff --git a/node_modules/node-addon-api/package.json b/node_modules/node-addon-api/package.json deleted file mode 100644 index 428dd78..0000000 --- a/node_modules/node-addon-api/package.json +++ /dev/null @@ -1,268 +0,0 @@ -{ - "_from": "node-addon-api@^2.0.0", - "_id": "[email protected]", - "_inBundle": false, - "_integrity": "sha512-ASCL5U13as7HhOExbT6OlWJJUV/lLzL2voOSP1UVehpRD8FbSrSDjfScK/KwAvVTI5AS6r4VwbOMlIqtvRidnA==", - "_location": "/node-addon-api", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "node-addon-api@^2.0.0", - "name": "node-addon-api", - "escapedName": "node-addon-api", - "rawSpec": "^2.0.0", - "saveSpec": null, - "fetchSpec": "^2.0.0" - }, - "_requiredBy": [ - "/@discordjs/opus" - ], - "_resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-2.0.0.tgz", - "_shasum": "f9afb8d777a91525244b01775ea0ddbe1125483b", - "_spec": "node-addon-api@^2.0.0", - "_where": "E:\\Documents\\GitHub\\s5nical\\node_modules\\@discordjs\\opus", - "bugs": { - "url": "https://github.com/nodejs/node-addon-api/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Abhishek Kumar Singh", - "url": "https://github.com/abhi11210646" - }, - { - "name": "Alba Mendez", - "url": "https://github.com/jmendeth" - }, - { - "name": "Andrew Petersen", - "url": "https://github.com/kirbysayshi" - }, - { - "name": "Anisha Rohra", - "url": "https://github.com/anisha-rohra" - }, - { - "name": "Anna Henningsen", - "url": "https://github.com/addaleax" - }, - { - "name": "Arnaud Botella", - "url": "https://github.com/BotellaA" - }, - { - "name": "Arunesh Chandra", - "url": "https://github.com/aruneshchandra" - }, - { - "name": "Ben Berman", - "url": "https://github.com/rivertam" - }, - { - "name": "Benjamin Byholm", - "url": "https://github.com/kkoopa" - }, - { - "name": "Bill Gallafent", - "url": "https://github.com/gallafent" - }, - { - "name": "Bruce A. MacNaughton", - "url": "https://github.com/bmacnaughton" - }, - { - "name": "Cory Mickelson", - "url": "https://github.com/corymickelson" - }, - { - "name": "David Halls", - "url": "https://github.com/davedoesdev" - }, - { - "name": "Dongjin Na", - "url": "https://github.com/nadongguri" - }, - { - "name": "Eric Bickle", - "url": "https://github.com/ebickle" - }, - { - "name": "Gabriel Schulhof", - "url": "https://github.com/gabrielschulhof" - }, - { - "name": "Gus Caplan", - "url": "https://github.com/devsnek" - }, - { - "name": "Hitesh Kanwathirtha", - "url": "https://github.com/digitalinfinity" - }, - { - "name": "Jake Barnes", - "url": "https://github.com/DuBistKomisch" - }, - { - "name": "Jake Yoon", - "url": "https://github.com/yjaeseok" - }, - { - "name": "Jason Ginchereau", - "url": "https://github.com/jasongin" - }, - { - "name": "Jim Schlight", - "url": "https://github.com/jschlight" - }, - { - "name": "Jinho Bang", - "url": "https://github.com/romandev" - }, - { - "name": "joshgarde", - "url": "https://github.com/joshgarde" - }, - { - "name": "Kevin Eady", - "url": "https://github.com/KevinEady" - }, - { - "name": "Konstantin Tarkus", - "url": "https://github.com/koistya" - }, - { - "name": "Kyle Farnung", - "url": "https://github.com/kfarnung" - }, - { - "name": "legendecas", - "url": "https://github.com/legendecas" - }, - { - "name": "Luciano Martorella", - "url": "https://github.com/lmartorella" - }, - { - "name": "Mathias Küsel", - "url": "https://github.com/mathiask88" - }, - { - "name": "Matteo Collina", - "url": "https://github.com/mcollina" - }, - { - "name": "Michael Dawson", - "url": "https://github.com/mhdawson" - }, - { - "name": "Michael Price", - "url": "https://github.com/mikepricedev" - }, - { - "name": "Michele Campus", - "url": "https://github.com/kYroL01" - }, - { - "name": "Mikhail Cheshkov", - "url": "https://github.com/mcheshkov" - }, - { - "name": "Nicola Del Gobbo", - "url": "https://github.com/NickNaso" - }, - { - "name": "Nick Soggin", - "url": "https://github.com/iSkore" - }, - { - "name": "Nurbol Alpysbayev", - "url": "https://github.com/anurbol" - }, - { - "name": "Philipp Renoth", - "url": "https://github.com/DaAitch" - }, - { - "name": "Rolf Timmermans", - "url": "https://github.com/rolftimmermans" - }, - { - "name": "Ross Weir", - "url": "https://github.com/ross-weir" - }, - { - "name": "Ryuichi Okumura", - "url": "https://github.com/okuryu" - }, - { - "name": "Sampson Gao", - "url": "https://github.com/sampsongao" - }, - { - "name": "Sam Roberts", - "url": "https://github.com/sam-github" - }, - { - "name": "Taylor Woll", - "url": "https://github.com/boingoing" - }, - { - "name": "Thomas Gentilhomme", - "url": "https://github.com/fraxken" - }, - { - "name": "Tim Rach", - "url": "https://github.com/timrach" - }, - { - "name": "Tobias Nießen", - "url": "https://github.com/tniessen" - }, - { - "name": "Tux3", - "url": "https://github.com/tux3" - }, - { - "name": "Yohei Kishimoto", - "url": "https://github.com/morokosi" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Node.js API (N-API)", - "devDependencies": { - "safe-buffer": "^5.1.1" - }, - "directories": {}, - "homepage": "https://github.com/nodejs/node-addon-api", - "keywords": [ - "n-api", - "napi", - "addon", - "native", - "bindings", - "c", - "c++", - "nan", - "node-addon-api" - ], - "license": "MIT", - "main": "index.js", - "name": "node-addon-api", - "optionalDependencies": {}, - "repository": { - "type": "git", - "url": "git://github.com/nodejs/node-addon-api.git" - }, - "scripts": { - "dev": "node test", - "dev:incremental": "node test", - "doc": "doxygen doc/Doxyfile", - "predev": "node-gyp rebuild -C test --debug", - "predev:incremental": "node-gyp configure build -C test --debug", - "pretest": "node-gyp rebuild -C test", - "test": "node test" - }, - "version": "2.0.0" -} diff --git a/node_modules/node-addon-api/src/node_api.cc b/node_modules/node-addon-api/src/node_api.cc deleted file mode 100644 index dd16016..0000000 --- a/node_modules/node-addon-api/src/node_api.cc +++ /dev/null @@ -1,3649 +0,0 @@ -/****************************************************************************** - * Experimental prototype for demonstrating VM agnostic and ABI stable API - * for native modules to use instead of using Nan and V8 APIs directly. - * - * The current status is "Experimental" and should not be used for - * production applications. The API is still subject to change - * and as an experimental feature is NOT subject to semver. - * - ******************************************************************************/ - -#include <node_buffer.h> -#include <node_object_wrap.h> -#include <limits.h> // INT_MAX -#include <string.h> -#include <algorithm> -#include <cmath> -#include <vector> -#include "node_api.h" -#include "node_internals.h" - -#define NAPI_VERSION 1 - -static -napi_status napi_set_last_error(napi_env env, napi_status error_code, - uint32_t engine_error_code = 0, - void* engine_reserved = nullptr); -static -napi_status napi_clear_last_error(napi_env env); - -struct napi_env__ { - explicit napi_env__(v8::Isolate* _isolate): isolate(_isolate), - has_instance_available(true), last_error() {} - ~napi_env__() { - last_exception.Reset(); - has_instance.Reset(); - wrap_template.Reset(); - } - v8::Isolate* isolate; - v8::Persistent<v8::Value> last_exception; - v8::Persistent<v8::Value> has_instance; - v8::Persistent<v8::ObjectTemplate> wrap_template; - bool has_instance_available; - napi_extended_error_info last_error; - int open_handle_scopes = 0; -}; - -#define ENV_OBJECT_TEMPLATE(env, prefix, destination, field_count) \ - do { \ - if ((env)->prefix ## _template.IsEmpty()) { \ - (destination) = v8::ObjectTemplate::New(isolate); \ - (destination)->SetInternalFieldCount((field_count)); \ - (env)->prefix ## _template.Reset(isolate, (destination)); \ - } else { \ - (destination) = v8::Local<v8::ObjectTemplate>::New( \ - isolate, env->prefix ## _template); \ - } \ - } while (0) - -#define RETURN_STATUS_IF_FALSE(env, condition, status) \ - do { \ - if (!(condition)) { \ - return napi_set_last_error((env), (status)); \ - } \ - } while (0) - -#define CHECK_ENV(env) \ - if ((env) == nullptr) { \ - return napi_invalid_arg; \ - } - -#define CHECK_ARG(env, arg) \ - RETURN_STATUS_IF_FALSE((env), ((arg) != nullptr), napi_invalid_arg) - -#define CHECK_MAYBE_EMPTY(env, maybe, status) \ - RETURN_STATUS_IF_FALSE((env), !((maybe).IsEmpty()), (status)) - -#define CHECK_MAYBE_NOTHING(env, maybe, status) \ - RETURN_STATUS_IF_FALSE((env), !((maybe).IsNothing()), (status)) - -// NAPI_PREAMBLE is not wrapped in do..while: try_catch must have function scope -#define NAPI_PREAMBLE(env) \ - CHECK_ENV((env)); \ - RETURN_STATUS_IF_FALSE((env), (env)->last_exception.IsEmpty(), \ - napi_pending_exception); \ - napi_clear_last_error((env)); \ - v8impl::TryCatch try_catch((env)) - -#define CHECK_TO_TYPE(env, type, context, result, src, status) \ - do { \ - CHECK_ARG((env), (src)); \ - auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ - CHECK_MAYBE_EMPTY((env), maybe, (status)); \ - (result) = maybe.ToLocalChecked(); \ - } while (0) - -#define CHECK_TO_FUNCTION(env, result, src) \ - do { \ - CHECK_ARG((env), (src)); \ - v8::Local<v8::Value> v8value = v8impl::V8LocalValueFromJsValue((src)); \ - RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), napi_invalid_arg); \ - (result) = v8value.As<v8::Function>(); \ - } while (0) - -#define CHECK_TO_OBJECT(env, context, result, src) \ - CHECK_TO_TYPE((env), Object, (context), (result), (src), napi_object_expected) - -#define CHECK_TO_STRING(env, context, result, src) \ - CHECK_TO_TYPE((env), String, (context), (result), (src), napi_string_expected) - -#define CHECK_TO_NUMBER(env, context, result, src) \ - CHECK_TO_TYPE((env), Number, (context), (result), (src), napi_number_expected) - -#define CHECK_TO_BOOL(env, context, result, src) \ - CHECK_TO_TYPE((env), Boolean, (context), (result), (src), \ - napi_boolean_expected) - -// n-api defines NAPI_AUTO_LENGHTH as the indicator that a string -// is null terminated. For V8 the equivalent is -1. The assert -// validates that our cast of NAPI_AUTO_LENGTH results in -1 as -// needed by V8. -#define CHECK_NEW_FROM_UTF8_LEN(env, result, str, len) \ - do { \ - static_assert(static_cast<int>(NAPI_AUTO_LENGTH) == -1, \ - "Casting NAPI_AUTO_LENGTH to int must result in -1"); \ - RETURN_STATUS_IF_FALSE((env), \ - (len == NAPI_AUTO_LENGTH) || len <= INT_MAX, \ - napi_invalid_arg); \ - auto str_maybe = v8::String::NewFromUtf8( \ - (env)->isolate, (str), v8::NewStringType::kInternalized, \ - static_cast<int>(len)); \ - CHECK_MAYBE_EMPTY((env), str_maybe, napi_generic_failure); \ - (result) = str_maybe.ToLocalChecked(); \ - } while (0) - -#define CHECK_NEW_FROM_UTF8(env, result, str) \ - CHECK_NEW_FROM_UTF8_LEN((env), (result), (str), NAPI_AUTO_LENGTH) - -#define GET_RETURN_STATUS(env) \ - (!try_catch.HasCaught() ? napi_ok \ - : napi_set_last_error((env), napi_pending_exception)) - -#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \ - do { \ - if (!(condition)) { \ - napi_throw_range_error((env), (error), (message)); \ - return napi_set_last_error((env), napi_generic_failure); \ - } \ - } while (0) - -#define CREATE_TYPED_ARRAY( \ - env, type, size_of_element, buffer, byte_offset, length, out) \ - do { \ - if ((size_of_element) > 1) { \ - THROW_RANGE_ERROR_IF_FALSE( \ - (env), (byte_offset) % (size_of_element) == 0, \ - "ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT", \ - "start offset of "#type" should be a multiple of "#size_of_element); \ - } \ - THROW_RANGE_ERROR_IF_FALSE((env), (length) * (size_of_element) + \ - (byte_offset) <= buffer->ByteLength(), \ - "ERR_NAPI_INVALID_TYPEDARRAY_LENGTH", \ - "Invalid typed array length"); \ - (out) = v8::type::New((buffer), (byte_offset), (length)); \ - } while (0) - -#define NAPI_CALL_INTO_MODULE(env, call, handle_exception) \ - do { \ - int open_handle_scopes = (env)->open_handle_scopes; \ - napi_clear_last_error((env)); \ - call; \ - CHECK_EQ((env)->open_handle_scopes, open_handle_scopes); \ - if (!(env)->last_exception.IsEmpty()) { \ - handle_exception( \ - v8::Local<v8::Value>::New((env)->isolate, (env)->last_exception)); \ - (env)->last_exception.Reset(); \ - } \ - } while (0) - -#define NAPI_CALL_INTO_MODULE_THROW(env, call) \ - NAPI_CALL_INTO_MODULE((env), call, (env)->isolate->ThrowException) - -namespace { -namespace v8impl { - -// convert from n-api property attributes to v8::PropertyAttribute -static inline v8::PropertyAttribute V8PropertyAttributesFromDescriptor( - const napi_property_descriptor* descriptor) { - unsigned int attribute_flags = v8::PropertyAttribute::None; - - if (descriptor->getter != nullptr || descriptor->setter != nullptr) { - // The napi_writable attribute is ignored for accessor descriptors, but - // V8 requires the ReadOnly attribute to match nonexistence of a setter. - attribute_flags |= (descriptor->setter == nullptr ? - v8::PropertyAttribute::ReadOnly : v8::PropertyAttribute::None); - } else if ((descriptor->attributes & napi_writable) == 0) { - attribute_flags |= v8::PropertyAttribute::ReadOnly; - } - - if ((descriptor->attributes & napi_enumerable) == 0) { - attribute_flags |= v8::PropertyAttribute::DontEnum; - } - if ((descriptor->attributes & napi_configurable) == 0) { - attribute_flags |= v8::PropertyAttribute::DontDelete; - } - - return static_cast<v8::PropertyAttribute>(attribute_flags); -} - -class HandleScopeWrapper { - public: - explicit HandleScopeWrapper(v8::Isolate* isolate) : scope(isolate) {} - - private: - v8::HandleScope scope; -}; - -// In node v0.10 version of v8, there is no EscapableHandleScope and the -// node v0.10 port use HandleScope::Close(Local<T> v) to mimic the behavior -// of a EscapableHandleScope::Escape(Local<T> v), but it is not the same -// semantics. This is an example of where the api abstraction fail to work -// across different versions. -class EscapableHandleScopeWrapper { - public: - explicit EscapableHandleScopeWrapper(v8::Isolate* isolate) - : scope(isolate), escape_called_(false) {} - bool escape_called() const { - return escape_called_; - } - template <typename T> - v8::Local<T> Escape(v8::Local<T> handle) { - escape_called_ = true; - return scope.Escape(handle); - } - - private: - v8::EscapableHandleScope scope; - bool escape_called_; -}; - -static -napi_handle_scope JsHandleScopeFromV8HandleScope(HandleScopeWrapper* s) { - return reinterpret_cast<napi_handle_scope>(s); -} - -static -HandleScopeWrapper* V8HandleScopeFromJsHandleScope(napi_handle_scope s) { - return reinterpret_cast<HandleScopeWrapper*>(s); -} - -static -napi_escapable_handle_scope JsEscapableHandleScopeFromV8EscapableHandleScope( - EscapableHandleScopeWrapper* s) { - return reinterpret_cast<napi_escapable_handle_scope>(s); -} - -static -EscapableHandleScopeWrapper* -V8EscapableHandleScopeFromJsEscapableHandleScope( - napi_escapable_handle_scope s) { - return reinterpret_cast<EscapableHandleScopeWrapper*>(s); -} - -//=== Conversion between V8 Handles and napi_value ======================== - -// This asserts v8::Local<> will always be implemented with a single -// pointer field so that we can pass it around as a void*. -static_assert(sizeof(v8::Local<v8::Value>) == sizeof(napi_value), - "Cannot convert between v8::Local<v8::Value> and napi_value"); - -static -napi_deferred JsDeferredFromV8Persistent(v8::Persistent<v8::Value>* local) { - return reinterpret_cast<napi_deferred>(local); -} - -static -v8::Persistent<v8::Value>* V8PersistentFromJsDeferred(napi_deferred local) { - return reinterpret_cast<v8::Persistent<v8::Value>*>(local); -} - -static -napi_value JsValueFromV8LocalValue(v8::Local<v8::Value> local) { - return reinterpret_cast<napi_value>(*local); -} - -static -v8::Local<v8::Value> V8LocalValueFromJsValue(napi_value v) { - v8::Local<v8::Value> local; - memcpy(&local, &v, sizeof(v)); - return local; -} - -static inline void trigger_fatal_exception( - napi_env env, v8::Local<v8::Value> local_err) { - v8::TryCatch try_catch(env->isolate); - env->isolate->ThrowException(local_err); - node::FatalException(env->isolate, try_catch); -} - -static inline napi_status V8NameFromPropertyDescriptor(napi_env env, - const napi_property_descriptor* p, - v8::Local<v8::Name>* result) { - if (p->utf8name != nullptr) { - CHECK_NEW_FROM_UTF8(env, *result, p->utf8name); - } else { - v8::Local<v8::Value> property_value = - v8impl::V8LocalValueFromJsValue(p->name); - - RETURN_STATUS_IF_FALSE(env, property_value->IsName(), napi_name_expected); - *result = property_value.As<v8::Name>(); - } - - return napi_ok; -} - -// Adapter for napi_finalize callbacks. -class Finalizer { - protected: - Finalizer(napi_env env, - napi_finalize finalize_callback, - void* finalize_data, - void* finalize_hint) - : _env(env), - _finalize_callback(finalize_callback), - _finalize_data(finalize_data), - _finalize_hint(finalize_hint) { - } - - ~Finalizer() { - } - - public: - static Finalizer* New(napi_env env, - napi_finalize finalize_callback = nullptr, - void* finalize_data = nullptr, - void* finalize_hint = nullptr) { - return new Finalizer( - env, finalize_callback, finalize_data, finalize_hint); - } - - static void Delete(Finalizer* finalizer) { - delete finalizer; - } - - // node::Buffer::FreeCallback - static void FinalizeBufferCallback(char* data, void* hint) { - Finalizer* finalizer = static_cast<Finalizer*>(hint); - if (finalizer->_finalize_callback != nullptr) { - NAPI_CALL_INTO_MODULE_THROW(finalizer->_env, - finalizer->_finalize_callback( - finalizer->_env, - data, - finalizer->_finalize_hint)); - } - - Delete(finalizer); - } - - protected: - napi_env _env; - napi_finalize _finalize_callback; - void* _finalize_data; - void* _finalize_hint; -}; - -// Wrapper around v8::Persistent that implements reference counting. -class Reference : private Finalizer { - private: - Reference(napi_env env, - v8::Local<v8::Value> value, - uint32_t initial_refcount, - bool delete_self, - napi_finalize finalize_callback, - void* finalize_data, - void* finalize_hint) - : Finalizer(env, finalize_callback, finalize_data, finalize_hint), - _persistent(env->isolate, value), - _refcount(initial_refcount), - _delete_self(delete_self) { - if (initial_refcount == 0) { - _persistent.SetWeak( - this, FinalizeCallback, v8::WeakCallbackType::kParameter); - _persistent.MarkIndependent(); - } - } - - ~Reference() { - // The V8 Persistent class currently does not reset in its destructor: - // see NonCopyablePersistentTraits::kResetInDestructor = false. - // (Comments there claim that might change in the future.) - // To avoid memory leaks, it is better to reset at this time, however - // care must be taken to avoid attempting this after the Isolate has - // shut down, for example via a static (atexit) destructor. - _persistent.Reset(); - } - - public: - static Reference* New(napi_env env, - v8::Local<v8::Value> value, - uint32_t initial_refcount, - bool delete_self, - napi_finalize finalize_callback = nullptr, - void* finalize_data = nullptr, - void* finalize_hint = nullptr) { - return new Reference(env, - value, - initial_refcount, - delete_self, - finalize_callback, - finalize_data, - finalize_hint); - } - - static void Delete(Reference* reference) { - delete reference; - } - - uint32_t Ref() { - if (++_refcount == 1) { - _persistent.ClearWeak(); - } - - return _refcount; - } - - uint32_t Unref() { - if (_refcount == 0) { - return 0; - } - if (--_refcount == 0) { - _persistent.SetWeak( - this, FinalizeCallback, v8::WeakCallbackType::kParameter); - _persistent.MarkIndependent(); - } - - return _refcount; - } - - uint32_t RefCount() { - return _refcount; - } - - v8::Local<v8::Value> Get() { - if (_persistent.IsEmpty()) { - return v8::Local<v8::Value>(); - } else { - return v8::Local<v8::Value>::New(_env->isolate, _persistent); - } - } - - private: - static void FinalizeCallback(const v8::WeakCallbackInfo<Reference>& data) { - Reference* reference = data.GetParameter(); - reference->_persistent.Reset(); - - // Check before calling the finalize callback, because the callback might - // delete it. - bool delete_self = reference->_delete_self; - napi_env env = reference->_env; - - if (reference->_finalize_callback != nullptr) { - NAPI_CALL_INTO_MODULE_THROW(env, - reference->_finalize_callback( - reference->_env, - reference->_finalize_data, - reference->_finalize_hint)); - } - - if (delete_self) { - Delete(reference); - } - } - - v8::Persistent<v8::Value> _persistent; - uint32_t _refcount; - bool _delete_self; -}; - -class TryCatch : public v8::TryCatch { - public: - explicit TryCatch(napi_env env) - : v8::TryCatch(env->isolate), _env(env) {} - - ~TryCatch() { - if (HasCaught()) { - _env->last_exception.Reset(_env->isolate, Exception()); - } - } - - private: - napi_env _env; -}; - -//=== Function napi_callback wrapper ================================= - -// Use this data structure to associate callback data with each N-API function -// exposed to JavaScript. The structure is stored in a v8::External which gets -// passed into our callback wrapper. This reduces the performance impact of -// calling through N-API. -// Ref: benchmark/misc/function_call -// Discussion (incl. perf. data): https://github.com/nodejs/node/pull/21072 -struct CallbackBundle { - // Bind the lifecycle of `this` C++ object to a JavaScript object. - // We never delete a CallbackBundle C++ object directly. - void BindLifecycleTo(v8::Isolate* isolate, v8::Local<v8::Value> target) { - handle.Reset(isolate, target); - handle.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter); - } - - napi_env env; // Necessary to invoke C++ NAPI callback - void* cb_data; // The user provided callback data - napi_callback function_or_getter; - napi_callback setter; - node::Persistent<v8::Value> handle; // Die with this JavaScript object - - private: - static void WeakCallback(v8::WeakCallbackInfo<CallbackBundle> const& info) { - // Use the "WeakCallback mechanism" to delete the C++ `bundle` object. - // This will be called when the v8::External containing `this` pointer - // is being GC-ed. - CallbackBundle* bundle = info.GetParameter(); - if (bundle != nullptr) { - delete bundle; - } - } -}; - -// Base class extended by classes that wrap V8 function and property callback -// info. -class CallbackWrapper { - public: - CallbackWrapper(napi_value this_arg, size_t args_length, void* data) - : _this(this_arg), _args_length(args_length), _data(data) {} - - virtual napi_value GetNewTarget() = 0; - virtual void Args(napi_value* buffer, size_t bufferlength) = 0; - virtual void SetReturnValue(napi_value value) = 0; - - napi_value This() { return _this; } - - size_t ArgsLength() { return _args_length; } - - void* Data() { return _data; } - - protected: - const napi_value _this; - const size_t _args_length; - void* _data; -}; - -template <typename Info, napi_callback CallbackBundle::*FunctionField> -class CallbackWrapperBase : public CallbackWrapper { - public: - CallbackWrapperBase(const Info& cbinfo, const size_t args_length) - : CallbackWrapper(JsValueFromV8LocalValue(cbinfo.This()), - args_length, - nullptr), - _cbinfo(cbinfo) { - _bundle = reinterpret_cast<CallbackBundle*>( - v8::Local<v8::External>::Cast(cbinfo.Data())->Value()); - _data = _bundle->cb_data; - } - - napi_value GetNewTarget() override { return nullptr; } - - protected: - void InvokeCallback() { - napi_callback_info cbinfo_wrapper = reinterpret_cast<napi_callback_info>( - static_cast<CallbackWrapper*>(this)); - - // All other pointers we need are stored in `_bundle` - napi_env env = _bundle->env; - napi_callback cb = _bundle->*FunctionField; - - napi_value result; - NAPI_CALL_INTO_MODULE_THROW(env, result = cb(env, cbinfo_wrapper)); - - if (result != nullptr) { - this->SetReturnValue(result); - } - } - - const Info& _cbinfo; - CallbackBundle* _bundle; -}; - -class FunctionCallbackWrapper - : public CallbackWrapperBase<v8::FunctionCallbackInfo<v8::Value>, - &CallbackBundle::function_or_getter> { - public: - static void Invoke(const v8::FunctionCallbackInfo<v8::Value>& info) { - FunctionCallbackWrapper cbwrapper(info); - cbwrapper.InvokeCallback(); - } - - explicit FunctionCallbackWrapper( - const v8::FunctionCallbackInfo<v8::Value>& cbinfo) - : CallbackWrapperBase(cbinfo, cbinfo.Length()) {} - - napi_value GetNewTarget() override { - if (_cbinfo.IsConstructCall()) { - return v8impl::JsValueFromV8LocalValue(_cbinfo.NewTarget()); - } else { - return nullptr; - } - } - - /*virtual*/ - void Args(napi_value* buffer, size_t buffer_length) override { - size_t i = 0; - size_t min = std::min(buffer_length, _args_length); - - for (; i < min; i += 1) { - buffer[i] = v8impl::JsValueFromV8LocalValue(_cbinfo[i]); - } - - if (i < buffer_length) { - napi_value undefined = - v8impl::JsValueFromV8LocalValue(v8::Undefined(_cbinfo.GetIsolate())); - for (; i < buffer_length; i += 1) { - buffer[i] = undefined; - } - } - } - - /*virtual*/ - void SetReturnValue(napi_value value) override { - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - _cbinfo.GetReturnValue().Set(val); - } -}; - -class GetterCallbackWrapper - : public CallbackWrapperBase<v8::PropertyCallbackInfo<v8::Value>, - &CallbackBundle::function_or_getter> { - public: - static void Invoke(v8::Local<v8::Name> property, - const v8::PropertyCallbackInfo<v8::Value>& info) { - GetterCallbackWrapper cbwrapper(info); - cbwrapper.InvokeCallback(); - } - - explicit GetterCallbackWrapper( - const v8::PropertyCallbackInfo<v8::Value>& cbinfo) - : CallbackWrapperBase(cbinfo, 0) {} - - /*virtual*/ - void Args(napi_value* buffer, size_t buffer_length) override { - if (buffer_length > 0) { - napi_value undefined = - v8impl::JsValueFromV8LocalValue(v8::Undefined(_cbinfo.GetIsolate())); - for (size_t i = 0; i < buffer_length; i += 1) { - buffer[i] = undefined; - } - } - } - - /*virtual*/ - void SetReturnValue(napi_value value) override { - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - _cbinfo.GetReturnValue().Set(val); - } -}; - -class SetterCallbackWrapper - : public CallbackWrapperBase<v8::PropertyCallbackInfo<void>, - &CallbackBundle::setter> { - public: - static void Invoke(v8::Local<v8::Name> property, - v8::Local<v8::Value> value, - const v8::PropertyCallbackInfo<void>& info) { - SetterCallbackWrapper cbwrapper(info, value); - cbwrapper.InvokeCallback(); - } - - SetterCallbackWrapper(const v8::PropertyCallbackInfo<void>& cbinfo, - const v8::Local<v8::Value>& value) - : CallbackWrapperBase(cbinfo, 1), _value(value) {} - - /*virtual*/ - void Args(napi_value* buffer, size_t buffer_length) override { - if (buffer_length > 0) { - buffer[0] = v8impl::JsValueFromV8LocalValue(_value); - - if (buffer_length > 1) { - napi_value undefined = v8impl::JsValueFromV8LocalValue( - v8::Undefined(_cbinfo.GetIsolate())); - for (size_t i = 1; i < buffer_length; i += 1) { - buffer[i] = undefined; - } - } - } - } - - /*virtual*/ - void SetReturnValue(napi_value value) override { - // Ignore any value returned from a setter callback. - } - - private: - const v8::Local<v8::Value>& _value; -}; - -// Creates an object to be made available to the static function callback -// wrapper, used to retrieve the native callback function and data pointer. -static -v8::Local<v8::Value> CreateFunctionCallbackData(napi_env env, - napi_callback cb, - void* data) { - CallbackBundle* bundle = new CallbackBundle(); - bundle->function_or_getter = cb; - bundle->cb_data = data; - bundle->env = env; - v8::Local<v8::Value> cbdata = v8::External::New(env->isolate, bundle); - bundle->BindLifecycleTo(env->isolate, cbdata); - - return cbdata; -} - -// Creates an object to be made available to the static getter/setter -// callback wrapper, used to retrieve the native getter/setter callback -// function and data pointer. -static -v8::Local<v8::Value> CreateAccessorCallbackData(napi_env env, - napi_callback getter, - napi_callback setter, - void* data) { - CallbackBundle* bundle = new CallbackBundle(); - bundle->function_or_getter = getter; - bundle->setter = setter; - bundle->cb_data = data; - bundle->env = env; - v8::Local<v8::Value> cbdata = v8::External::New(env->isolate, bundle); - bundle->BindLifecycleTo(env->isolate, cbdata); - - return cbdata; -} - -int kWrapperFields = 3; - -// Pointer used to identify items wrapped by N-API. Used by FindWrapper and -// napi_wrap(). -const char napi_wrap_name[] = "N-API Wrapper"; - -// Search the object's prototype chain for the wrapper object. Usually the -// wrapper would be the first in the chain, but it is OK for other objects to -// be inserted in the prototype chain. -static -bool FindWrapper(v8::Local<v8::Object> obj, - v8::Local<v8::Object>* result = nullptr, - v8::Local<v8::Object>* parent = nullptr) { - v8::Local<v8::Object> wrapper = obj; - - do { - v8::Local<v8::Value> proto = wrapper->GetPrototype(); - if (proto.IsEmpty() || !proto->IsObject()) { - return false; - } - if (parent != nullptr) { - *parent = wrapper; - } - wrapper = proto.As<v8::Object>(); - if (wrapper->InternalFieldCount() == kWrapperFields) { - v8::Local<v8::Value> external = wrapper->GetInternalField(1); - if (external->IsExternal() && - external.As<v8::External>()->Value() == v8impl::napi_wrap_name) { - break; - } - } - } while (true); - - if (result != nullptr) { - *result = wrapper; - } - return true; -} - -static void DeleteEnv(napi_env env, void* data, void* hint) { - delete env; -} - -static -napi_env GetEnv(v8::Local<v8::Context> context) { - napi_env result; - - auto isolate = context->GetIsolate(); - auto global = context->Global(); - - // In the case of the string for which we grab the private and the value of - // the private on the global object we can call .ToLocalChecked() directly - // because we need to stop hard if either of them is empty. - // - // Re https://github.com/nodejs/node/pull/14217#discussion_r128775149 - auto key = v8::Private::ForApi(isolate, - v8::String::NewFromOneByte(isolate, - reinterpret_cast<const uint8_t*>("N-API Environment"), - v8::NewStringType::kInternalized).ToLocalChecked()); - auto value = global->GetPrivate(context, key).ToLocalChecked(); - - if (value->IsExternal()) { - result = static_cast<napi_env>(value.As<v8::External>()->Value()); - } else { - result = new napi_env__(isolate); - auto external = v8::External::New(isolate, result); - - // We must also stop hard if the result of assigning the env to the global - // is either nothing or false. - CHECK(global->SetPrivate(context, key, external).FromJust()); - - // Create a self-destructing reference to external that will get rid of the - // napi_env when external goes out of scope. - Reference::New(result, external, 0, true, DeleteEnv, nullptr, nullptr); - } - - return result; -} - -static -napi_status Unwrap(napi_env env, - napi_value js_object, - void** result, - v8::Local<v8::Object>* wrapper, - v8::Local<v8::Object>* parent = nullptr) { - CHECK_ARG(env, js_object); - CHECK_ARG(env, result); - - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(js_object); - RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg); - v8::Local<v8::Object> obj = value.As<v8::Object>(); - - RETURN_STATUS_IF_FALSE( - env, v8impl::FindWrapper(obj, wrapper, parent), napi_invalid_arg); - - v8::Local<v8::Value> unwrappedValue = (*wrapper)->GetInternalField(0); - RETURN_STATUS_IF_FALSE(env, unwrappedValue->IsExternal(), napi_invalid_arg); - - *result = unwrappedValue.As<v8::External>()->Value(); - - return napi_ok; -} - -static -napi_status ConcludeDeferred(napi_env env, - napi_deferred deferred, - napi_value result, - bool is_resolved) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Local<v8::Context> context = env->isolate->GetCurrentContext(); - v8::Persistent<v8::Value>* deferred_ref = - V8PersistentFromJsDeferred(deferred); - v8::Local<v8::Value> v8_deferred = - v8::Local<v8::Value>::New(env->isolate, *deferred_ref); - - auto v8_resolver = v8::Local<v8::Promise::Resolver>::Cast(v8_deferred); - - v8::Maybe<bool> success = is_resolved ? - v8_resolver->Resolve(context, v8impl::V8LocalValueFromJsValue(result)) : - v8_resolver->Reject(context, v8impl::V8LocalValueFromJsValue(result)); - - deferred_ref->Reset(); - delete deferred_ref; - - RETURN_STATUS_IF_FALSE(env, success.FromMaybe(false), napi_generic_failure); - - return GET_RETURN_STATUS(env); -} - -} // end of namespace v8impl - -// Intercepts the Node-V8 module registration callback. Converts parameters -// to NAPI equivalents and then calls the registration callback specified -// by the NAPI module. -void napi_module_register_cb(v8::Local<v8::Object> exports, - v8::Local<v8::Value> module, - v8::Local<v8::Context> context, - void* priv) { - napi_module* mod = static_cast<napi_module*>(priv); - - // Create a new napi_env for this module or reference one if a pre-existing - // one is found. - napi_env env = v8impl::GetEnv(context); - - napi_value _exports; - NAPI_CALL_INTO_MODULE_THROW(env, - _exports = mod->nm_register_func(env, - v8impl::JsValueFromV8LocalValue(exports))); - - // If register function returned a non-null exports object different from - // the exports object we passed it, set that as the "exports" property of - // the module. - if (_exports != nullptr && - _exports != v8impl::JsValueFromV8LocalValue(exports)) { - napi_value _module = v8impl::JsValueFromV8LocalValue(module); - napi_set_named_property(env, _module, "exports", _exports); - } -} - -} // end of anonymous namespace - -// Registers a NAPI module. -void napi_module_register(napi_module* mod) { - node::node_module* nm = new node::node_module { - NODE_MODULE_VERSION, - mod->nm_flags, - nullptr, - mod->nm_filename, - nullptr, - napi_module_register_cb, - mod->nm_modname, - mod, // priv - nullptr, - }; - node::node_module_register(nm); -} - -// Warning: Keep in-sync with napi_status enum -static -const char* error_messages[] = {nullptr, - "Invalid argument", - "An object was expected", - "A string was expected", - "A string or symbol was expected", - "A function was expected", - "A number was expected", - "A boolean was expected", - "An array was expected", - "Unknown failure", - "An exception is pending", - "The async work item was cancelled", - "napi_escape_handle already called on scope"}; - -static inline napi_status napi_clear_last_error(napi_env env) { - env->last_error.error_code = napi_ok; - - // TODO(boingoing): Should this be a callback? - env->last_error.engine_error_code = 0; - env->last_error.engine_reserved = nullptr; - return napi_ok; -} - -static inline -napi_status napi_set_last_error(napi_env env, napi_status error_code, - uint32_t engine_error_code, - void* engine_reserved) { - env->last_error.error_code = error_code; - env->last_error.engine_error_code = engine_error_code; - env->last_error.engine_reserved = engine_reserved; - return error_code; -} - -napi_status napi_get_last_error_info(napi_env env, - const napi_extended_error_info** result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - // you must update this assert to reference the last message - // in the napi_status enum each time a new error message is added. - // We don't have a napi_status_last as this would result in an ABI - // change each time a message was added. - static_assert( - node::arraysize(error_messages) == napi_escape_called_twice + 1, - "Count of error messages must match count of error values"); - CHECK_LE(env->last_error.error_code, napi_escape_called_twice); - - // Wait until someone requests the last error information to fetch the error - // message string - env->last_error.error_message = - error_messages[env->last_error.error_code]; - - *result = &(env->last_error); - return napi_ok; -} - -napi_status napi_fatal_exception(napi_env env, napi_value err) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, err); - - v8::Local<v8::Value> local_err = v8impl::V8LocalValueFromJsValue(err); - v8impl::trigger_fatal_exception(env, local_err); - - return napi_clear_last_error(env); -} - -NAPI_NO_RETURN void napi_fatal_error(const char* location, - size_t location_len, - const char* message, - size_t message_len) { - std::string location_string; - std::string message_string; - - if (location_len != NAPI_AUTO_LENGTH) { - location_string.assign( - const_cast<char*>(location), location_len); - } else { - location_string.assign( - const_cast<char*>(location), strlen(location)); - } - - if (message_len != NAPI_AUTO_LENGTH) { - message_string.assign( - const_cast<char*>(message), message_len); - } else { - message_string.assign( - const_cast<char*>(message), strlen(message)); - } - - node::FatalError(location_string.c_str(), message_string.c_str()); -} - -napi_status napi_create_function(napi_env env, - const char* utf8name, - size_t length, - napi_callback cb, - void* callback_data, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - CHECK_ARG(env, cb); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Function> return_value; - v8::EscapableHandleScope scope(isolate); - v8::Local<v8::Value> cbdata = - v8impl::CreateFunctionCallbackData(env, cb, callback_data); - - RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); - - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::MaybeLocal<v8::Function> maybe_function = - v8::Function::New(context, - v8impl::FunctionCallbackWrapper::Invoke, - cbdata); - CHECK_MAYBE_EMPTY(env, maybe_function, napi_generic_failure); - - return_value = scope.Escape(maybe_function.ToLocalChecked()); - - if (utf8name != nullptr) { - v8::Local<v8::String> name_string; - CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); - return_value->SetName(name_string); - } - - *result = v8impl::JsValueFromV8LocalValue(return_value); - - return GET_RETURN_STATUS(env); -} - -napi_status napi_define_class(napi_env env, - const char* utf8name, - size_t length, - napi_callback constructor, - void* callback_data, - size_t property_count, - const napi_property_descriptor* properties, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - CHECK_ARG(env, constructor); - - v8::Isolate* isolate = env->isolate; - - v8::EscapableHandleScope scope(isolate); - v8::Local<v8::Value> cbdata = - v8impl::CreateFunctionCallbackData(env, constructor, callback_data); - - RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); - - v8::Local<v8::FunctionTemplate> tpl = v8::FunctionTemplate::New( - isolate, v8impl::FunctionCallbackWrapper::Invoke, cbdata); - - v8::Local<v8::String> name_string; - CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); - tpl->SetClassName(name_string); - - size_t static_property_count = 0; - for (size_t i = 0; i < property_count; i++) { - const napi_property_descriptor* p = properties + i; - - if ((p->attributes & napi_static) != 0) { - // Static properties are handled separately below. - static_property_count++; - continue; - } - - v8::Local<v8::Name> property_name; - napi_status status = - v8impl::V8NameFromPropertyDescriptor(env, p, &property_name); - - if (status != napi_ok) { - return napi_set_last_error(env, status); - } - - v8::PropertyAttribute attributes = - v8impl::V8PropertyAttributesFromDescriptor(p); - - // This code is similar to that in napi_define_properties(); the - // difference is it applies to a template instead of an object. - if (p->getter != nullptr || p->setter != nullptr) { - v8::Local<v8::Value> cbdata = v8impl::CreateAccessorCallbackData( - env, p->getter, p->setter, p->data); - - tpl->PrototypeTemplate()->SetAccessor( - property_name, - p->getter ? v8impl::GetterCallbackWrapper::Invoke : nullptr, - p->setter ? v8impl::SetterCallbackWrapper::Invoke : nullptr, - cbdata, - v8::AccessControl::DEFAULT, - attributes); - } else if (p->method != nullptr) { - v8::Local<v8::Value> cbdata = - v8impl::CreateFunctionCallbackData(env, p->method, p->data); - - RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); - - v8::Local<v8::FunctionTemplate> t = - v8::FunctionTemplate::New(isolate, - v8impl::FunctionCallbackWrapper::Invoke, - cbdata, - v8::Signature::New(isolate, tpl)); - - tpl->PrototypeTemplate()->Set(property_name, t, attributes); - } else { - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(p->value); - tpl->PrototypeTemplate()->Set(property_name, value, attributes); - } - } - - *result = v8impl::JsValueFromV8LocalValue(scope.Escape(tpl->GetFunction())); - - if (static_property_count > 0) { - std::vector<napi_property_descriptor> static_descriptors; - static_descriptors.reserve(static_property_count); - - for (size_t i = 0; i < property_count; i++) { - const napi_property_descriptor* p = properties + i; - if ((p->attributes & napi_static) != 0) { - static_descriptors.push_back(*p); - } - } - - napi_status status = - napi_define_properties(env, - *result, - static_descriptors.size(), - static_descriptors.data()); - if (status != napi_ok) return status; - } - - return GET_RETURN_STATUS(env); -} - -napi_status napi_get_property_names(napi_env env, - napi_value object, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - CHECK_TO_OBJECT(env, context, obj, object); - - auto maybe_propertynames = obj->GetPropertyNames(context); - - CHECK_MAYBE_EMPTY(env, maybe_propertynames, napi_generic_failure); - - *result = v8impl::JsValueFromV8LocalValue( - maybe_propertynames.ToLocalChecked()); - return GET_RETURN_STATUS(env); -} - -napi_status napi_set_property(napi_env env, - napi_value object, - napi_value key, - napi_value value) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, key); - CHECK_ARG(env, value); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key); - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - - v8::Maybe<bool> set_maybe = obj->Set(context, k, val); - - RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure); - return GET_RETURN_STATUS(env); -} - -napi_status napi_has_property(napi_env env, - napi_value object, - napi_value key, - bool* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - CHECK_ARG(env, key); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key); - v8::Maybe<bool> has_maybe = obj->Has(context, k); - - CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure); - - *result = has_maybe.FromMaybe(false); - return GET_RETURN_STATUS(env); -} - -napi_status napi_get_property(napi_env env, - napi_value object, - napi_value key, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, key); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - auto get_maybe = obj->Get(context, k); - - CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure); - - v8::Local<v8::Value> val = get_maybe.ToLocalChecked(); - *result = v8impl::JsValueFromV8LocalValue(val); - return GET_RETURN_STATUS(env); -} - -napi_status napi_delete_property(napi_env env, - napi_value object, - napi_value key, - bool* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, key); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - v8::Maybe<bool> delete_maybe = obj->Delete(context, k); - CHECK_MAYBE_NOTHING(env, delete_maybe, napi_generic_failure); - - if (result != NULL) - *result = delete_maybe.FromMaybe(false); - - return GET_RETURN_STATUS(env); -} - -napi_status napi_has_own_property(napi_env env, - napi_value object, - napi_value key, - bool* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, key); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - v8::Local<v8::Value> k = v8impl::V8LocalValueFromJsValue(key); - RETURN_STATUS_IF_FALSE(env, k->IsName(), napi_name_expected); - v8::Maybe<bool> has_maybe = obj->HasOwnProperty(context, k.As<v8::Name>()); - CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure); - *result = has_maybe.FromMaybe(false); - - return GET_RETURN_STATUS(env); -} - -napi_status napi_set_named_property(napi_env env, - napi_value object, - const char* utf8name, - napi_value value) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, value); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - v8::Local<v8::Name> key; - CHECK_NEW_FROM_UTF8(env, key, utf8name); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - - v8::Maybe<bool> set_maybe = obj->Set(context, key, val); - - RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure); - return GET_RETURN_STATUS(env); -} - -napi_status napi_has_named_property(napi_env env, - napi_value object, - const char* utf8name, - bool* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - v8::Local<v8::Name> key; - CHECK_NEW_FROM_UTF8(env, key, utf8name); - - v8::Maybe<bool> has_maybe = obj->Has(context, key); - - CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure); - - *result = has_maybe.FromMaybe(false); - return GET_RETURN_STATUS(env); -} - -napi_status napi_get_named_property(napi_env env, - napi_value object, - const char* utf8name, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - v8::Local<v8::Name> key; - CHECK_NEW_FROM_UTF8(env, key, utf8name); - - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - auto get_maybe = obj->Get(context, key); - - CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure); - - v8::Local<v8::Value> val = get_maybe.ToLocalChecked(); - *result = v8impl::JsValueFromV8LocalValue(val); - return GET_RETURN_STATUS(env); -} - -napi_status napi_set_element(napi_env env, - napi_value object, - uint32_t index, - napi_value value) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, value); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - auto set_maybe = obj->Set(context, index, val); - - RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure); - - return GET_RETURN_STATUS(env); -} - -napi_status napi_has_element(napi_env env, - napi_value object, - uint32_t index, - bool* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - v8::Maybe<bool> has_maybe = obj->Has(context, index); - - CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure); - - *result = has_maybe.FromMaybe(false); - return GET_RETURN_STATUS(env); -} - -napi_status napi_get_element(napi_env env, - napi_value object, - uint32_t index, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - - auto get_maybe = obj->Get(context, index); - - CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure); - - *result = v8impl::JsValueFromV8LocalValue(get_maybe.ToLocalChecked()); - return GET_RETURN_STATUS(env); -} - -napi_status napi_delete_element(napi_env env, - napi_value object, - uint32_t index, - bool* result) { - NAPI_PREAMBLE(env); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - - CHECK_TO_OBJECT(env, context, obj, object); - v8::Maybe<bool> delete_maybe = obj->Delete(context, index); - CHECK_MAYBE_NOTHING(env, delete_maybe, napi_generic_failure); - - if (result != NULL) - *result = delete_maybe.FromMaybe(false); - - return GET_RETURN_STATUS(env); -} - -napi_status napi_define_properties(napi_env env, - napi_value object, - size_t property_count, - const napi_property_descriptor* properties) { - NAPI_PREAMBLE(env); - if (property_count > 0) { - CHECK_ARG(env, properties); - } - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - v8::Local<v8::Object> obj; - CHECK_TO_OBJECT(env, context, obj, object); - - for (size_t i = 0; i < property_count; i++) { - const napi_property_descriptor* p = &properties[i]; - - v8::Local<v8::Name> property_name; - napi_status status = - v8impl::V8NameFromPropertyDescriptor(env, p, &property_name); - - if (status != napi_ok) { - return napi_set_last_error(env, status); - } - - v8::PropertyAttribute attributes = - v8impl::V8PropertyAttributesFromDescriptor(p); - - if (p->getter != nullptr || p->setter != nullptr) { - v8::Local<v8::Value> cbdata = v8impl::CreateAccessorCallbackData( - env, - p->getter, - p->setter, - p->data); - - auto set_maybe = obj->SetAccessor( - context, - property_name, - p->getter ? v8impl::GetterCallbackWrapper::Invoke : nullptr, - p->setter ? v8impl::SetterCallbackWrapper::Invoke : nullptr, - cbdata, - v8::AccessControl::DEFAULT, - attributes); - - if (!set_maybe.FromMaybe(false)) { - return napi_set_last_error(env, napi_invalid_arg); - } - } else if (p->method != nullptr) { - v8::Local<v8::Value> cbdata = - v8impl::CreateFunctionCallbackData(env, p->method, p->data); - - CHECK_MAYBE_EMPTY(env, cbdata, napi_generic_failure); - - v8::MaybeLocal<v8::Function> maybe_fn = - v8::Function::New(context, - v8impl::FunctionCallbackWrapper::Invoke, - cbdata); - - CHECK_MAYBE_EMPTY(env, maybe_fn, napi_generic_failure); - - auto define_maybe = obj->DefineOwnProperty( - context, property_name, maybe_fn.ToLocalChecked(), attributes); - - if (!define_maybe.FromMaybe(false)) { - return napi_set_last_error(env, napi_generic_failure); - } - } else { - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(p->value); - - auto define_maybe = - obj->DefineOwnProperty(context, property_name, value, attributes); - - if (!define_maybe.FromMaybe(false)) { - return napi_set_last_error(env, napi_invalid_arg); - } - } - } - - return GET_RETURN_STATUS(env); -} - -napi_status napi_is_array(napi_env env, napi_value value, bool* result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - - *result = val->IsArray(); - return napi_clear_last_error(env); -} - -napi_status napi_get_array_length(napi_env env, - napi_value value, - uint32_t* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - RETURN_STATUS_IF_FALSE(env, val->IsArray(), napi_array_expected); - - v8::Local<v8::Array> arr = val.As<v8::Array>(); - *result = arr->Length(); - - return GET_RETURN_STATUS(env); -} - -napi_status napi_strict_equals(napi_env env, - napi_value lhs, - napi_value rhs, - bool* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, lhs); - CHECK_ARG(env, rhs); - CHECK_ARG(env, result); - - v8::Local<v8::Value> a = v8impl::V8LocalValueFromJsValue(lhs); - v8::Local<v8::Value> b = v8impl::V8LocalValueFromJsValue(rhs); - - *result = a->StrictEquals(b); - return GET_RETURN_STATUS(env); -} - -napi_status napi_get_prototype(napi_env env, - napi_value object, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - v8::Local<v8::Object> obj; - CHECK_TO_OBJECT(env, context, obj, object); - - v8::Local<v8::Value> val = obj->GetPrototype(); - *result = v8impl::JsValueFromV8LocalValue(val); - return GET_RETURN_STATUS(env); -} - -napi_status napi_create_object(napi_env env, napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Object::New(env->isolate)); - - return napi_clear_last_error(env); -} - -napi_status napi_create_array(napi_env env, napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Array::New(env->isolate)); - - return napi_clear_last_error(env); -} - -napi_status napi_create_array_with_length(napi_env env, - size_t length, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Array::New(env->isolate, length)); - - return napi_clear_last_error(env); -} - -napi_status napi_create_string_latin1(napi_env env, - const char* str, - size_t length, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - auto isolate = env->isolate; - auto str_maybe = - v8::String::NewFromOneByte(isolate, - reinterpret_cast<const uint8_t*>(str), - v8::NewStringType::kInternalized, - length); - CHECK_MAYBE_EMPTY(env, str_maybe, napi_generic_failure); - - *result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked()); - return napi_clear_last_error(env); -} - -napi_status napi_create_string_utf8(napi_env env, - const char* str, - size_t length, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - v8::Local<v8::String> s; - CHECK_NEW_FROM_UTF8_LEN(env, s, str, length); - - *result = v8impl::JsValueFromV8LocalValue(s); - return napi_clear_last_error(env); -} - -napi_status napi_create_string_utf16(napi_env env, - const char16_t* str, - size_t length, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - auto isolate = env->isolate; - auto str_maybe = - v8::String::NewFromTwoByte(isolate, - reinterpret_cast<const uint16_t*>(str), - v8::NewStringType::kInternalized, - length); - CHECK_MAYBE_EMPTY(env, str_maybe, napi_generic_failure); - - *result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked()); - return napi_clear_last_error(env); -} - -napi_status napi_create_double(napi_env env, - double value, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Number::New(env->isolate, value)); - - return napi_clear_last_error(env); -} - -napi_status napi_create_int32(napi_env env, - int32_t value, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Integer::New(env->isolate, value)); - - return napi_clear_last_error(env); -} - -napi_status napi_create_uint32(napi_env env, - uint32_t value, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Integer::NewFromUnsigned(env->isolate, value)); - - return napi_clear_last_error(env); -} - -napi_status napi_create_int64(napi_env env, - int64_t value, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Number::New(env->isolate, static_cast<double>(value))); - - return napi_clear_last_error(env); -} - -napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - - if (value) { - *result = v8impl::JsValueFromV8LocalValue(v8::True(isolate)); - } else { - *result = v8impl::JsValueFromV8LocalValue(v8::False(isolate)); - } - - return napi_clear_last_error(env); -} - -napi_status napi_create_symbol(napi_env env, - napi_value description, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - - if (description == nullptr) { - *result = v8impl::JsValueFromV8LocalValue(v8::Symbol::New(isolate)); - } else { - v8::Local<v8::Value> desc = v8impl::V8LocalValueFromJsValue(description); - RETURN_STATUS_IF_FALSE(env, desc->IsString(), napi_string_expected); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Symbol::New(isolate, desc.As<v8::String>())); - } - - return napi_clear_last_error(env); -} - -static napi_status set_error_code(napi_env env, - v8::Local<v8::Value> error, - napi_value code, - const char* code_cstring) { - if ((code != nullptr) || (code_cstring != nullptr)) { - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> err_object = error.As<v8::Object>(); - - v8::Local<v8::Value> code_value = v8impl::V8LocalValueFromJsValue(code); - if (code != nullptr) { - code_value = v8impl::V8LocalValueFromJsValue(code); - RETURN_STATUS_IF_FALSE(env, code_value->IsString(), napi_string_expected); - } else { - CHECK_NEW_FROM_UTF8(env, code_value, code_cstring); - } - - v8::Local<v8::Name> code_key; - CHECK_NEW_FROM_UTF8(env, code_key, "code"); - - v8::Maybe<bool> set_maybe = err_object->Set(context, code_key, code_value); - RETURN_STATUS_IF_FALSE(env, - set_maybe.FromMaybe(false), - napi_generic_failure); - - // now update the name to be "name [code]" where name is the - // original name and code is the code associated with the Error - v8::Local<v8::String> name_string; - CHECK_NEW_FROM_UTF8(env, name_string, ""); - v8::Local<v8::Name> name_key; - CHECK_NEW_FROM_UTF8(env, name_key, "name"); - - auto maybe_name = err_object->Get(context, name_key); - if (!maybe_name.IsEmpty()) { - v8::Local<v8::Value> name = maybe_name.ToLocalChecked(); - if (name->IsString()) { - name_string = v8::String::Concat(name_string, name.As<v8::String>()); - } - } - name_string = v8::String::Concat(name_string, - FIXED_ONE_BYTE_STRING(isolate, " [")); - name_string = v8::String::Concat(name_string, code_value.As<v8::String>()); - name_string = v8::String::Concat(name_string, - FIXED_ONE_BYTE_STRING(isolate, "]")); - - set_maybe = err_object->Set(context, name_key, name_string); - RETURN_STATUS_IF_FALSE(env, - set_maybe.FromMaybe(false), - napi_generic_failure); - } - return napi_ok; -} - -napi_status napi_create_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, msg); - CHECK_ARG(env, result); - - v8::Local<v8::Value> message_value = v8impl::V8LocalValueFromJsValue(msg); - RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); - - v8::Local<v8::Value> error_obj = - v8::Exception::Error(message_value.As<v8::String>()); - napi_status status = set_error_code(env, error_obj, code, nullptr); - if (status != napi_ok) return status; - - *result = v8impl::JsValueFromV8LocalValue(error_obj); - - return napi_clear_last_error(env); -} - -napi_status napi_create_type_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, msg); - CHECK_ARG(env, result); - - v8::Local<v8::Value> message_value = v8impl::V8LocalValueFromJsValue(msg); - RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); - - v8::Local<v8::Value> error_obj = - v8::Exception::TypeError(message_value.As<v8::String>()); - napi_status status = set_error_code(env, error_obj, code, nullptr); - if (status != napi_ok) return status; - - *result = v8impl::JsValueFromV8LocalValue(error_obj); - - return napi_clear_last_error(env); -} - -napi_status napi_create_range_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, msg); - CHECK_ARG(env, result); - - v8::Local<v8::Value> message_value = v8impl::V8LocalValueFromJsValue(msg); - RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); - - v8::Local<v8::Value> error_obj = - v8::Exception::RangeError(message_value.As<v8::String>()); - napi_status status = set_error_code(env, error_obj, code, nullptr); - if (status != napi_ok) return status; - - *result = v8impl::JsValueFromV8LocalValue(error_obj); - - return napi_clear_last_error(env); -} - -napi_status napi_typeof(napi_env env, - napi_value value, - napi_valuetype* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> v = v8impl::V8LocalValueFromJsValue(value); - - if (v->IsNumber()) { - *result = napi_number; - } else if (v->IsString()) { - *result = napi_string; - } else if (v->IsFunction()) { - // This test has to come before IsObject because IsFunction - // implies IsObject - *result = napi_function; - } else if (v->IsExternal()) { - // This test has to come before IsObject because IsExternal - // implies IsObject - *result = napi_external; - } else if (v->IsObject()) { - *result = napi_object; - } else if (v->IsBoolean()) { - *result = napi_boolean; - } else if (v->IsUndefined()) { - *result = napi_undefined; - } else if (v->IsSymbol()) { - *result = napi_symbol; - } else if (v->IsNull()) { - *result = napi_null; - } else { - // Should not get here unless V8 has added some new kind of value. - return napi_set_last_error(env, napi_invalid_arg); - } - - return napi_clear_last_error(env); -} - -napi_status napi_get_undefined(napi_env env, napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Undefined(env->isolate)); - - return napi_clear_last_error(env); -} - -napi_status napi_get_null(napi_env env, napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsValueFromV8LocalValue( - v8::Null(env->isolate)); - - return napi_clear_last_error(env); -} - -// Gets all callback info in a single call. (Ugly, but faster.) -napi_status napi_get_cb_info( - napi_env env, // [in] NAPI environment handle - napi_callback_info cbinfo, // [in] Opaque callback-info handle - size_t* argc, // [in-out] Specifies the size of the provided argv array - // and receives the actual count of args. - napi_value* argv, // [out] Array of values - napi_value* this_arg, // [out] Receives the JS 'this' arg for the call - void** data) { // [out] Receives the data pointer for the callback. - CHECK_ENV(env); - CHECK_ARG(env, cbinfo); - - v8impl::CallbackWrapper* info = - reinterpret_cast<v8impl::CallbackWrapper*>(cbinfo); - - if (argv != nullptr) { - CHECK_ARG(env, argc); - info->Args(argv, *argc); - } - if (argc != nullptr) { - *argc = info->ArgsLength(); - } - if (this_arg != nullptr) { - *this_arg = info->This(); - } - if (data != nullptr) { - *data = info->Data(); - } - - return napi_clear_last_error(env); -} - -napi_status napi_get_new_target(napi_env env, - napi_callback_info cbinfo, - napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, cbinfo); - CHECK_ARG(env, result); - - v8impl::CallbackWrapper* info = - reinterpret_cast<v8impl::CallbackWrapper*>(cbinfo); - - *result = info->GetNewTarget(); - return napi_clear_last_error(env); -} - -napi_status napi_call_function(napi_env env, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, recv); - if (argc > 0) { - CHECK_ARG(env, argv); - } - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - v8::Local<v8::Value> v8recv = v8impl::V8LocalValueFromJsValue(recv); - - v8::Local<v8::Function> v8func; - CHECK_TO_FUNCTION(env, v8func, func); - - auto maybe = v8func->Call(context, v8recv, argc, - reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv))); - - if (try_catch.HasCaught()) { - return napi_set_last_error(env, napi_pending_exception); - } else { - if (result != nullptr) { - CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); - *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); - } - return napi_clear_last_error(env); - } -} - -napi_status napi_get_global(napi_env env, napi_value* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - // TODO(ianhall): what if we need the global object from a different - // context in the same isolate? - // Should napi_env be the current context rather than the current isolate? - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - *result = v8impl::JsValueFromV8LocalValue(context->Global()); - - return napi_clear_last_error(env); -} - -napi_status napi_throw(napi_env env, napi_value error) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, error); - - v8::Isolate* isolate = env->isolate; - - isolate->ThrowException(v8impl::V8LocalValueFromJsValue(error)); - // any VM calls after this point and before returning - // to the javascript invoker will fail - return napi_clear_last_error(env); -} - -napi_status napi_throw_error(napi_env env, - const char* code, - const char* msg) { - NAPI_PREAMBLE(env); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::String> str; - CHECK_NEW_FROM_UTF8(env, str, msg); - - v8::Local<v8::Value> error_obj = v8::Exception::Error(str); - napi_status status = set_error_code(env, error_obj, nullptr, code); - if (status != napi_ok) return status; - - isolate->ThrowException(error_obj); - // any VM calls after this point and before returning - // to the javascript invoker will fail - return napi_clear_last_error(env); -} - -napi_status napi_throw_type_error(napi_env env, - const char* code, - const char* msg) { - NAPI_PREAMBLE(env); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::String> str; - CHECK_NEW_FROM_UTF8(env, str, msg); - - v8::Local<v8::Value> error_obj = v8::Exception::TypeError(str); - napi_status status = set_error_code(env, error_obj, nullptr, code); - if (status != napi_ok) return status; - - isolate->ThrowException(error_obj); - // any VM calls after this point and before returning - // to the javascript invoker will fail - return napi_clear_last_error(env); -} - -napi_status napi_throw_range_error(napi_env env, - const char* code, - const char* msg) { - NAPI_PREAMBLE(env); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::String> str; - CHECK_NEW_FROM_UTF8(env, str, msg); - - v8::Local<v8::Value> error_obj = v8::Exception::RangeError(str); - napi_status status = set_error_code(env, error_obj, nullptr, code); - if (status != napi_ok) return status; - - isolate->ThrowException(error_obj); - // any VM calls after this point and before returning - // to the javascript invoker will fail - return napi_clear_last_error(env); -} - -napi_status napi_is_error(napi_env env, napi_value value, bool* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot - // throw JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - *result = val->IsNativeError(); - - return napi_clear_last_error(env); -} - -napi_status napi_get_value_double(napi_env env, - napi_value value, - double* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected); - - *result = val.As<v8::Number>()->Value(); - - return napi_clear_last_error(env); -} - -napi_status napi_get_value_int32(napi_env env, - napi_value value, - int32_t* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - - if (val->IsInt32()) { - *result = val.As<v8::Int32>()->Value(); - } else { - RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected); - - // Empty context: https://github.com/nodejs/node/issues/14379 - v8::Local<v8::Context> context; - *result = val->Int32Value(context).FromJust(); - } - - return napi_clear_last_error(env); -} - -napi_status napi_get_value_uint32(napi_env env, - napi_value value, - uint32_t* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - - if (val->IsUint32()) { - *result = val.As<v8::Uint32>()->Value(); - } else { - RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected); - - // Empty context: https://github.com/nodejs/node/issues/14379 - v8::Local<v8::Context> context; - *result = val->Uint32Value(context).FromJust(); - } - - return napi_clear_last_error(env); -} - -napi_status napi_get_value_int64(napi_env env, - napi_value value, - int64_t* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - - // This is still a fast path very likely to be taken. - if (val->IsInt32()) { - *result = val.As<v8::Int32>()->Value(); - return napi_clear_last_error(env); - } - - RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected); - - // v8::Value::IntegerValue() converts NaN to INT64_MIN, inconsistent with - // v8::Value::Int32Value() that converts NaN to 0. So special-case NaN here. - double doubleValue = val.As<v8::Number>()->Value(); - if (std::isnan(doubleValue)) { - *result = 0; - } else { - // Empty context: https://github.com/nodejs/node/issues/14379 - v8::Local<v8::Context> context; - *result = val->IntegerValue(context).FromJust(); - } - - return napi_clear_last_error(env); -} - -napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - RETURN_STATUS_IF_FALSE(env, val->IsBoolean(), napi_boolean_expected); - - *result = val.As<v8::Boolean>()->Value(); - - return napi_clear_last_error(env); -} - -// Copies a JavaScript string into a LATIN-1 string buffer. The result is the -// number of bytes (excluding the null terminator) copied into buf. -// A sufficient buffer size should be greater than the length of string, -// reserving space for null terminator. -// If bufsize is insufficient, the string will be truncated and null terminated. -// If buf is NULL, this method returns the length of the string (in bytes) -// via the result parameter. -// The result argument is optional unless buf is NULL. -napi_status napi_get_value_string_latin1(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected); - - if (!buf) { - CHECK_ARG(env, result); - *result = val.As<v8::String>()->Length(); - } else { - int copied = val.As<v8::String>()->WriteOneByte( - reinterpret_cast<uint8_t*>(buf), 0, bufsize - 1, - v8::String::NO_NULL_TERMINATION); - - buf[copied] = '\0'; - if (result != nullptr) { - *result = copied; - } - } - - return napi_clear_last_error(env); -} - -// Copies a JavaScript string into a UTF-8 string buffer. The result is the -// number of bytes (excluding the null terminator) copied into buf. -// A sufficient buffer size should be greater than the length of string, -// reserving space for null terminator. -// If bufsize is insufficient, the string will be truncated and null terminated. -// If buf is NULL, this method returns the length of the string (in bytes) -// via the result parameter. -// The result argument is optional unless buf is NULL. -napi_status napi_get_value_string_utf8(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected); - - if (!buf) { - CHECK_ARG(env, result); - *result = val.As<v8::String>()->Utf8Length(); - } else { - int copied = val.As<v8::String>()->WriteUtf8( - buf, bufsize - 1, nullptr, v8::String::REPLACE_INVALID_UTF8 | - v8::String::NO_NULL_TERMINATION); - - buf[copied] = '\0'; - if (result != nullptr) { - *result = copied; - } - } - - return napi_clear_last_error(env); -} - -// Copies a JavaScript string into a UTF-16 string buffer. The result is the -// number of 2-byte code units (excluding the null terminator) copied into buf. -// A sufficient buffer size should be greater than the length of string, -// reserving space for null terminator. -// If bufsize is insufficient, the string will be truncated and null terminated. -// If buf is NULL, this method returns the length of the string (in 2-byte -// code units) via the result parameter. -// The result argument is optional unless buf is NULL. -napi_status napi_get_value_string_utf16(napi_env env, - napi_value value, - char16_t* buf, - size_t bufsize, - size_t* result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected); - - if (!buf) { - CHECK_ARG(env, result); - // V8 assumes UTF-16 length is the same as the number of characters. - *result = val.As<v8::String>()->Length(); - } else { - int copied = val.As<v8::String>()->Write( - reinterpret_cast<uint16_t*>(buf), 0, bufsize - 1, - v8::String::NO_NULL_TERMINATION); - - buf[copied] = '\0'; - if (result != nullptr) { - *result = copied; - } - } - - return napi_clear_last_error(env); -} - -napi_status napi_coerce_to_object(napi_env env, - napi_value value, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Object> obj; - CHECK_TO_OBJECT(env, context, obj, value); - - *result = v8impl::JsValueFromV8LocalValue(obj); - return GET_RETURN_STATUS(env); -} - -napi_status napi_coerce_to_bool(napi_env env, - napi_value value, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Boolean> b; - - CHECK_TO_BOOL(env, context, b, value); - - *result = v8impl::JsValueFromV8LocalValue(b); - return GET_RETURN_STATUS(env); -} - -napi_status napi_coerce_to_number(napi_env env, - napi_value value, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Number> num; - - CHECK_TO_NUMBER(env, context, num, value); - - *result = v8impl::JsValueFromV8LocalValue(num); - return GET_RETURN_STATUS(env); -} - -napi_status napi_coerce_to_string(napi_env env, - napi_value value, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::String> str; - - CHECK_TO_STRING(env, context, str, value); - - *result = v8impl::JsValueFromV8LocalValue(str); - return GET_RETURN_STATUS(env); -} - -napi_status napi_wrap(napi_env env, - napi_value js_object, - void* native_object, - napi_finalize finalize_cb, - void* finalize_hint, - napi_ref* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, js_object); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(js_object); - RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg); - v8::Local<v8::Object> obj = value.As<v8::Object>(); - - // If we've already wrapped this object, we error out. - RETURN_STATUS_IF_FALSE(env, !v8impl::FindWrapper(obj), napi_invalid_arg); - - // Create a wrapper object with an internal field to hold the wrapped pointer - // and a second internal field to identify the owner as N-API. - v8::Local<v8::ObjectTemplate> wrapper_template; - ENV_OBJECT_TEMPLATE(env, wrap, wrapper_template, v8impl::kWrapperFields); - - auto maybe_object = wrapper_template->NewInstance(context); - CHECK_MAYBE_EMPTY(env, maybe_object, napi_generic_failure); - v8::Local<v8::Object> wrapper = maybe_object.ToLocalChecked(); - - // Store the pointer as an external in the wrapper. - wrapper->SetInternalField(0, v8::External::New(isolate, native_object)); - wrapper->SetInternalField(1, v8::External::New(isolate, - reinterpret_cast<void*>(const_cast<char*>(v8impl::napi_wrap_name)))); - - // Insert the wrapper into the object's prototype chain. - v8::Local<v8::Value> proto = obj->GetPrototype(); - CHECK(wrapper->SetPrototype(context, proto).FromJust()); - CHECK(obj->SetPrototype(context, wrapper).FromJust()); - - v8impl::Reference* reference = nullptr; - if (result != nullptr) { - // The returned reference should be deleted via napi_delete_reference() - // ONLY in response to the finalize callback invocation. (If it is deleted - // before then, then the finalize callback will never be invoked.) - // Therefore a finalize callback is required when returning a reference. - CHECK_ARG(env, finalize_cb); - reference = v8impl::Reference::New( - env, obj, 0, false, finalize_cb, native_object, finalize_hint); - *result = reinterpret_cast<napi_ref>(reference); - } else if (finalize_cb != nullptr) { - // Create a self-deleting reference just for the finalize callback. - reference = v8impl::Reference::New( - env, obj, 0, true, finalize_cb, native_object, finalize_hint); - } - - if (reference != nullptr) { - wrapper->SetInternalField(2, v8::External::New(isolate, reference)); - } - - return GET_RETURN_STATUS(env); -} - -napi_status napi_unwrap(napi_env env, napi_value obj, void** result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - v8::Local<v8::Object> wrapper; - return napi_set_last_error(env, v8impl::Unwrap(env, obj, result, &wrapper)); -} - -napi_status napi_remove_wrap(napi_env env, napi_value obj, void** result) { - NAPI_PREAMBLE(env); - v8::Local<v8::Object> wrapper; - v8::Local<v8::Object> parent; - napi_status status = v8impl::Unwrap(env, obj, result, &wrapper, &parent); - if (status != napi_ok) { - return napi_set_last_error(env, status); - } - - v8::Local<v8::Value> external = wrapper->GetInternalField(2); - if (external->IsExternal()) { - v8impl::Reference::Delete( - static_cast<v8impl::Reference*>(external.As<v8::External>()->Value())); - } - - if (!parent.IsEmpty()) { - v8::Maybe<bool> maybe = parent->SetPrototype( - env->isolate->GetCurrentContext(), wrapper->GetPrototype()); - CHECK_MAYBE_NOTHING(env, maybe, napi_generic_failure); - if (!maybe.FromMaybe(false)) { - return napi_set_last_error(env, napi_generic_failure); - } - } - - return GET_RETURN_STATUS(env); -} - -napi_status napi_create_external(napi_env env, - void* data, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - - v8::Local<v8::Value> external_value = v8::External::New(isolate, data); - - // The Reference object will delete itself after invoking the finalizer - // callback. - v8impl::Reference::New(env, - external_value, - 0, - true, - finalize_cb, - data, - finalize_hint); - - *result = v8impl::JsValueFromV8LocalValue(external_value); - - return napi_clear_last_error(env); -} - -napi_status napi_get_value_external(napi_env env, - napi_value value, - void** result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - RETURN_STATUS_IF_FALSE(env, val->IsExternal(), napi_invalid_arg); - - v8::Local<v8::External> external_value = val.As<v8::External>(); - *result = external_value->Value(); - - return napi_clear_last_error(env); -} - -// Set initial_refcount to 0 for a weak reference, >0 for a strong reference. -napi_status napi_create_reference(napi_env env, - napi_value value, - uint32_t initial_refcount, - napi_ref* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> v8_value = v8impl::V8LocalValueFromJsValue(value); - - if (!(v8_value->IsObject() || v8_value->IsFunction())) { - return napi_set_last_error(env, napi_object_expected); - } - - v8impl::Reference* reference = - v8impl::Reference::New(env, v8_value, initial_refcount, false); - - *result = reinterpret_cast<napi_ref>(reference); - return napi_clear_last_error(env); -} - -// Deletes a reference. The referenced value is released, and may be GC'd unless -// there are other references to it. -napi_status napi_delete_reference(napi_env env, napi_ref ref) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, ref); - - v8impl::Reference::Delete(reinterpret_cast<v8impl::Reference*>(ref)); - - return napi_clear_last_error(env); -} - -// Increments the reference count, optionally returning the resulting count. -// After this call the reference will be a strong reference because its -// refcount is >0, and the referenced object is effectively "pinned". -// Calling this when the refcount is 0 and the object is unavailable -// results in an error. -napi_status napi_reference_ref(napi_env env, napi_ref ref, uint32_t* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, ref); - - v8impl::Reference* reference = reinterpret_cast<v8impl::Reference*>(ref); - uint32_t count = reference->Ref(); - - if (result != nullptr) { - *result = count; - } - - return napi_clear_last_error(env); -} - -// Decrements the reference count, optionally returning the resulting count. If -// the result is 0 the reference is now weak and the object may be GC'd at any -// time if there are no other references. Calling this when the refcount is -// already 0 results in an error. -napi_status napi_reference_unref(napi_env env, napi_ref ref, uint32_t* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, ref); - - v8impl::Reference* reference = reinterpret_cast<v8impl::Reference*>(ref); - - if (reference->RefCount() == 0) { - return napi_set_last_error(env, napi_generic_failure); - } - - uint32_t count = reference->Unref(); - - if (result != nullptr) { - *result = count; - } - - return napi_clear_last_error(env); -} - -// Attempts to get a referenced value. If the reference is weak, the value might -// no longer be available, in that case the call is still successful but the -// result is NULL. -napi_status napi_get_reference_value(napi_env env, - napi_ref ref, - napi_value* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, ref); - CHECK_ARG(env, result); - - v8impl::Reference* reference = reinterpret_cast<v8impl::Reference*>(ref); - *result = v8impl::JsValueFromV8LocalValue(reference->Get()); - - return napi_clear_last_error(env); -} - -napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsHandleScopeFromV8HandleScope( - new v8impl::HandleScopeWrapper(env->isolate)); - env->open_handle_scopes++; - return napi_clear_last_error(env); -} - -napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, scope); - if (env->open_handle_scopes == 0) { - return napi_handle_scope_mismatch; - } - - env->open_handle_scopes--; - delete v8impl::V8HandleScopeFromJsHandleScope(scope); - return napi_clear_last_error(env); -} - -napi_status napi_open_escapable_handle_scope( - napi_env env, - napi_escapable_handle_scope* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = v8impl::JsEscapableHandleScopeFromV8EscapableHandleScope( - new v8impl::EscapableHandleScopeWrapper(env->isolate)); - env->open_handle_scopes++; - return napi_clear_last_error(env); -} - -napi_status napi_close_escapable_handle_scope( - napi_env env, - napi_escapable_handle_scope scope) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, scope); - if (env->open_handle_scopes == 0) { - return napi_handle_scope_mismatch; - } - - delete v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope(scope); - env->open_handle_scopes--; - return napi_clear_last_error(env); -} - -napi_status napi_escape_handle(napi_env env, - napi_escapable_handle_scope scope, - napi_value escapee, - napi_value* result) { - // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw - // JS exceptions. - CHECK_ENV(env); - CHECK_ARG(env, scope); - CHECK_ARG(env, escapee); - CHECK_ARG(env, result); - - v8impl::EscapableHandleScopeWrapper* s = - v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope(scope); - if (!s->escape_called()) { - *result = v8impl::JsValueFromV8LocalValue( - s->Escape(v8impl::V8LocalValueFromJsValue(escapee))); - return napi_clear_last_error(env); - } - return napi_set_last_error(env, napi_escape_called_twice); -} - -napi_status napi_new_instance(napi_env env, - napi_value constructor, - size_t argc, - const napi_value* argv, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, constructor); - if (argc > 0) { - CHECK_ARG(env, argv); - } - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - v8::Local<v8::Function> ctor; - CHECK_TO_FUNCTION(env, ctor, constructor); - - auto maybe = ctor->NewInstance(context, argc, - reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv))); - - CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); - - *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); - return GET_RETURN_STATUS(env); -} - -napi_status napi_instanceof(napi_env env, - napi_value object, - napi_value constructor, - bool* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, object); - CHECK_ARG(env, result); - - *result = false; - - v8::Local<v8::Object> ctor; - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - CHECK_TO_OBJECT(env, context, ctor, constructor); - - if (!ctor->IsFunction()) { - napi_throw_type_error(env, - "ERR_NAPI_CONS_FUNCTION", - "Constructor must be a function"); - - return napi_set_last_error(env, napi_function_expected); - } - - if (env->has_instance_available) { - napi_value value, js_result = nullptr, has_instance = nullptr; - napi_status status = napi_generic_failure; - napi_valuetype value_type; - - // Get "Symbol" from the global object - if (env->has_instance.IsEmpty()) { - status = napi_get_global(env, &value); - if (status != napi_ok) return status; - status = napi_get_named_property(env, value, "Symbol", &value); - if (status != napi_ok) return status; - status = napi_typeof(env, value, &value_type); - if (status != napi_ok) return status; - - // Get "hasInstance" from Symbol - if (value_type == napi_function) { - status = napi_get_named_property(env, value, "hasInstance", &value); - if (status != napi_ok) return status; - status = napi_typeof(env, value, &value_type); - if (status != napi_ok) return status; - - // Store Symbol.hasInstance in a global persistent reference - if (value_type == napi_symbol) { - env->has_instance.Reset(env->isolate, - v8impl::V8LocalValueFromJsValue(value)); - has_instance = value; - } - } - } else { - has_instance = v8impl::JsValueFromV8LocalValue( - v8::Local<v8::Value>::New(env->isolate, env->has_instance)); - } - - if (has_instance) { - status = napi_get_property(env, constructor, has_instance, &value); - if (status != napi_ok) return status; - status = napi_typeof(env, value, &value_type); - if (status != napi_ok) return status; - - // Call the function to determine whether the object is an instance of the - // constructor - if (value_type == napi_function) { - status = napi_call_function(env, constructor, value, 1, &object, - &js_result); - if (status != napi_ok) return status; - return napi_get_value_bool(env, js_result, result); - } - } - - env->has_instance_available = false; - } - - // If running constructor[Symbol.hasInstance](object) did not work, we perform - // a traditional instanceof (early Node.js 6.x). - - v8::Local<v8::String> prototype_string; - CHECK_NEW_FROM_UTF8(env, prototype_string, "prototype"); - - auto maybe_prototype = ctor->Get(context, prototype_string); - CHECK_MAYBE_EMPTY(env, maybe_prototype, napi_generic_failure); - - v8::Local<v8::Value> prototype_property = maybe_prototype.ToLocalChecked(); - if (!prototype_property->IsObject()) { - napi_throw_type_error( - env, - "ERR_NAPI_CONS_PROTOTYPE_OBJECT", - "Constructor.prototype must be an object"); - - return napi_set_last_error(env, napi_object_expected); - } - - auto maybe_ctor = prototype_property->ToObject(context); - CHECK_MAYBE_EMPTY(env, maybe_ctor, napi_generic_failure); - ctor = maybe_ctor.ToLocalChecked(); - - v8::Local<v8::Value> current_obj = v8impl::V8LocalValueFromJsValue(object); - if (!current_obj->StrictEquals(ctor)) { - for (v8::Local<v8::Value> original_obj = current_obj; - !(current_obj->IsNull() || current_obj->IsUndefined());) { - if (current_obj->StrictEquals(ctor)) { - *result = !(original_obj->IsNumber() || - original_obj->IsBoolean() || - original_obj->IsString()); - break; - } - v8::Local<v8::Object> obj; - CHECK_TO_OBJECT(env, context, obj, v8impl::JsValueFromV8LocalValue( - current_obj)); - current_obj = obj->GetPrototype(); - } - } - - return GET_RETURN_STATUS(env); -} - -napi_status napi_async_init(napi_env env, - napi_value async_resource, - napi_value async_resource_name, - napi_async_context* result) { - CHECK_ENV(env); - CHECK_ARG(env, async_resource_name); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - v8::Local<v8::Object> v8_resource; - if (async_resource != nullptr) { - CHECK_TO_OBJECT(env, context, v8_resource, async_resource); - } else { - v8_resource = v8::Object::New(isolate); - } - - v8::Local<v8::String> v8_resource_name; - CHECK_TO_STRING(env, context, v8_resource_name, async_resource_name); - - // TODO(jasongin): Consider avoiding allocation here by using - // a tagged pointer with 2×31 bit fields instead. - node::async_context* async_context = new node::async_context(); - - *async_context = node::EmitAsyncInit(isolate, v8_resource, v8_resource_name); - *result = reinterpret_cast<napi_async_context>(async_context); - - return napi_clear_last_error(env); -} - -napi_status napi_async_destroy(napi_env env, - napi_async_context async_context) { - CHECK_ENV(env); - CHECK_ARG(env, async_context); - - v8::Isolate* isolate = env->isolate; - node::async_context* node_async_context = - reinterpret_cast<node::async_context*>(async_context); - node::EmitAsyncDestroy(isolate, *node_async_context); - - delete node_async_context; - - return napi_clear_last_error(env); -} - -napi_status napi_make_callback(napi_env env, - napi_async_context async_context, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, recv); - if (argc > 0) { - CHECK_ARG(env, argv); - } - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - v8::Local<v8::Object> v8recv; - CHECK_TO_OBJECT(env, context, v8recv, recv); - - v8::Local<v8::Function> v8func; - CHECK_TO_FUNCTION(env, v8func, func); - - node::async_context* node_async_context = - reinterpret_cast<node::async_context*>(async_context); - if (node_async_context == nullptr) { - static node::async_context empty_context = { 0, 0 }; - node_async_context = &empty_context; - } - - v8::MaybeLocal<v8::Value> callback_result = node::MakeCallback( - isolate, v8recv, v8func, argc, - reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv)), - *node_async_context); - CHECK_MAYBE_EMPTY(env, callback_result, napi_generic_failure); - - if (result != nullptr) { - *result = v8impl::JsValueFromV8LocalValue( - callback_result.ToLocalChecked()); - } - - return GET_RETURN_STATUS(env); -} - -// Methods to support catching exceptions -napi_status napi_is_exception_pending(napi_env env, bool* result) { - // NAPI_PREAMBLE is not used here: this function must execute when there is a - // pending exception. - CHECK_ENV(env); - CHECK_ARG(env, result); - - *result = !env->last_exception.IsEmpty(); - return napi_clear_last_error(env); -} - -napi_status napi_get_and_clear_last_exception(napi_env env, - napi_value* result) { - // NAPI_PREAMBLE is not used here: this function must execute when there is a - // pending exception. - CHECK_ENV(env); - CHECK_ARG(env, result); - - if (env->last_exception.IsEmpty()) { - return napi_get_undefined(env, result); - } else { - *result = v8impl::JsValueFromV8LocalValue( - v8::Local<v8::Value>::New(env->isolate, env->last_exception)); - env->last_exception.Reset(); - } - - return napi_clear_last_error(env); -} - -napi_status napi_create_buffer(napi_env env, - size_t length, - void** data, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - auto maybe = node::Buffer::New(env->isolate, length); - - CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); - - v8::Local<v8::Object> buffer = maybe.ToLocalChecked(); - - *result = v8impl::JsValueFromV8LocalValue(buffer); - - if (data != nullptr) { - *data = node::Buffer::Data(buffer); - } - - return GET_RETURN_STATUS(env); -} - -napi_status napi_create_external_buffer(napi_env env, - size_t length, - void* data, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - - // The finalizer object will delete itself after invoking the callback. - v8impl::Finalizer* finalizer = v8impl::Finalizer::New( - env, finalize_cb, nullptr, finalize_hint); - - auto maybe = node::Buffer::New(isolate, - static_cast<char*>(data), - length, - v8impl::Finalizer::FinalizeBufferCallback, - finalizer); - - CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); - - *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); - return GET_RETURN_STATUS(env); - // Tell coverity that 'finalizer' should not be freed when we return - // as it will be deleted when the buffer to which it is associated - // is finalized. - // coverity[leaked_storage] -} - -napi_status napi_create_buffer_copy(napi_env env, - size_t length, - const void* data, - void** result_data, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - auto maybe = node::Buffer::Copy(env->isolate, - static_cast<const char*>(data), length); - - CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); - - v8::Local<v8::Object> buffer = maybe.ToLocalChecked(); - *result = v8impl::JsValueFromV8LocalValue(buffer); - - if (result_data != nullptr) { - *result_data = node::Buffer::Data(buffer); - } - - return GET_RETURN_STATUS(env); -} - -napi_status napi_is_buffer(napi_env env, napi_value value, bool* result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - *result = node::Buffer::HasInstance(v8impl::V8LocalValueFromJsValue(value)); - return napi_clear_last_error(env); -} - -napi_status napi_get_buffer_info(napi_env env, - napi_value value, - void** data, - size_t* length) { - CHECK_ENV(env); - CHECK_ARG(env, value); - - v8::Local<v8::Value> buffer = v8impl::V8LocalValueFromJsValue(value); - - if (data != nullptr) { - *data = node::Buffer::Data(buffer); - } - if (length != nullptr) { - *length = node::Buffer::Length(buffer); - } - - return napi_clear_last_error(env); -} - -napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - *result = val->IsArrayBuffer(); - - return napi_clear_last_error(env); -} - -napi_status napi_create_arraybuffer(napi_env env, - size_t byte_length, - void** data, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::ArrayBuffer> buffer = - v8::ArrayBuffer::New(isolate, byte_length); - - // Optionally return a pointer to the buffer's data, to avoid another call to - // retrieve it. - if (data != nullptr) { - *data = buffer->GetContents().Data(); - } - - *result = v8impl::JsValueFromV8LocalValue(buffer); - return GET_RETURN_STATUS(env); -} - -napi_status napi_create_external_arraybuffer(napi_env env, - void* external_data, - size_t byte_length, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, result); - - v8::Isolate* isolate = env->isolate; - v8::Local<v8::ArrayBuffer> buffer = - v8::ArrayBuffer::New(isolate, external_data, byte_length); - - if (finalize_cb != nullptr) { - // Create a self-deleting weak reference that invokes the finalizer - // callback. - v8impl::Reference::New(env, - buffer, - 0, - true, - finalize_cb, - external_data, - finalize_hint); - } - - *result = v8impl::JsValueFromV8LocalValue(buffer); - return GET_RETURN_STATUS(env); -} - -napi_status napi_get_arraybuffer_info(napi_env env, - napi_value arraybuffer, - void** data, - size_t* byte_length) { - CHECK_ENV(env); - CHECK_ARG(env, arraybuffer); - - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(arraybuffer); - RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg); - - v8::ArrayBuffer::Contents contents = - value.As<v8::ArrayBuffer>()->GetContents(); - - if (data != nullptr) { - *data = contents.Data(); - } - - if (byte_length != nullptr) { - *byte_length = contents.ByteLength(); - } - - return napi_clear_last_error(env); -} - -napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - *result = val->IsTypedArray(); - - return napi_clear_last_error(env); -} - -napi_status napi_create_typedarray(napi_env env, - napi_typedarray_type type, - size_t length, - napi_value arraybuffer, - size_t byte_offset, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, arraybuffer); - CHECK_ARG(env, result); - - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(arraybuffer); - RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg); - - v8::Local<v8::ArrayBuffer> buffer = value.As<v8::ArrayBuffer>(); - v8::Local<v8::TypedArray> typedArray; - - switch (type) { - case napi_int8_array: - CREATE_TYPED_ARRAY( - env, Int8Array, 1, buffer, byte_offset, length, typedArray); - break; - case napi_uint8_array: - CREATE_TYPED_ARRAY( - env, Uint8Array, 1, buffer, byte_offset, length, typedArray); - break; - case napi_uint8_clamped_array: - CREATE_TYPED_ARRAY( - env, Uint8ClampedArray, 1, buffer, byte_offset, length, typedArray); - break; - case napi_int16_array: - CREATE_TYPED_ARRAY( - env, Int16Array, 2, buffer, byte_offset, length, typedArray); - break; - case napi_uint16_array: - CREATE_TYPED_ARRAY( - env, Uint16Array, 2, buffer, byte_offset, length, typedArray); - break; - case napi_int32_array: - CREATE_TYPED_ARRAY( - env, Int32Array, 4, buffer, byte_offset, length, typedArray); - break; - case napi_uint32_array: - CREATE_TYPED_ARRAY( - env, Uint32Array, 4, buffer, byte_offset, length, typedArray); - break; - case napi_float32_array: - CREATE_TYPED_ARRAY( - env, Float32Array, 4, buffer, byte_offset, length, typedArray); - break; - case napi_float64_array: - CREATE_TYPED_ARRAY( - env, Float64Array, 8, buffer, byte_offset, length, typedArray); - break; - default: - return napi_set_last_error(env, napi_invalid_arg); - } - - *result = v8impl::JsValueFromV8LocalValue(typedArray); - return GET_RETURN_STATUS(env); -} - -napi_status napi_get_typedarray_info(napi_env env, - napi_value typedarray, - napi_typedarray_type* type, - size_t* length, - void** data, - napi_value* arraybuffer, - size_t* byte_offset) { - CHECK_ENV(env); - CHECK_ARG(env, typedarray); - - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(typedarray); - RETURN_STATUS_IF_FALSE(env, value->IsTypedArray(), napi_invalid_arg); - - v8::Local<v8::TypedArray> array = value.As<v8::TypedArray>(); - - if (type != nullptr) { - if (value->IsInt8Array()) { - *type = napi_int8_array; - } else if (value->IsUint8Array()) { - *type = napi_uint8_array; - } else if (value->IsUint8ClampedArray()) { - *type = napi_uint8_clamped_array; - } else if (value->IsInt16Array()) { - *type = napi_int16_array; - } else if (value->IsUint16Array()) { - *type = napi_uint16_array; - } else if (value->IsInt32Array()) { - *type = napi_int32_array; - } else if (value->IsUint32Array()) { - *type = napi_uint32_array; - } else if (value->IsFloat32Array()) { - *type = napi_float32_array; - } else if (value->IsFloat64Array()) { - *type = napi_float64_array; - } - } - - if (length != nullptr) { - *length = array->Length(); - } - - v8::Local<v8::ArrayBuffer> buffer = array->Buffer(); - if (data != nullptr) { - *data = static_cast<uint8_t*>(buffer->GetContents().Data()) + - array->ByteOffset(); - } - - if (arraybuffer != nullptr) { - *arraybuffer = v8impl::JsValueFromV8LocalValue(buffer); - } - - if (byte_offset != nullptr) { - *byte_offset = array->ByteOffset(); - } - - return napi_clear_last_error(env); -} - -napi_status napi_create_dataview(napi_env env, - size_t byte_length, - napi_value arraybuffer, - size_t byte_offset, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, arraybuffer); - CHECK_ARG(env, result); - - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(arraybuffer); - RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg); - - v8::Local<v8::ArrayBuffer> buffer = value.As<v8::ArrayBuffer>(); - if (byte_length + byte_offset > buffer->ByteLength()) { - napi_throw_range_error( - env, - "ERR_NAPI_INVALID_DATAVIEW_ARGS", - "byte_offset + byte_length should be less than or " - "equal to the size in bytes of the array passed in"); - return napi_set_last_error(env, napi_generic_failure); - } - v8::Local<v8::DataView> DataView = v8::DataView::New(buffer, byte_offset, - byte_length); - - *result = v8impl::JsValueFromV8LocalValue(DataView); - return GET_RETURN_STATUS(env); -} - -napi_status napi_is_dataview(napi_env env, napi_value value, bool* result) { - CHECK_ENV(env); - CHECK_ARG(env, value); - CHECK_ARG(env, result); - - v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); - *result = val->IsDataView(); - - return napi_clear_last_error(env); -} - -napi_status napi_get_dataview_info(napi_env env, - napi_value dataview, - size_t* byte_length, - void** data, - napi_value* arraybuffer, - size_t* byte_offset) { - CHECK_ENV(env); - CHECK_ARG(env, dataview); - - v8::Local<v8::Value> value = v8impl::V8LocalValueFromJsValue(dataview); - RETURN_STATUS_IF_FALSE(env, value->IsDataView(), napi_invalid_arg); - - v8::Local<v8::DataView> array = value.As<v8::DataView>(); - - if (byte_length != nullptr) { - *byte_length = array->ByteLength(); - } - - v8::Local<v8::ArrayBuffer> buffer = array->Buffer(); - if (data != nullptr) { - *data = static_cast<uint8_t*>(buffer->GetContents().Data()) + - array->ByteOffset(); - } - - if (arraybuffer != nullptr) { - *arraybuffer = v8impl::JsValueFromV8LocalValue(buffer); - } - - if (byte_offset != nullptr) { - *byte_offset = array->ByteOffset(); - } - - return napi_clear_last_error(env); -} - -napi_status napi_get_version(napi_env env, uint32_t* result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - *result = NAPI_VERSION; - return napi_clear_last_error(env); -} - -napi_status napi_get_node_version(napi_env env, - const napi_node_version** result) { - CHECK_ENV(env); - CHECK_ARG(env, result); - static const napi_node_version version = { - NODE_MAJOR_VERSION, - NODE_MINOR_VERSION, - NODE_PATCH_VERSION, - NODE_RELEASE - }; - *result = &version; - return napi_clear_last_error(env); -} - -napi_status napi_adjust_external_memory(napi_env env, - int64_t change_in_bytes, - int64_t* adjusted_value) { - CHECK_ENV(env); - CHECK_ARG(env, adjusted_value); - - *adjusted_value = env->isolate->AdjustAmountOfExternalAllocatedMemory( - change_in_bytes); - - return napi_clear_last_error(env); -} - -namespace { -namespace uvimpl { - -static napi_status ConvertUVErrorCode(int code) { - switch (code) { - case 0: - return napi_ok; - case UV_EINVAL: - return napi_invalid_arg; - case UV_ECANCELED: - return napi_cancelled; - } - - return napi_generic_failure; -} - -// Wrapper around uv_work_t which calls user-provided callbacks. -class Work : public node::AsyncResource { - private: - explicit Work(napi_env env, - v8::Local<v8::Object> async_resource, - v8::Local<v8::String> async_resource_name, - napi_async_execute_callback execute, - napi_async_complete_callback complete = nullptr, - void* data = nullptr) - : AsyncResource(env->isolate, - async_resource, - *v8::String::Utf8Value(async_resource_name)), - _env(env), - _data(data), - _execute(execute), - _complete(complete) { - memset(&_request, 0, sizeof(_request)); - _request.data = this; - } - - ~Work() { } - - public: - static Work* New(napi_env env, - v8::Local<v8::Object> async_resource, - v8::Local<v8::String> async_resource_name, - napi_async_execute_callback execute, - napi_async_complete_callback complete, - void* data) { - return new Work(env, async_resource, async_resource_name, - execute, complete, data); - } - - static void Delete(Work* work) { - delete work; - } - - static void ExecuteCallback(uv_work_t* req) { - Work* work = static_cast<Work*>(req->data); - work->_execute(work->_env, work->_data); - } - - static void CompleteCallback(uv_work_t* req, int status) { - Work* work = static_cast<Work*>(req->data); - - if (work->_complete != nullptr) { - napi_env env = work->_env; - - // Establish a handle scope here so that every callback doesn't have to. - // Also it is needed for the exception-handling below. - v8::HandleScope scope(env->isolate); - CallbackScope callback_scope(work); - - NAPI_CALL_INTO_MODULE(env, - work->_complete(env, ConvertUVErrorCode(status), work->_data), - [env] (v8::Local<v8::Value> local_err) { - // If there was an unhandled exception in the complete callback, - // report it as a fatal exception. (There is no JavaScript on the - // callstack that can possibly handle it.) - v8impl::trigger_fatal_exception(env, local_err); - }); - - // Note: Don't access `work` after this point because it was - // likely deleted by the complete callback. - } - } - - uv_work_t* Request() { - return &_request; - } - - private: - napi_env _env; - void* _data; - uv_work_t _request; - napi_async_execute_callback _execute; - napi_async_complete_callback _complete; -}; - -} // end of namespace uvimpl -} // end of anonymous namespace - -#define CALL_UV(env, condition) \ - do { \ - int result = (condition); \ - napi_status status = uvimpl::ConvertUVErrorCode(result); \ - if (status != napi_ok) { \ - return napi_set_last_error(env, status, result); \ - } \ - } while (0) - -napi_status napi_create_async_work(napi_env env, - napi_value async_resource, - napi_value async_resource_name, - napi_async_execute_callback execute, - napi_async_complete_callback complete, - void* data, - napi_async_work* result) { - CHECK_ENV(env); - CHECK_ARG(env, execute); - CHECK_ARG(env, result); - - v8::Local<v8::Context> context = env->isolate->GetCurrentContext(); - - v8::Local<v8::Object> resource; - if (async_resource != nullptr) { - CHECK_TO_OBJECT(env, context, resource, async_resource); - } else { - resource = v8::Object::New(env->isolate); - } - - v8::Local<v8::String> resource_name; - CHECK_TO_STRING(env, context, resource_name, async_resource_name); - - uvimpl::Work* work = - uvimpl::Work::New(env, resource, resource_name, - execute, complete, data); - - *result = reinterpret_cast<napi_async_work>(work); - - return napi_clear_last_error(env); -} - -napi_status napi_delete_async_work(napi_env env, napi_async_work work) { - CHECK_ENV(env); - CHECK_ARG(env, work); - - uvimpl::Work::Delete(reinterpret_cast<uvimpl::Work*>(work)); - - return napi_clear_last_error(env); -} - -napi_status napi_queue_async_work(napi_env env, napi_async_work work) { - CHECK_ENV(env); - CHECK_ARG(env, work); - - // Consider: Encapsulate the uv_loop_t into an opaque pointer parameter. - // Currently the environment event loop is the same as the UV default loop. - // Someday (if node ever supports multiple isolates), it may be better to get - // the loop from node::Environment::GetCurrent(env->isolate)->event_loop(); - uv_loop_t* event_loop = uv_default_loop(); - - uvimpl::Work* w = reinterpret_cast<uvimpl::Work*>(work); - - CALL_UV(env, uv_queue_work(event_loop, - w->Request(), - uvimpl::Work::ExecuteCallback, - uvimpl::Work::CompleteCallback)); - - return napi_clear_last_error(env); -} - -napi_status napi_cancel_async_work(napi_env env, napi_async_work work) { - CHECK_ENV(env); - CHECK_ARG(env, work); - - uvimpl::Work* w = reinterpret_cast<uvimpl::Work*>(work); - - CALL_UV(env, uv_cancel(reinterpret_cast<uv_req_t*>(w->Request()))); - - return napi_clear_last_error(env); -} - -napi_status napi_create_promise(napi_env env, - napi_deferred* deferred, - napi_value* promise) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, deferred); - CHECK_ARG(env, promise); - - auto maybe = v8::Promise::Resolver::New(env->isolate->GetCurrentContext()); - CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); - - auto v8_resolver = maybe.ToLocalChecked(); - auto v8_deferred = new v8::Persistent<v8::Value>(); - v8_deferred->Reset(env->isolate, v8_resolver); - - *deferred = v8impl::JsDeferredFromV8Persistent(v8_deferred); - *promise = v8impl::JsValueFromV8LocalValue(v8_resolver->GetPromise()); - return GET_RETURN_STATUS(env); -} - -napi_status napi_resolve_deferred(napi_env env, - napi_deferred deferred, - napi_value resolution) { - return v8impl::ConcludeDeferred(env, deferred, resolution, true); -} - -napi_status napi_reject_deferred(napi_env env, - napi_deferred deferred, - napi_value resolution) { - return v8impl::ConcludeDeferred(env, deferred, resolution, false); -} - -napi_status napi_is_promise(napi_env env, - napi_value promise, - bool* is_promise) { - CHECK_ENV(env); - CHECK_ARG(env, promise); - CHECK_ARG(env, is_promise); - - *is_promise = v8impl::V8LocalValueFromJsValue(promise)->IsPromise(); - - return napi_clear_last_error(env); -} - -napi_status napi_run_script(napi_env env, - napi_value script, - napi_value* result) { - NAPI_PREAMBLE(env); - CHECK_ARG(env, script); - CHECK_ARG(env, result); - - v8::Local<v8::Value> v8_script = v8impl::V8LocalValueFromJsValue(script); - - if (!v8_script->IsString()) { - return napi_set_last_error(env, napi_string_expected); - } - - v8::Local<v8::Context> context = env->isolate->GetCurrentContext(); - - auto maybe_script = v8::Script::Compile(context, - v8::Local<v8::String>::Cast(v8_script)); - CHECK_MAYBE_EMPTY(env, maybe_script, napi_generic_failure); - - auto script_result = - maybe_script.ToLocalChecked()->Run(context); - CHECK_MAYBE_EMPTY(env, script_result, napi_generic_failure); - - *result = v8impl::JsValueFromV8LocalValue(script_result.ToLocalChecked()); - return GET_RETURN_STATUS(env); -} diff --git a/node_modules/node-addon-api/src/node_api.gyp b/node_modules/node-addon-api/src/node_api.gyp deleted file mode 100644 index 3de7da1..0000000 --- a/node_modules/node-addon-api/src/node_api.gyp +++ /dev/null @@ -1,21 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'nothing', - 'type': 'static_library', - 'sources': [ 'nothing.c' ] - }, - { - 'target_name': 'node-api', - 'type': 'static_library', - 'sources': [ - 'node_api.cc', - 'node_internals.cc', - ], - 'defines': [ - 'EXTERNAL_NAPI', - ], - 'cflags_cc': ['-fvisibility=hidden'] - } - ] -} diff --git a/node_modules/node-addon-api/src/node_api.h b/node_modules/node-addon-api/src/node_api.h deleted file mode 100644 index 27028f7..0000000 --- a/node_modules/node-addon-api/src/node_api.h +++ /dev/null @@ -1,588 +0,0 @@ -/****************************************************************************** - * Experimental prototype for demonstrating VM agnostic and ABI stable API - * for native modules to use instead of using Nan and V8 APIs directly. - * - * The current status is "Experimental" and should not be used for - * production applications. The API is still subject to change - * and as an experimental feature is NOT subject to semver. - * - ******************************************************************************/ -#ifndef SRC_NODE_API_H_ -#define SRC_NODE_API_H_ - -#include <stddef.h> -#include <stdbool.h> -#include "node_api_types.h" - -#ifdef _WIN32 - #ifdef BUILDING_NODE_EXTENSION - #ifdef EXTERNAL_NAPI - // Building external N-API, or native module against external N-API - #define NAPI_EXTERN /* nothing */ - #else - // Building native module against node with built-in N-API - #define NAPI_EXTERN __declspec(dllimport) - #endif - #else - // Building node with built-in N-API - #define NAPI_EXTERN __declspec(dllexport) - #endif -#else - #define NAPI_EXTERN /* nothing */ -#endif - -#ifdef _WIN32 -# define NAPI_MODULE_EXPORT __declspec(dllexport) -#else -# define NAPI_MODULE_EXPORT __attribute__((visibility("default"))) -#endif - -#ifdef __GNUC__ -#define NAPI_NO_RETURN __attribute__((noreturn)) -#else -#define NAPI_NO_RETURN -#endif - - -typedef napi_value (*napi_addon_register_func)(napi_env env, - napi_value exports); - -typedef struct { - int nm_version; - unsigned int nm_flags; - const char* nm_filename; - napi_addon_register_func nm_register_func; - const char* nm_modname; - void* nm_priv; - void* reserved[4]; -} napi_module; - -#define NAPI_MODULE_VERSION 1 - -#if defined(_MSC_VER) -#pragma section(".CRT$XCU", read) -#define NAPI_C_CTOR(fn) \ - static void __cdecl fn(void); \ - __declspec(dllexport, allocate(".CRT$XCU")) void(__cdecl * fn##_)(void) = \ - fn; \ - static void __cdecl fn(void) -#else -#define NAPI_C_CTOR(fn) \ - static void fn(void) __attribute__((constructor)); \ - static void fn(void) -#endif - -#ifdef __cplusplus -#define EXTERN_C_START extern "C" { -#define EXTERN_C_END } -#else -#define EXTERN_C_START -#define EXTERN_C_END -#endif - -#define NAPI_MODULE_X(modname, regfunc, priv, flags) \ - EXTERN_C_START \ - static napi_module _module = \ - { \ - NAPI_MODULE_VERSION, \ - flags, \ - __FILE__, \ - regfunc, \ - #modname, \ - priv, \ - {0}, \ - }; \ - NAPI_C_CTOR(_register_ ## modname) { \ - napi_module_register(&_module); \ - } \ - EXTERN_C_END - -#define NAPI_MODULE(modname, regfunc) \ - NAPI_MODULE_X(modname, regfunc, NULL, 0) - -#define NAPI_AUTO_LENGTH SIZE_MAX - -EXTERN_C_START - -NAPI_EXTERN void napi_module_register(napi_module* mod); - -NAPI_EXTERN napi_status -napi_get_last_error_info(napi_env env, - const napi_extended_error_info** result); - -NAPI_EXTERN napi_status napi_fatal_exception(napi_env env, napi_value err); - -NAPI_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, - size_t location_len, - const char* message, - size_t message_len); - -// Getters for defined singletons -NAPI_EXTERN napi_status napi_get_undefined(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_get_null(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_get_global(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_get_boolean(napi_env env, - bool value, - napi_value* result); - -// Methods to create Primitive types/Objects -NAPI_EXTERN napi_status napi_create_object(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_create_array(napi_env env, napi_value* result); -NAPI_EXTERN napi_status napi_create_array_with_length(napi_env env, - size_t length, - napi_value* result); -NAPI_EXTERN napi_status napi_create_double(napi_env env, - double value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_int32(napi_env env, - int32_t value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_uint32(napi_env env, - uint32_t value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_int64(napi_env env, - int64_t value, - napi_value* result); -NAPI_EXTERN napi_status napi_create_string_latin1(napi_env env, - const char* str, - size_t length, - napi_value* result); -NAPI_EXTERN napi_status napi_create_string_utf8(napi_env env, - const char* str, - size_t length, - napi_value* result); -NAPI_EXTERN napi_status napi_create_string_utf16(napi_env env, - const char16_t* str, - size_t length, - napi_value* result); -NAPI_EXTERN napi_status napi_create_symbol(napi_env env, - napi_value description, - napi_value* result); -NAPI_EXTERN napi_status napi_create_function(napi_env env, - const char* utf8name, - size_t length, - napi_callback cb, - void* data, - napi_value* result); -NAPI_EXTERN napi_status napi_create_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); -NAPI_EXTERN napi_status napi_create_type_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); -NAPI_EXTERN napi_status napi_create_range_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result); - -// Methods to get the the native napi_value from Primitive type -NAPI_EXTERN napi_status napi_typeof(napi_env env, - napi_value value, - napi_valuetype* result); -NAPI_EXTERN napi_status napi_get_value_double(napi_env env, - napi_value value, - double* result); -NAPI_EXTERN napi_status napi_get_value_int32(napi_env env, - napi_value value, - int32_t* result); -NAPI_EXTERN napi_status napi_get_value_uint32(napi_env env, - napi_value value, - uint32_t* result); -NAPI_EXTERN napi_status napi_get_value_int64(napi_env env, - napi_value value, - int64_t* result); -NAPI_EXTERN napi_status napi_get_value_bool(napi_env env, - napi_value value, - bool* result); - -// Copies LATIN-1 encoded bytes from a string into a buffer. -NAPI_EXTERN napi_status napi_get_value_string_latin1(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result); - -// Copies UTF-8 encoded bytes from a string into a buffer. -NAPI_EXTERN napi_status napi_get_value_string_utf8(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result); - -// Copies UTF-16 encoded bytes from a string into a buffer. -NAPI_EXTERN napi_status napi_get_value_string_utf16(napi_env env, - napi_value value, - char16_t* buf, - size_t bufsize, - size_t* result); - -// Methods to coerce values -// These APIs may execute user scripts -NAPI_EXTERN napi_status napi_coerce_to_bool(napi_env env, - napi_value value, - napi_value* result); -NAPI_EXTERN napi_status napi_coerce_to_number(napi_env env, - napi_value value, - napi_value* result); -NAPI_EXTERN napi_status napi_coerce_to_object(napi_env env, - napi_value value, - napi_value* result); -NAPI_EXTERN napi_status napi_coerce_to_string(napi_env env, - napi_value value, - napi_value* result); - -// Methods to work with Objects -NAPI_EXTERN napi_status napi_get_prototype(napi_env env, - napi_value object, - napi_value* result); -NAPI_EXTERN napi_status napi_get_property_names(napi_env env, - napi_value object, - napi_value* result); -NAPI_EXTERN napi_status napi_set_property(napi_env env, - napi_value object, - napi_value key, - napi_value value); -NAPI_EXTERN napi_status napi_has_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -NAPI_EXTERN napi_status napi_get_property(napi_env env, - napi_value object, - napi_value key, - napi_value* result); -NAPI_EXTERN napi_status napi_delete_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -NAPI_EXTERN napi_status napi_has_own_property(napi_env env, - napi_value object, - napi_value key, - bool* result); -NAPI_EXTERN napi_status napi_set_named_property(napi_env env, - napi_value object, - const char* utf8name, - napi_value value); -NAPI_EXTERN napi_status napi_has_named_property(napi_env env, - napi_value object, - const char* utf8name, - bool* result); -NAPI_EXTERN napi_status napi_get_named_property(napi_env env, - napi_value object, - const char* utf8name, - napi_value* result); -NAPI_EXTERN napi_status napi_set_element(napi_env env, - napi_value object, - uint32_t index, - napi_value value); -NAPI_EXTERN napi_status napi_has_element(napi_env env, - napi_value object, - uint32_t index, - bool* result); -NAPI_EXTERN napi_status napi_get_element(napi_env env, - napi_value object, - uint32_t index, - napi_value* result); -NAPI_EXTERN napi_status napi_delete_element(napi_env env, - napi_value object, - uint32_t index, - bool* result); -NAPI_EXTERN napi_status -napi_define_properties(napi_env env, - napi_value object, - size_t property_count, - const napi_property_descriptor* properties); - -// Methods to work with Arrays -NAPI_EXTERN napi_status napi_is_array(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_get_array_length(napi_env env, - napi_value value, - uint32_t* result); - -// Methods to compare values -NAPI_EXTERN napi_status napi_strict_equals(napi_env env, - napi_value lhs, - napi_value rhs, - bool* result); - -// Methods to work with Functions -NAPI_EXTERN napi_status napi_call_function(napi_env env, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); -NAPI_EXTERN napi_status napi_new_instance(napi_env env, - napi_value constructor, - size_t argc, - const napi_value* argv, - napi_value* result); -NAPI_EXTERN napi_status napi_instanceof(napi_env env, - napi_value object, - napi_value constructor, - bool* result); - -// Methods to work with napi_callbacks - -// Gets all callback info in a single call. (Ugly, but faster.) -NAPI_EXTERN napi_status napi_get_cb_info( - napi_env env, // [in] NAPI environment handle - napi_callback_info cbinfo, // [in] Opaque callback-info handle - size_t* argc, // [in-out] Specifies the size of the provided argv array - // and receives the actual count of args. - napi_value* argv, // [out] Array of values - napi_value* this_arg, // [out] Receives the JS 'this' arg for the call - void** data); // [out] Receives the data pointer for the callback. - -NAPI_EXTERN napi_status napi_get_new_target(napi_env env, - napi_callback_info cbinfo, - napi_value* result); -NAPI_EXTERN napi_status -napi_define_class(napi_env env, - const char* utf8name, - size_t length, - napi_callback constructor, - void* data, - size_t property_count, - const napi_property_descriptor* properties, - napi_value* result); - -// Methods to work with external data objects -NAPI_EXTERN napi_status napi_wrap(napi_env env, - napi_value js_object, - void* native_object, - napi_finalize finalize_cb, - void* finalize_hint, - napi_ref* result); -NAPI_EXTERN napi_status napi_unwrap(napi_env env, - napi_value js_object, - void** result); -NAPI_EXTERN napi_status napi_remove_wrap(napi_env env, - napi_value js_object, - void** result); -NAPI_EXTERN napi_status napi_create_external(napi_env env, - void* data, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result); -NAPI_EXTERN napi_status napi_get_value_external(napi_env env, - napi_value value, - void** result); - -// Methods to control object lifespan - -// Set initial_refcount to 0 for a weak reference, >0 for a strong reference. -NAPI_EXTERN napi_status napi_create_reference(napi_env env, - napi_value value, - uint32_t initial_refcount, - napi_ref* result); - -// Deletes a reference. The referenced value is released, and may -// be GC'd unless there are other references to it. -NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref); - -// Increments the reference count, optionally returning the resulting count. -// After this call the reference will be a strong reference because its -// refcount is >0, and the referenced object is effectively "pinned". -// Calling this when the refcount is 0 and the object is unavailable -// results in an error. -NAPI_EXTERN napi_status napi_reference_ref(napi_env env, - napi_ref ref, - uint32_t* result); - -// Decrements the reference count, optionally returning the resulting count. -// If the result is 0 the reference is now weak and the object may be GC'd -// at any time if there are no other references. Calling this when the -// refcount is already 0 results in an error. -NAPI_EXTERN napi_status napi_reference_unref(napi_env env, - napi_ref ref, - uint32_t* result); - -// Attempts to get a referenced value. If the reference is weak, -// the value might no longer be available, in that case the call -// is still successful but the result is NULL. -NAPI_EXTERN napi_status napi_get_reference_value(napi_env env, - napi_ref ref, - napi_value* result); - -NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, - napi_handle_scope* result); -NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, - napi_handle_scope scope); -NAPI_EXTERN napi_status -napi_open_escapable_handle_scope(napi_env env, - napi_escapable_handle_scope* result); -NAPI_EXTERN napi_status -napi_close_escapable_handle_scope(napi_env env, - napi_escapable_handle_scope scope); - -NAPI_EXTERN napi_status napi_escape_handle(napi_env env, - napi_escapable_handle_scope scope, - napi_value escapee, - napi_value* result); - -// Methods to support error handling -NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error); -NAPI_EXTERN napi_status napi_throw_error(napi_env env, - const char* code, - const char* msg); -NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, - const char* code, - const char* msg); -NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, - const char* code, - const char* msg); -NAPI_EXTERN napi_status napi_is_error(napi_env env, - napi_value value, - bool* result); - -// Methods to support catching exceptions -NAPI_EXTERN napi_status napi_is_exception_pending(napi_env env, bool* result); -NAPI_EXTERN napi_status napi_get_and_clear_last_exception(napi_env env, - napi_value* result); - -// Methods to provide node::Buffer functionality with napi types -NAPI_EXTERN napi_status napi_create_buffer(napi_env env, - size_t length, - void** data, - napi_value* result); -NAPI_EXTERN napi_status napi_create_external_buffer(napi_env env, - size_t length, - void* data, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result); -NAPI_EXTERN napi_status napi_create_buffer_copy(napi_env env, - size_t length, - const void* data, - void** result_data, - napi_value* result); -NAPI_EXTERN napi_status napi_is_buffer(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_get_buffer_info(napi_env env, - napi_value value, - void** data, - size_t* length); - -// Methods to work with array buffers and typed arrays -NAPI_EXTERN napi_status napi_is_arraybuffer(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_create_arraybuffer(napi_env env, - size_t byte_length, - void** data, - napi_value* result); -NAPI_EXTERN napi_status -napi_create_external_arraybuffer(napi_env env, - void* external_data, - size_t byte_length, - napi_finalize finalize_cb, - void* finalize_hint, - napi_value* result); -NAPI_EXTERN napi_status napi_get_arraybuffer_info(napi_env env, - napi_value arraybuffer, - void** data, - size_t* byte_length); -NAPI_EXTERN napi_status napi_is_typedarray(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_create_typedarray(napi_env env, - napi_typedarray_type type, - size_t length, - napi_value arraybuffer, - size_t byte_offset, - napi_value* result); -NAPI_EXTERN napi_status napi_get_typedarray_info(napi_env env, - napi_value typedarray, - napi_typedarray_type* type, - size_t* length, - void** data, - napi_value* arraybuffer, - size_t* byte_offset); - -NAPI_EXTERN napi_status napi_create_dataview(napi_env env, - size_t length, - napi_value arraybuffer, - size_t byte_offset, - napi_value* result); -NAPI_EXTERN napi_status napi_is_dataview(napi_env env, - napi_value value, - bool* result); -NAPI_EXTERN napi_status napi_get_dataview_info(napi_env env, - napi_value dataview, - size_t* bytelength, - void** data, - napi_value* arraybuffer, - size_t* byte_offset); - -// Methods to manage simple async operations -NAPI_EXTERN -napi_status napi_create_async_work(napi_env env, - napi_value async_resource, - napi_value async_resource_name, - napi_async_execute_callback execute, - napi_async_complete_callback complete, - void* data, - napi_async_work* result); -NAPI_EXTERN napi_status napi_delete_async_work(napi_env env, - napi_async_work work); -NAPI_EXTERN napi_status napi_queue_async_work(napi_env env, - napi_async_work work); -NAPI_EXTERN napi_status napi_cancel_async_work(napi_env env, - napi_async_work work); - -// Methods for custom handling of async operations -NAPI_EXTERN napi_status napi_async_init(napi_env env, - napi_value async_resource, - napi_value async_resource_name, - napi_async_context* result); - -NAPI_EXTERN napi_status napi_async_destroy(napi_env env, - napi_async_context async_context); - -NAPI_EXTERN napi_status napi_make_callback(napi_env env, - napi_async_context async_context, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); - -// version management -NAPI_EXTERN napi_status napi_get_version(napi_env env, uint32_t* result); - -NAPI_EXTERN -napi_status napi_get_node_version(napi_env env, - const napi_node_version** version); - -// Promises -NAPI_EXTERN napi_status napi_create_promise(napi_env env, - napi_deferred* deferred, - napi_value* promise); -NAPI_EXTERN napi_status napi_resolve_deferred(napi_env env, - napi_deferred deferred, - napi_value resolution); -NAPI_EXTERN napi_status napi_reject_deferred(napi_env env, - napi_deferred deferred, - napi_value rejection); -NAPI_EXTERN napi_status napi_is_promise(napi_env env, - napi_value promise, - bool* is_promise); - -// Memory management -NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, - int64_t change_in_bytes, - int64_t* adjusted_value); - -// Runnig a script -NAPI_EXTERN napi_status napi_run_script(napi_env env, - napi_value script, - napi_value* result); - -EXTERN_C_END - -#endif // SRC_NODE_API_H_ diff --git a/node_modules/node-addon-api/src/node_api_types.h b/node_modules/node-addon-api/src/node_api_types.h deleted file mode 100644 index 230c1f4..0000000 --- a/node_modules/node-addon-api/src/node_api_types.h +++ /dev/null @@ -1,115 +0,0 @@ -#ifndef SRC_NODE_API_TYPES_H_ -#define SRC_NODE_API_TYPES_H_ - -#include <stddef.h> -#include <stdint.h> - -#if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900) - typedef uint16_t char16_t; -#endif - -// JSVM API types are all opaque pointers for ABI stability -// typedef undefined structs instead of void* for compile time type safety -typedef struct napi_env__ *napi_env; -typedef struct napi_value__ *napi_value; -typedef struct napi_ref__ *napi_ref; -typedef struct napi_handle_scope__ *napi_handle_scope; -typedef struct napi_escapable_handle_scope__ *napi_escapable_handle_scope; -typedef struct napi_callback_info__ *napi_callback_info; -typedef struct napi_async_context__ *napi_async_context; -typedef struct napi_async_work__ *napi_async_work; -typedef struct napi_deferred__ *napi_deferred; - -typedef enum { - napi_default = 0, - napi_writable = 1 << 0, - napi_enumerable = 1 << 1, - napi_configurable = 1 << 2, - - // Used with napi_define_class to distinguish static properties - // from instance properties. Ignored by napi_define_properties. - napi_static = 1 << 10, -} napi_property_attributes; - -typedef enum { - // ES6 types (corresponds to typeof) - napi_undefined, - napi_null, - napi_boolean, - napi_number, - napi_string, - napi_symbol, - napi_object, - napi_function, - napi_external, -} napi_valuetype; - -typedef enum { - napi_int8_array, - napi_uint8_array, - napi_uint8_clamped_array, - napi_int16_array, - napi_uint16_array, - napi_int32_array, - napi_uint32_array, - napi_float32_array, - napi_float64_array, -} napi_typedarray_type; - -typedef enum { - napi_ok, - napi_invalid_arg, - napi_object_expected, - napi_string_expected, - napi_name_expected, - napi_function_expected, - napi_number_expected, - napi_boolean_expected, - napi_array_expected, - napi_generic_failure, - napi_pending_exception, - napi_cancelled, - napi_escape_called_twice, - napi_handle_scope_mismatch -} napi_status; - -typedef napi_value (*napi_callback)(napi_env env, - napi_callback_info info); -typedef void (*napi_finalize)(napi_env env, - void* finalize_data, - void* finalize_hint); -typedef void (*napi_async_execute_callback)(napi_env env, - void* data); -typedef void (*napi_async_complete_callback)(napi_env env, - napi_status status, - void* data); - -typedef struct { - // One of utf8name or name should be NULL. - const char* utf8name; - napi_value name; - - napi_callback method; - napi_callback getter; - napi_callback setter; - napi_value value; - - napi_property_attributes attributes; - void* data; -} napi_property_descriptor; - -typedef struct { - const char* error_message; - void* engine_reserved; - uint32_t engine_error_code; - napi_status error_code; -} napi_extended_error_info; - -typedef struct { - uint32_t major; - uint32_t minor; - uint32_t patch; - const char* release; -} napi_node_version; - -#endif // SRC_NODE_API_TYPES_H_ diff --git a/node_modules/node-addon-api/src/node_internals.cc b/node_modules/node-addon-api/src/node_internals.cc deleted file mode 100644 index c4a7dd8..0000000 --- a/node_modules/node-addon-api/src/node_internals.cc +++ /dev/null @@ -1,142 +0,0 @@ -#include "node_internals.h" -#include <stdlib.h> -#include <cstdarg> -#include <vector> -#include "uv.h" - -#if defined(_MSC_VER) -#define getpid GetCurrentProcessId -#else -#include <unistd.h> // getpid -#endif - -#if NODE_MAJOR_VERSION < 8 || NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION < 6 -CallbackScope::CallbackScope(void *work) { -} -#endif // NODE_MAJOR_VERSION < 8 - -namespace node { - -#if NODE_MAJOR_VERSION < 8 - -async_context EmitAsyncInit(v8::Isolate* isolate, - v8::Local<v8::Object> resource, - v8::Local<v8::String> name, - async_id trigger_async_id) { - return async_context(); -} - -void EmitAsyncDestroy(v8::Isolate* isolate, - async_context asyncContext) { -} - -AsyncResource::AsyncResource(v8::Isolate* isolate, - v8::Local<v8::Object> object, - const char *name) { -} - -#endif // NODE_MAJOR_VERSION < 8 - -#if NODE_MAJOR_VERSION < 8 || NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION < 6 - -v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate, - v8::Local<v8::Object> recv, - v8::Local<v8::Function> callback, - int argc, - v8::Local<v8::Value>* argv, - async_context asyncContext) { - return node::MakeCallback(isolate, recv, callback, argc, argv); -} - -#endif // NODE_MAJOR_VERSION < 8 || NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION < 6 - -static void PrintErrorString(const char* format, ...) { - va_list ap; - va_start(ap, format); -#ifdef _WIN32 - HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE); - - // Check if stderr is something other than a tty/console - if (stderr_handle == INVALID_HANDLE_VALUE || - stderr_handle == nullptr || - uv_guess_handle(_fileno(stderr)) != UV_TTY) { - vfprintf(stderr, format, ap); - va_end(ap); - return; - } - - // Fill in any placeholders - int n = _vscprintf(format, ap); - std::vector<char> out(n + 1); - vsprintf(out.data(), format, ap); - - // Get required wide buffer size - n = MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, nullptr, 0); - - std::vector<wchar_t> wbuf(n); - MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, wbuf.data(), n); - - // Don't include the null character in the output - CHECK_GT(n, 0); - WriteConsoleW(stderr_handle, wbuf.data(), n - 1, nullptr, nullptr); -#else - vfprintf(stderr, format, ap); -#endif - va_end(ap); -} - -void DumpBacktrace(FILE* fp) { -} - -NO_RETURN void Abort() { - DumpBacktrace(stderr); - fflush(stderr); - ABORT_NO_BACKTRACE(); -} - -NO_RETURN void Assert(const char* const (*args)[4]) { - auto filename = (*args)[0]; - auto linenum = (*args)[1]; - auto message = (*args)[2]; - auto function = (*args)[3]; - - char exepath[256]; - size_t exepath_size = sizeof(exepath); - if (uv_exepath(exepath, &exepath_size)) - snprintf(exepath, sizeof(exepath), "node"); - - char pid[12] = {0}; - snprintf(pid, sizeof(pid), "[%u]", getpid()); - - fprintf(stderr, "%s%s: %s:%s:%s%s Assertion `%s' failed.\n", - exepath, pid, filename, linenum, - function, *function ? ":" : "", message); - fflush(stderr); - - Abort(); -} - -static void OnFatalError(const char* location, const char* message) { - if (location) { - PrintErrorString("FATAL ERROR: %s %s\n", location, message); - } else { - PrintErrorString("FATAL ERROR: %s\n", message); - } - fflush(stderr); - ABORT(); -} - -NO_RETURN void FatalError(const char* location, const char* message) { - OnFatalError(location, message); - // to suppress compiler warning - ABORT(); -} - -} // namespace node - -#if NODE_MAJOR_VERSION < 6 -v8::Local<v8::Name> v8::Private::ForApi(v8::Isolate* isolate, - v8::Local<v8::String> key) { - return v8::Symbol::ForApi(isolate, key); -} -#endif // NODE_MAJOR_VERSION < 6 diff --git a/node_modules/node-addon-api/src/node_internals.h b/node_modules/node-addon-api/src/node_internals.h deleted file mode 100644 index bacccff..0000000 --- a/node_modules/node-addon-api/src/node_internals.h +++ /dev/null @@ -1,157 +0,0 @@ -#ifndef SRC_NODE_INTERNALS_H_ -#define SRC_NODE_INTERNALS_H_ - -// -// This is a stripped down shim to allow node_api.cc to build outside of the node source tree. -// - -#include "node_version.h" -#include "util-inl.h" -#include <stdio.h> -#include <stdint.h> -#include "uv.h" -#include "node.h" -#include <string> - -// Windows 8+ does not like abort() in Release mode -#ifdef _WIN32 -#define ABORT_NO_BACKTRACE() raise(SIGABRT) -#else -#define ABORT_NO_BACKTRACE() abort() -#endif - -#define ABORT() node::Abort() - -#ifdef __GNUC__ -#define LIKELY(expr) __builtin_expect(!!(expr), 1) -#define UNLIKELY(expr) __builtin_expect(!!(expr), 0) -#define PRETTY_FUNCTION_NAME __PRETTY_FUNCTION__ -#else -#define LIKELY(expr) expr -#define UNLIKELY(expr) expr -#define PRETTY_FUNCTION_NAME "" -#endif - -#define STRINGIFY_(x) #x -#define STRINGIFY(x) STRINGIFY_(x) - -#define CHECK(expr) \ - do { \ - if (UNLIKELY(!(expr))) { \ - static const char* const args[] = { __FILE__, STRINGIFY(__LINE__), \ - #expr, PRETTY_FUNCTION_NAME }; \ - node::Assert(&args); \ - } \ - } while (0) - -#define CHECK_EQ(a, b) CHECK((a) == (b)) -#define CHECK_GE(a, b) CHECK((a) >= (b)) -#define CHECK_GT(a, b) CHECK((a) > (b)) -#define CHECK_LE(a, b) CHECK((a) <= (b)) -#define CHECK_LT(a, b) CHECK((a) < (b)) -#define CHECK_NE(a, b) CHECK((a) != (b)) - -#ifdef __GNUC__ -#define NO_RETURN __attribute__((noreturn)) -#else -#define NO_RETURN -#endif - -#ifndef NODE_RELEASE -#define NODE_RELEASE "node" -#endif - -#if NODE_MAJOR_VERSION < 8 || NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION < 6 -class CallbackScope { - public: - CallbackScope(void *work); -}; -#endif // NODE_MAJOR_VERSION < 8 - -namespace node { - -// Copied from Node.js' src/node_persistent.h -template <typename T> -struct ResetInDestructorPersistentTraits { - static const bool kResetInDestructor = true; - template <typename S, typename M> - // Disallow copy semantics by leaving this unimplemented. - inline static void Copy( - const v8::Persistent<S, M>&, - v8::Persistent<T, ResetInDestructorPersistentTraits<T>>*); -}; - -// v8::Persistent does not reset the object slot in its destructor. That is -// acknowledged as a flaw in the V8 API and expected to change in the future -// but for now node::Persistent is the easier and safer alternative. -template <typename T> -using Persistent = v8::Persistent<T, ResetInDestructorPersistentTraits<T>>; - -#if NODE_MAJOR_VERSION < 8 || NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION < 2 -typedef int async_id; - -typedef struct async_context { - node::async_id async_id; - node::async_id trigger_async_id; -} async_context; -#endif // NODE_MAJOR_VERSION < 8.2 - -#if NODE_MAJOR_VERSION < 8 || NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION < 6 -NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, - v8::Local<v8::Object> resource, - v8::Local<v8::String> name, - async_id trigger_async_id = -1); - -NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate, - async_context asyncContext); - -v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate, - v8::Local<v8::Object> recv, - v8::Local<v8::Function> callback, - int argc, - v8::Local<v8::Value>* argv, - async_context asyncContext); - -#if NODE_MAJOR_VERSION < 8 -class AsyncResource { - public: - AsyncResource(v8::Isolate* isolate, - v8::Local<v8::Object> object, - const char *name); -}; -#endif // node version below 8 - -#endif // node version below 8.6 - -// The slightly odd function signature for Assert() is to ease -// instruction cache pressure in calls from ASSERT and CHECK. -NO_RETURN void Abort(); -NO_RETURN void Assert(const char* const (*args)[4]); -void DumpBacktrace(FILE* fp); - -template <typename T, size_t N> -constexpr size_t arraysize(const T(&)[N]) { return N; } - -NO_RETURN void FatalError(const char* location, const char* message); - -} // namespace node - -#if NODE_MAJOR_VERSION < 8 -#define NewTarget This -#endif // NODE_MAJOR_VERSION < 8 - -#if NODE_MAJOR_VERSION < 6 -namespace v8 { - namespace Private { - v8::Local<v8::Name> ForApi(v8::Isolate* isolate, v8::Local<v8::String> key); - } -} -#define GetPrivate(context, key) Get((context), (key)) -#define SetPrivate(context, key, value) \ - DefineOwnProperty((context), (key), (value), \ - static_cast<v8::PropertyAttribute>(v8::DontEnum | \ - v8::DontDelete | \ - v8::ReadOnly)) -#endif // NODE_MAJOR_VERSION < 6 - -#endif // SRC_NODE_INTERNALS_H_ diff --git a/node_modules/node-addon-api/src/nothing.c b/node_modules/node-addon-api/src/nothing.c deleted file mode 100644 index e69de29..0000000 --- a/node_modules/node-addon-api/src/nothing.c +++ /dev/null diff --git a/node_modules/node-addon-api/src/util-inl.h b/node_modules/node-addon-api/src/util-inl.h deleted file mode 100644 index 30aad16..0000000 --- a/node_modules/node-addon-api/src/util-inl.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef SRC_UTIL_INL_H_ -#define SRC_UTIL_INL_H_ - -#include "util.h" -#include "v8.h" - -namespace node { - -inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, - const char* data, - int length) { - return v8::String::NewFromOneByte(isolate, - reinterpret_cast<const uint8_t*>(data), - v8::NewStringType::kNormal, - length).ToLocalChecked(); -} - -inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, - const signed char* data, - int length) { - return v8::String::NewFromOneByte(isolate, - reinterpret_cast<const uint8_t*>(data), - v8::NewStringType::kNormal, - length).ToLocalChecked(); -} - -inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, - const unsigned char* data, - int length) { - return v8::String::NewFromOneByte(isolate, - reinterpret_cast<const uint8_t*>(data), - v8::NewStringType::kNormal, - length).ToLocalChecked(); -} - -} // namespace node - -#endif // SRC_UTIL_INL_H_ diff --git a/node_modules/node-addon-api/src/util.h b/node_modules/node-addon-api/src/util.h deleted file mode 100644 index 6765bc1..0000000 --- a/node_modules/node-addon-api/src/util.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef SRC_UTIL_H_ -#define SRC_UTIL_H_ - -#define FIXED_ONE_BYTE_STRING(isolate, string) \ - (node::OneByteString((isolate), (string), sizeof(string) - 1)) - -#endif // SRC_UTIL_H_ diff --git a/node_modules/node-addon-api/tools/README.md b/node_modules/node-addon-api/tools/README.md deleted file mode 100644 index b71e5d9..0000000 --- a/node_modules/node-addon-api/tools/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# Migration Script - -The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. - -### How To Use - -To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. -``` -npm install node-addon-api -``` - -Then run the script passing your project directory -``` -node ./node_modules/node-addon-api/tools/conversion.js ./ -``` - -After finish, recompile and debug things that are missed by the script. - - -### Quick Fixes -Here is the list of things that can be fixed easily. - 1. Change your methods' return value to void if it doesn't return value to JavaScript. - 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. - 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); - - -### Major Reconstructions -The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. - -So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. - - 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as -``` -[ClassName](const Napi::CallbackInfo& info); -``` -and define it as -``` -[ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ - ... -} -``` -This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. - - 2. Move your original constructor code into the new constructor. Delete your original constructor. - 3. In your class initialization function, associate native methods in the following way. The `&` character before methods is required because they are not static methods but instance methods. -``` -Napi::FunctionReference constructor; - -void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { - Napi::HandleScope scope(env); - Napi::Function ctor = DefineClass(env, "Canvas", { - InstanceMethod("Func1", &[ClassName]::Func1), - InstanceMethod("Func2", &[ClassName]::Func2), - InstanceAccessor("Value", &[ClassName]::ValueGetter), - StaticMethod("MethodName", &[ClassName]::StaticMethod), - InstanceValue("Value", Napi::[Type]::New(env, value)), - }); - - constructor = Napi::Persistent(ctor); - constructor .SuppressDestruct(); - exports.Set("[ClassName]", ctor); -} -``` - 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. - - -If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. diff --git a/node_modules/node-addon-api/tools/check-napi.js b/node_modules/node-addon-api/tools/check-napi.js deleted file mode 100644 index 48fdfc0..0000000 --- a/node_modules/node-addon-api/tools/check-napi.js +++ /dev/null @@ -1,100 +0,0 @@ -'use strict'; -// Descend into a directory structure and, for each file matching *.node, output -// based on the imports found in the file whether it's an N-API module or not. - -const fs = require('fs'); -const path = require('path'); -const child_process = require('child_process'); - -// Read the output of the command, break it into lines, and use the reducer to -// decide whether the file is an N-API module or not. -function checkFile(file, command, argv, reducer) { - const child = child_process.spawn(command, argv, { - stdio: ['inherit', 'pipe', 'inherit'] - }); - let leftover = ''; - let isNapi = undefined; - child.stdout.on('data', (chunk) => { - if (isNapi === undefined) { - chunk = (leftover + chunk.toString()).split(/[\r\n]+/); - leftover = chunk.pop(); - isNapi = chunk.reduce(reducer, isNapi); - if (isNapi !== undefined) { - child.kill(); - } - } - }); - child.on('close', (code, signal) => { - if ((code === null && signal !== null) || (code !== 0)) { - console.log( - command + ' exited with code: ' + code + ' and signal: ' + signal); - } else { - // Green if it's a N-API module, red otherwise. - console.log( - '\x1b[' + (isNapi ? '42' : '41') + 'm' + - (isNapi ? ' N-API' : 'Not N-API') + - '\x1b[0m: ' + file); - } - }); -} - -// Use nm -a to list symbols. -function checkFileUNIX(file) { - checkFile(file, 'nm', ['-a', file], (soFar, line) => { - if (soFar === undefined) { - line = line.match(/([0-9a-f]*)? ([a-zA-Z]) (.*$)/); - if (line[2] === 'U') { - if (/^napi/.test(line[3])) { - soFar = true; - } - } - } - return soFar; - }); -} - -// Use dumpbin /imports to list symbols. -function checkFileWin32(file) { - checkFile(file, 'dumpbin', ['/imports', file], (soFar, line) => { - if (soFar === undefined) { - line = line.match(/([0-9a-f]*)? +([a-zA-Z0-9]) (.*$)/); - if (line && /^napi/.test(line[line.length - 1])) { - soFar = true; - } - } - return soFar; - }); -} - -// Descend into a directory structure and pass each file ending in '.node' to -// one of the above checks, depending on the OS. -function recurse(top) { - fs.readdir(top, (error, items) => { - if (error) { - throw ("error reading directory " + top + ": " + error); - } - items.forEach((item) => { - item = path.join(top, item); - fs.stat(item, ((item) => (error, stats) => { - if (error) { - throw ("error about " + item + ": " + error); - } - if (stats.isDirectory()) { - recurse(item); - } else if (/[.]node$/.test(item) && - // Explicitly ignore files called 'nothing.node' because they are - // artefacts of node-addon-api having identified a version of - // Node.js that ships with a correct implementation of N-API. - path.basename(item) !== 'nothing.node') { - process.platform === 'win32' ? - checkFileWin32(item) : - checkFileUNIX(item); - } - })(item)); - }); - }); -} - -// Start with the directory given on the command line or the current directory -// if nothing was given. -recurse(process.argv.length > 3 ? process.argv[2] : '.'); diff --git a/node_modules/node-addon-api/tools/conversion.js b/node_modules/node-addon-api/tools/conversion.js deleted file mode 100644 index 35afc21..0000000 --- a/node_modules/node-addon-api/tools/conversion.js +++ /dev/null @@ -1,313 +0,0 @@ -#! /usr/bin/env node - -'use strict' - -const fs = require('fs'); -const path = require('path'); - -const args = process.argv.slice(2); -const dir = args[0]; -if (!dir) { - console.log('Usage: node ' + path.basename(__filename) + ' <target-dir>'); - process.exit(1); -} - -const NodeApiVersion = require('../package.json').version; - -const disable = args[1]; -if (disable != "--disable" && dir != "--disable") { - var ConfigFileOperations = { - 'package.json': [ - [ /([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'], - [ /[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, '' ] - ], - 'binding.gyp': [ - [ /([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'<!@(node -p "require(\\\'node-addon-api\\\').include")\',' ], - [ /([ ]*)"include_dirs": \[/g, '$1"include_dirs": [\n$1 "<!@(node -p \\"require(\'node-addon-api\').include\\")",' ], - [ /([ ]*)'dependencies': \[/g, '$1\'dependencies\': [\n$1 \'<!(node -p "require(\\\'node-addon-api\\\').gyp")\','], - [ /([ ]*)"dependencies": \[/g, '$1"dependencies": [\n$1 "<!(node -p \'require(\\\"node-addon-api\\\").gyp\')",'], - [ /[ ]*("|')<!\(node -e ("|'|\\"|\\')require\(("|'|\\"|\\')nan("|'|\\"|\\')\)("|'|\\"|\\')\)("|')(,|)[\r\n]/g, '' ], - [ /([ ]*)("|')target_name("|'): ("|')(.+?)("|'),/g, '$1$2target_name$2: $4$5$6,\n $2cflags!$2: [ $2-fno-exceptions$2 ],\n $2cflags_cc!$2: [ $2-fno-exceptions$2 ],\n $2xcode_settings$2: { $2GCC_ENABLE_CPP_EXCEPTIONS$2: $2YES$2,\n $2CLANG_CXX_LIBRARY$2: $2libc++$2,\n $2MACOSX_DEPLOYMENT_TARGET$2: $210.7$2,\n },\n $2msvs_settings$2: {\n $2VCCLCompilerTool$2: { $2ExceptionHandling$2: 1 },\n },' ], - ] - }; -} else { - var ConfigFileOperations = { - 'package.json': [ - [ /([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'], - [ /[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, '' ] - ], - 'binding.gyp': [ - [ /([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'<!@(node -p "require(\\\'node-addon-api\\\').include")\',' ], - [ /([ ]*)"include_dirs": \[/g, '$1"include_dirs": [\n$1 "<!@(node -p \'require(\\\"node-addon-api\\\").include\')",' ], - [ /([ ]*)'dependencies': \[/g, '$1\'dependencies\': [\n$1 \'<!(node -p "require(\\\'node-addon-api\\\').gyp")\','], - [ /([ ]*)"dependencies": \[/g, '$1"dependencies": [\n$1 "<!(node -p \'require(\\\"node-addon-api\\\").gyp\')",'], - [ /[ ]*("|')<!\(node -e ("|'|\\"|\\')require\(("|'|\\"|\\')nan("|'|\\"|\\')\)("|'|\\"|\\')\)("|')(,|)[\r\n]/g, '' ], - [ /([ ]*)("|')target_name("|'): ("|')(.+?)("|'),/g, '$1$2target_name$2: $4$5$6,\n $2cflags!$2: [ $2-fno-exceptions$2 ],\n $2cflags_cc!$2: [ $2-fno-exceptions$2 ],\n $2defines$2: [ $2NAPI_DISABLE_CPP_EXCEPTIONS$2 ],\n $2conditions$2: [\n [\'OS==\"win\"\', { $2defines$2: [ $2_HAS_EXCEPTIONS=1$2 ] }]\n ]' ], - ] - }; -} - -var SourceFileOperations = [ - [ /Nan::SetMethod\(target,[\s]*\"(.*)\"[\s]*,[\s]*([^)]+)\)/g, 'exports.Set(Napi::String::New(env, \"$1\"), Napi::Function::New(env, $2))' ], - - [ /v8::Local<v8::FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {' ], - [ /Local<FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);\s+(\w+)\.Reset\((\1)\);\s+\1->SetClassName\((Nan::String::New|Nan::New<(v8::)*String>)\("(.+?)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$6", {'], - [ /Local<FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {' ], - [ /Nan::New<v8::FunctionTemplate>\(([\w\d:]+)\)->GetFunction\(\)/g, 'Napi::Function::New(env, $1)' ], - [ /Nan::New<FunctionTemplate>\(([\w\d:]+)\)->GetFunction()/g, 'Napi::Function::New(env, $1);' ], - [ /Nan::New<v8::FunctionTemplate>\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)' ], - [ /Nan::New<FunctionTemplate>\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)' ], - - // FunctionTemplate to FunctionReference - [ /Nan::Persistent<(v8::)*FunctionTemplate>/g, 'Napi::FunctionReference' ], - [ /Nan::Persistent<(v8::)*Function>/g, 'Napi::FunctionReference' ], - [ /v8::Local<v8::FunctionTemplate>/g, 'Napi::FunctionReference' ], - [ /Local<FunctionTemplate>/g, 'Napi::FunctionReference' ], - [ /v8::FunctionTemplate/g, 'Napi::FunctionReference' ], - [ /FunctionTemplate/g, 'Napi::FunctionReference' ], - - - [ /([ ]*)Nan::SetPrototypeMethod\(\w+, "(\w+)", (\w+)\);/g, '$1InstanceMethod("$2", &$3),' ], - [ /([ ]*)(?:\w+\.Reset\(\w+\);\s+)?\(target\)\.Set\("(\w+)",\s*Nan::GetFunction\((\w+)\)\);/gm, - '});\n\n' + - '$1constructor = Napi::Persistent($3);\n' + - '$1constructor.SuppressDestruct();\n' + - '$1target.Set("$2", $3);' ], - - - // TODO: Other attribute combinations - [ /static_cast<PropertyAttribute>\(ReadOnly\s*\|\s*DontDelete\)/gm, - 'static_cast<napi_property_attributes>(napi_enumerable | napi_configurable)' ], - - [ /([\w\d:<>]+?)::Cast\((.+?)\)/g, '$2.As<$1>()' ], - - [ /\*Nan::Utf8String\(([^)]+)\)/g, '$1->As<Napi::String>().Utf8Value().c_str()' ], - [ /Nan::Utf8String +(\w+)\(([^)]+)\)/g, 'std::string $1 = $2.As<Napi::String>()' ], - [ /Nan::Utf8String/g, 'std::string' ], - - [ /v8::String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)' ], - [ /String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)' ], - [ /\.length\(\)/g, '.Length()' ], - - [ /Nan::MakeCallback\(([^,]+),[\s\\]+([^,]+),/gm, '$2.MakeCallback($1,' ], - - [ /class\s+(\w+)\s*:\s*public\s+Nan::ObjectWrap/g, 'class $1 : public Napi::ObjectWrap<$1>' ], - [ /(\w+)\(([^\)]*)\)\s*:\s*Nan::ObjectWrap\(\)\s*(,)?/gm, '$1($2) : Napi::ObjectWrap<$1>()$3' ], - - // HandleOKCallback to OnOK - [ /HandleOKCallback/g, 'OnOK' ], - // HandleErrorCallback to OnError - [ /HandleErrorCallback/g, 'OnError' ], - - // ex. .As<Function>() to .As<Napi::Object>() - [ /\.As<v8::(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As<Napi::$1>()' ], - [ /\.As<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As<Napi::$1>()' ], - - // ex. Nan::New<Number>(info[0]) to Napi::Number::New(info[0]) - [ /Nan::New<(v8::)*Integer>\((.+?)\)/g, 'Napi::Number::New(env, $2)' ], - [ /Nan::New\(([0-9\.]+)\)/g, 'Napi::Number::New(env, $1)' ], - [ /Nan::New<(v8::)*String>\("(.+?)"\)/g, 'Napi::String::New(env, "$2")' ], - [ /Nan::New\("(.+?)"\)/g, 'Napi::String::New(env, "$1")' ], - [ /Nan::New<(v8::)*(.+?)>\(\)/g, 'Napi::$2::New(env)' ], - [ /Nan::New<(.+?)>\(\)/g, 'Napi::$1::New(env)' ], - [ /Nan::New<(v8::)*(.+?)>\(/g, 'Napi::$2::New(env, ' ], - [ /Nan::New<(.+?)>\(/g, 'Napi::$1::New(env, ' ], - [ /Nan::NewBuffer\(/g, 'Napi::Buffer<char>::New(env, ' ], - // TODO: Properly handle this - [ /Nan::New\(/g, 'Napi::New(env, ' ], - - [ /\.IsInt32\(\)/g, '.IsNumber()' ], - [ /->IsInt32\(\)/g, '.IsNumber()' ], - - - [ /(.+?)->BooleanValue\(\)/g, '$1.As<Napi::Boolean>().Value()' ], - [ /(.+?)->Int32Value\(\)/g, '$1.As<Napi::Number>().Int32Value()' ], - [ /(.+?)->Uint32Value\(\)/g, '$1.As<Napi::Number>().Uint32Value()' ], - [ /(.+?)->IntegerValue\(\)/g, '$1.As<Napi::Number>().Int64Value()' ], - [ /(.+?)->NumberValue\(\)/g, '$1.As<Napi::Number>().DoubleValue()' ], - - // ex. Nan::To<bool>(info[0]) to info[0].Value() - [ /Nan::To<v8::(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To<Napi::$1>()' ], - [ /Nan::To<(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To<Napi::$1>()' ], - // ex. Nan::To<bool>(info[0]) to info[0].As<Napi::Boolean>().Value() - [ /Nan::To<bool>\((.+?)\)/g, '$1.As<Napi::Boolean>().Value()' ], - // ex. Nan::To<int>(info[0]) to info[0].As<Napi::Number>().Int32Value() - [ /Nan::To<int>\((.+?)\)/g, '$1.As<Napi::Number>().Int32Value()' ], - // ex. Nan::To<int32_t>(info[0]) to info[0].As<Napi::Number>().Int32Value() - [ /Nan::To<int32_t>\((.+?)\)/g, '$1.As<Napi::Number>().Int32Value()' ], - // ex. Nan::To<uint32_t>(info[0]) to info[0].As<Napi::Number>().Uint32Value() - [ /Nan::To<uint32_t>\((.+?)\)/g, '$1.As<Napi::Number>().Uint32Value()' ], - // ex. Nan::To<int64_t>(info[0]) to info[0].As<Napi::Number>().Int64Value() - [ /Nan::To<int64_t>\((.+?)\)/g, '$1.As<Napi::Number>().Int64Value()' ], - // ex. Nan::To<float>(info[0]) to info[0].As<Napi::Number>().FloatValue() - [ /Nan::To<float>\((.+?)\)/g, '$1.As<Napi::Number>().FloatValue()' ], - // ex. Nan::To<double>(info[0]) to info[0].As<Napi::Number>().DoubleValue() - [ /Nan::To<double>\((.+?)\)/g, '$1.As<Napi::Number>().DoubleValue()' ], - - [ /Nan::New\((\w+)\)->HasInstance\((\w+)\)/g, '$2.InstanceOf($1.Value())' ], - - [ /Nan::Has\(([^,]+),\s*/gm, '($1).Has(' ], - [ /\.Has\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Has($1)' ], - [ /\.Has\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Has($1)' ], - - [ /Nan::Get\(([^,]+),\s*/gm, '($1).Get(' ], - [ /\.Get\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Get($1)' ], - [ /\.Get\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Get($1)' ], - - [ /Nan::Set\(([^,]+),\s*/gm, '($1).Set(' ], - [ /\.Set\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\s*,/gm, '.Set($1,' ], - [ /\.Set\([\s|\\]*Nan::New\(([^)]+)\)\s*,/gm, '.Set($1,' ], - - - // ex. node::Buffer::HasInstance(info[0]) to info[0].IsBuffer() - [ /node::Buffer::HasInstance\((.+?)\)/g, '$1.IsBuffer()' ], - // ex. node::Buffer::Length(info[0]) to info[0].Length() - [ /node::Buffer::Length\((.+?)\)/g, '$1.As<Napi::Buffer<char>>().Length()' ], - // ex. node::Buffer::Data(info[0]) to info[0].Data() - [ /node::Buffer::Data\((.+?)\)/g, '$1.As<Napi::Buffer<char>>().Data()' ], - [ /Nan::CopyBuffer\(/g, 'Napi::Buffer::Copy(env, ' ], - - // Nan::AsyncQueueWorker(worker) - [ /Nan::AsyncQueueWorker\((.+)\);/g, '$1.Queue();' ], - [ /Nan::(Undefined|Null|True|False)\(\)/g, 'env.$1()' ], - - // Nan::ThrowError(error) to Napi::Error::New(env, error).ThrowAsJavaScriptException() - [ /([ ]*)return Nan::Throw(\w*?)Error\((.+?)\);/g, '$1Napi::$2Error::New(env, $3).ThrowAsJavaScriptException();\n$1return env.Null();' ], - [ /Nan::Throw(\w*?)Error\((.+?)\);\n(\s*)return;/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n$3return env.Null();' ], - [ /Nan::Throw(\w*?)Error\((.+?)\);/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n' ], - // Nan::RangeError(error) to Napi::RangeError::New(env, error) - [ /Nan::(\w*?)Error\((.+)\)/g, 'Napi::$1Error::New(env, $2)' ], - - [ /Nan::Set\((.+?),\n* *(.+?),\n* *(.+?),\n* *(.+?)\)/g, '$1.Set($2, $3, $4)' ], - - [ /Nan::(Escapable)?HandleScope\s+(\w+)\s*;/g, 'Napi::$1HandleScope $2(env);' ], - [ /Nan::(Escapable)?HandleScope/g, 'Napi::$1HandleScope' ], - [ /Nan::ForceSet\(([^,]+), ?/g, '$1->DefineProperty(' ], - [ /\.ForceSet\(Napi::String::New\(env, "(\w+)"\),\s*?/g, '.DefineProperty("$1", ' ], - // [ /Nan::GetPropertyNames\(([^,]+)\)/, '$1->GetPropertyNames()' ], - [ /Nan::Equals\(([^,]+),/g, '$1.StrictEquals(' ], - - - [ /(.+)->Set\(/g, '$1.Set\(' ], - - - [ /Nan::Callback/g, 'Napi::FunctionReference' ], - - - [ /Nan::Persistent<Object>/g, 'Napi::ObjectReference' ], - [ /Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target/g, 'Napi::Env& env, Napi::Object& target' ], - - [ /(\w+)\*\s+(\w+)\s*=\s*Nan::ObjectWrap::Unwrap<\w+>\(info\.This\(\)\);/g, '$1* $2 = this;' ], - [ /Nan::ObjectWrap::Unwrap<(\w+)>\((.*)\);/g, '$2.Unwrap<$1>();' ], - - [ /Nan::NAN_METHOD_RETURN_TYPE/g, 'void' ], - [ /NAN_INLINE/g, 'inline' ], - - [ /Nan::NAN_METHOD_ARGS_TYPE/g, 'const Napi::CallbackInfo&' ], - [ /NAN_METHOD\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], - [ /static\s*NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)' ], - [ /NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)' ], - [ /static\s*NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)' ], - [ /NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)' ], - [ /void Init\((v8::)*Local<(v8::)*Object> exports\)/g, 'Napi::Object Init(Napi::Env env, Napi::Object exports)' ], - [ /NAN_MODULE_INIT\(([\w\d:]+?)\);/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports);' ], - [ /NAN_MODULE_INIT\(([\w\d:]+?)\)/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports)' ], - - - [ /::(Init(?:ialize)?)\(target\)/g, '::$1(env, target, module)' ], - [ /constructor_template/g, 'constructor' ], - - [ /Nan::FunctionCallbackInfo<(v8::)?Value>[ ]*& [ ]*info\)[ ]*{\n*([ ]*)/gm, 'Napi::CallbackInfo& info) {\n$2Napi::Env env = info.Env();\n$2' ], - [ /Nan::FunctionCallbackInfo<(v8::)*Value>\s*&\s*info\);/g, 'Napi::CallbackInfo& info);' ], - [ /Nan::FunctionCallbackInfo<(v8::)*Value>\s*&/g, 'Napi::CallbackInfo&' ], - - [ /Buffer::HasInstance\(([^)]+)\)/g, '$1.IsBuffer()' ], - - [ /info\[(\d+)\]->/g, 'info[$1].' ], - [ /info\[([\w\d]+)\]->/g, 'info[$1].' ], - [ /info\.This\(\)->/g, 'info.This().' ], - [ /->Is(Object|String|Int32|Number)\(\)/g, '.Is$1()' ], - [ /info.GetReturnValue\(\).SetUndefined\(\)/g, 'return env.Undefined()' ], - [ /info\.GetReturnValue\(\)\.Set\(((\n|.)+?)\);/g, 'return $1;' ], - - - // ex. Local<Value> to Napi::Value - [ /v8::Local<v8::(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1' ], - [ /Local<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1' ], - - // Declare an env in helper functions that take a Napi::Value - [ /(\w+)\(Napi::Value (\w+)(,\s*[^\()]+)?\)\s*{\n*([ ]*)/gm, '$1(Napi::Value $2$3) {\n$4Napi::Env env = $2.Env();\n$4' ], - - // delete #include <node.h> and/or <v8.h> - [ /#include +(<|")(?:node|nan).h("|>)/g, "#include $1napi.h$2\n#include $1uv.h$2" ], - // NODE_MODULE to NODE_API_MODULE - [ /NODE_MODULE/g, 'NODE_API_MODULE' ], - [ /Nan::/g, 'Napi::' ], - [ /nan.h/g, 'napi.h' ], - - // delete .FromJust() - [ /\.FromJust\(\)/g, '' ], - // delete .ToLocalCheck() - [ /\.ToLocalChecked\(\)/g, '' ], - [ /^.*->SetInternalFieldCount\(.*$/gm, '' ], - - // replace using node; and/or using v8; to using Napi; - [ /using (node|v8);/g, 'using Napi;' ], - [ /using namespace (node|Nan|v8);/g, 'using namespace Napi;' ], - // delete using v8::Local; - [ /using v8::Local;\n/g, '' ], - // replace using v8::XXX; with using Napi::XXX - [ /using v8::([A-Za-z]+);/g, 'using Napi::$1;' ], - -]; - -var paths = listFiles(dir); -paths.forEach(function(dirEntry) { - var filename = dirEntry.split('\\').pop().split('/').pop(); - - // Check whether the file is a source file or a config file - // then execute function accordingly - var sourcePattern = /.+\.h|.+\.cc|.+\.cpp/; - if (sourcePattern.test(filename)) { - convertFile(dirEntry, SourceFileOperations); - } else if (ConfigFileOperations[filename] != null) { - convertFile(dirEntry, ConfigFileOperations[filename]); - } -}); - -function listFiles(dir, filelist) { - var files = fs.readdirSync(dir); - filelist = filelist || []; - files.forEach(function(file) { - if (file === 'node_modules') { - return - } - - if (fs.statSync(path.join(dir, file)).isDirectory()) { - filelist = listFiles(path.join(dir, file), filelist); - } else { - filelist.push(path.join(dir, file)); - } - }); - return filelist; -} - -function convert(content, operations) { - for (let i = 0; i < operations.length; i ++) { - let operation = operations[i]; - content = content.replace(operation[0], operation[1]); - } - return content; -} - -function convertFile(fileName, operations) { - fs.readFile(fileName, "utf-8", function (err, file) { - if (err) throw err; - - file = convert(file, operations); - - fs.writeFile(fileName, file, function(err){ - if (err) throw err; - }); - }); -} |