start nodejs bot

This commit is contained in:
2021-02-11 02:38:15 +01:00
parent 968105f35d
commit 6d84704b1f
1814 changed files with 303741 additions and 0 deletions

111
node_modules/node-addon-api/.clang-format generated vendored Normal file
View File

@@ -0,0 +1,111 @@
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Right
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: true
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 8
UseTab: Never

8
node_modules/node-addon-api/.editorconfig generated vendored Normal file
View File

@@ -0,0 +1,8 @@
root = true
[*]
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 2

55
node_modules/node-addon-api/.github/workflows/ci.yml generated vendored Normal file
View File

@@ -0,0 +1,55 @@
name: Node.js CI
on: [push, pull_request]
jobs:
test:
timeout-minutes: 30
strategy:
matrix:
node-version:
- node/10
- node/12
- node/14
- node/15
compiler:
- gcc
- clang
os:
- ubuntu-16.04 # ubuntu-18.04/ubuntu-latest missing package g++-4.9
- macos-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Install system dependencies
run: |
if [ "${{ matrix.compiler }}" = "gcc" -a "${{ matrix.os }}" = ubuntu-* ]; then
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install g++-4.9
fi
- name: Use Node.js ${{ matrix.node-version }}
run: |
git clone --branch v1.4.2 --depth 1 https://github.com/jasongin/nvs ~/.nvs
. ~/.nvs/nvs.sh
nvs --version
nvs add ${{ matrix.node-version }}
nvs use ${{ matrix.node-version }}
node --version
npm --version
npm install
- name: npm test
run: |
if [ "${{ matrix.compiler }}" = "gcc" ]; then
export CC="gcc" CXX="g++"
fi
if [ "${{ matrix.compiler }}" = "gcc" -a "${{ matrix.os }}" = ubuntu-* ]; then
export CC="gcc-4.9" CXX="g++-4.9" AR="gcc-ar-4.9" RANLIB="gcc-ranlib-4.9" NM="gcc-nm-4.9"
fi
if [ "${{ matrix.compiler }}" = "clang" ]; then
export CC="clang" CXX="clang++"
fi
export CFLAGS="$CFLAGS -O3 --coverage" LDFLAGS="$LDFLAGS --coverage"
echo "CFLAGS=\"$CFLAGS\" LDFLAGS=\"$LDFLAGS\""
npm run pretest -- --verbose
node test

View File

@@ -0,0 +1,24 @@
name: Style Checks
on: [push, pull_request]
jobs:
lint:
if: github.repository == 'nodejs/node-addon-api'
strategy:
matrix:
node-version: [14.x]
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- run: git branch -a
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: CLANG_FORMAT_START=refs/remotes/origin/master npm run lint

View File

@@ -0,0 +1,18 @@
name: "Close stale issues"
on:
schedule:
- cron: "0 0 * * *"
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'This issue is stale because it has been open many days with no activity. It will be closed soon unless the stale label is removed or a comment is made.'
stale-issue-label: 'stale'
exempt-issue-label: 'never stale'
days-before-stale: 90
days-before-close: 30

58
node_modules/node-addon-api/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,58 @@
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/10
- NODEJS_VERSION=node/12
- NODEJS_VERSION=node/14
- NODEJS_VERSION=nightly
matrix:
fast_finish: true
allow_failures:
- env: NODEJS_VERSION=nightly
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

626
node_modules/node-addon-api/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,626 @@
# node-addon-api Changelog
## 2020-12-17 Version 3.1.0, @NickNaso
### Notable changes:
#### API
- Added `Napi::TypedThreadSafeFunction` class that is a new implementation for
thread-safe functions.
- Fixed leak on `Napi::AsyncProgressWorkerBase`.
- Fixed empty data on `Napi::AsyncProgressWorker::OnProgress` caused by race
conditions of `Napi::AsyncProgressWorker`.
- Added `Napi::ArrayBuffer::Detach()` and `Napi::ArrayBuffer::IsDetached()`.
- Fixed problem on `Napi::FinalizeCallback` it needs to create a
`Napi::HandleScope` when it calls `Napi::ObjectWrap::~ObjectWrap()`.
#### Documentation
- Added documentation for `Napi::TypedThreadSafeFunction`.
- Removed unsued Doxygen file.
- Clarified when to use N-API.
- Added support information.
- Some minor corrections all over the documentation.
#### TEST
- Added test for `Napi::TypedThreadSafeFunction`.
- Fixed testing for specific N-API version.
- Some minor corrections all over the test suite.
### TOOL
- Setup github actions for tests.
- Added stale action.
- Removed `sudo` tag from Travis CI.
- Added clang-format.
- Added pre-commit package for linting.
### Commits
* [[`ff642c5b85`](https://github.com/nodejs/node-addon-api/commit/ff642c5b85)] - **doc**: fix tsfn docs to reflect true implementation (#860) (Kevin Eady)
* [[`86feeebf54`](https://github.com/nodejs/node-addon-api/commit/86feeebf54)] - **src**: empty data OnProgress in AsyncProgressWorker (legendecas) [#853](https://github.com/nodejs/node-addon-api/pull/853)
* [[`a7fb5fb31c`](https://github.com/nodejs/node-addon-api/commit/a7fb5fb31c)] - **action**: add stale action (#856) (Michael Dawson)
* [[`fd44609885`](https://github.com/nodejs/node-addon-api/commit/fd44609885)] - **chore**: setup github actions for tests (#854) (legendecas) [#854](https://github.com/nodejs/node-addon-api/pull/854)
* [[`c52ace4813`](https://github.com/nodejs/node-addon-api/commit/c52ace4813)] - **script**: fix complains that js files are not supported on npm run lint:fix (#852) (legendecas)
* [[`b4a3364ad5`](https://github.com/nodejs/node-addon-api/commit/b4a3364ad5)] - **doc**: remove unused Doxygen file (#851) (Michael Dawson)
* [[`b810466ae2`](https://github.com/nodejs/node-addon-api/commit/b810466ae2)] - **doc**: clarify when to use N-API (#849) (Michael Dawson)
* [[`528b9f6832`](https://github.com/nodejs/node-addon-api/commit/528b9f6832)] - **test**: remove sudo from travis (#850) (Michael Dawson)
* [[`4bb680de4e`](https://github.com/nodejs/node-addon-api/commit/4bb680de4e)] - Remove misleading sentence (#847) (Nikolai Vavilov) [#847](https://github.com/nodejs/node-addon-api/pull/847)
* [[`48e6b584a3`](https://github.com/nodejs/node-addon-api/commit/48e6b584a3)] - Merge pull request #742 from KevinEady/contexted-tsfn-api-gcc-4 (Gabriel Schulhof)
* [[`d5e37210cc`](https://github.com/nodejs/node-addon-api/commit/d5e37210cc)] - **tools**: print more instructions on clang-format check failed (#846) (legendecas) [#846](https://github.com/nodejs/node-addon-api/pull/846)
* [[`d9e11ff2c9`](https://github.com/nodejs/node-addon-api/commit/d9e11ff2c9)] - **doc**: add support info (#843) (Michael Dawson) [#843](https://github.com/nodejs/node-addon-api/pull/843)
* [[`356e93d69a`](https://github.com/nodejs/node-addon-api/commit/356e93d69a)] - **test**: fixup testing for specific N-API version (#840) (Michael Dawson) [#840](https://github.com/nodejs/node-addon-api/pull/840)
* [[`5e5b9ce1b7`](https://github.com/nodejs/node-addon-api/commit/5e5b9ce1b7)] - Apply formatting changes (Kevin Eady)
* [[`559ad8c0c0`](https://github.com/nodejs/node-addon-api/commit/559ad8c0c0)] - Merge remote-tracking branch 'upstream/master' into contexted-tsfn-api-gcc-4 (Kevin Eady)
* [[`c24c455ced`](https://github.com/nodejs/node-addon-api/commit/c24c455ced)] - Rename to TypedThreadSafeFunction (Kevin Eady)
* [[`63b43f4125`](https://github.com/nodejs/node-addon-api/commit/63b43f4125)] - **test**: fix buildType bug objectwrap\_worker\_thread (raisinten) [#837](https://github.com/nodejs/node-addon-api/pull/837)
* [[`6321f2ba1a`](https://github.com/nodejs/node-addon-api/commit/6321f2ba1a)] - **test**: fix typos in addon\_build/index.js (raisinten) [#838](https://github.com/nodejs/node-addon-api/pull/838)
* [[`59c6a6aeb0`](https://github.com/nodejs/node-addon-api/commit/59c6a6aeb0)] - **fix**: git-clang-format doesn't recognize no changes requested on given files (#835) (legendecas)
* [[`1427b3ef78`](https://github.com/nodejs/node-addon-api/commit/1427b3ef78)] - **src**: create a HandleScope in FinalizeCallback (blagoev) [#832](https://github.com/nodejs/node-addon-api/pull/832)
* [[`8fb5820557`](https://github.com/nodejs/node-addon-api/commit/8fb5820557)] - **build**: add incremental clang-format checks (legendecas) [#819](https://github.com/nodejs/node-addon-api/pull/819)
* [[`2c02d317e5`](https://github.com/nodejs/node-addon-api/commit/2c02d317e5)] - **build**: add pre-commit package for linting (#823) (Kevin Eady)
* [[`1b52c28eb8`](https://github.com/nodejs/node-addon-api/commit/1b52c28eb8)] - Clean up AsyncProgressWorker documentation (#831) (mastergberry)
* [[`4abe7cfe30`](https://github.com/nodejs/node-addon-api/commit/4abe7cfe30)] - **test**: rename tsfnex test files (Kevin Eady)
* [[`c9563caa25`](https://github.com/nodejs/node-addon-api/commit/c9563caa25)] - **src**: add ArrayBuffer::Detach() and ::IsDetached() (Tobias Nießen) [#659](https://github.com/nodejs/node-addon-api/pull/659)
* [[`c79cabaed2`](https://github.com/nodejs/node-addon-api/commit/c79cabaed2)] - **doc**: avoid directing users to HTTP (#828) (Tobias Nießen)
* [[`7a13f861ab`](https://github.com/nodejs/node-addon-api/commit/7a13f861ab)] - **doc**: fix additional typo (Kevin Eady)
* [[`7ec9741dd2`](https://github.com/nodejs/node-addon-api/commit/7ec9741dd2)] - Merge remote-tracking branch 'upstream/master' into contexted-tsfn-api-gcc-4 (Kevin Eady)
* [[`f5fad239fa`](https://github.com/nodejs/node-addon-api/commit/f5fad239fa)] - Update object\_reference.md (#827) (kidneysolo)
* [[`35b65712c2`](https://github.com/nodejs/node-addon-api/commit/35b65712c2)] - **Fix**: some typos in documentation (#826) (Helio Frota)
* [[`8983383000`](https://github.com/nodejs/node-addon-api/commit/8983383000)] - **Fix**: some typos in the document (#825) (Ziqiu Zhao)
* [[`826e466ef6`](https://github.com/nodejs/node-addon-api/commit/826e466ef6)] - Fixed example in addon.md. (#820) (nempoBu4) [#820](https://github.com/nodejs/node-addon-api/pull/820)
* [[`b54f5eb788`](https://github.com/nodejs/node-addon-api/commit/b54f5eb788)] - Additional changes from review (Kevin Eady)
* [[`59f27dac9a`](https://github.com/nodejs/node-addon-api/commit/59f27dac9a)] - Fix common.gypi (Kevin Eady)
* [[`151a914c99`](https://github.com/nodejs/node-addon-api/commit/151a914c99)] - Apply documentation suggestions from code review (Kevin Eady)
* [[`ceb27d4949`](https://github.com/nodejs/node-addon-api/commit/ceb27d4949)] - **src**: fix leak in AsyncProgressWorkerBase\<DataType\> (Ferdinand Holzer) [#795](https://github.com/nodejs/node-addon-api/pull/795)
## 2020-09-18 Version 3.0.2, @NickNaso
### Notable changes:
#### API
- Introduced `include_dir` for use with **gyp** in a scalar context.
- Added `Napi::Addon` to help handle the loading of a native add-on into
multiple threads and or multiple times in the same thread.
- Concentrate callbacks provided to core N-API.
- Make sure wrapcallback is used.
#### Documentation
- Added documentation for `Napi::Addon`.
- Added documentation that reports the full class hierarchy.
- Added link to N-API tutorial website.
- Some minor corrections all over the documentation.
#### TEST
- Added tests to check the build process.
- Refactored test for threasfafe function using async/await.
- Converted tests that gc into async functions that await 10 ticks after
each gc.
- Some minor corrections all over the test suite.
### Commits
* [[`51e25f7c39`](https://github.com/nodejs/node-addon-api/commit/51e25f7c39)] - **doc**: remove a file (#815) (Gabriel Schulhof)
* [[`8c9f1809a2`](https://github.com/nodejs/node-addon-api/commit/8c9f1809a2)] - **doc**: add inheritance links and other changes (Gabriel Schulhof) [#798](https://github.com/nodejs/node-addon-api/pull/798)
* [[`6562e6b0ab`](https://github.com/nodejs/node-addon-api/commit/6562e6b0ab)] - **test**: added tests to check the build process (NickNaso) [#808](https://github.com/nodejs/node-addon-api/pull/808)
* [[`a13b36c96e`](https://github.com/nodejs/node-addon-api/commit/a13b36c96e)] - **test**: fix the threasfafe function test (NickNaso) [#807](https://github.com/nodejs/node-addon-api/pull/807)
* [[`f27623ff61`](https://github.com/nodejs/node-addon-api/commit/f27623ff61)] - **build**: introduce include\_dir (Lovell Fuller) [#766](https://github.com/nodejs/node-addon-api/pull/766)
* [[`9aceea71fc`](https://github.com/nodejs/node-addon-api/commit/9aceea71fc)] - **src**: concentrate callbacks provided to core N-API (Gabriel Schulhof) [#786](https://github.com/nodejs/node-addon-api/pull/786)
* [[`2bc45bbffd`](https://github.com/nodejs/node-addon-api/commit/2bc45bbffd)] - **test**: refactor test to use async/await (Velmisov) [#787](https://github.com/nodejs/node-addon-api/pull/787)
* [[`518cfdcdc1`](https://github.com/nodejs/node-addon-api/commit/518cfdcdc1)] - **test**: test ObjectWrap destructor - no HandleScope (David Halls) [#729](https://github.com/nodejs/node-addon-api/pull/729)
* [[`c2cbbd9191`](https://github.com/nodejs/node-addon-api/commit/c2cbbd9191)] - **doc**: add link to n-api tutorial website (#794) (Jim Schlight) [#794](https://github.com/nodejs/node-addon-api/pull/794)
* [[`1c2a8d59b5`](https://github.com/nodejs/node-addon-api/commit/1c2a8d59b5)] - **doc**: Added required return to example (#793) (pacop) [#793](https://github.com/nodejs/node-addon-api/pull/793)
* [[`cec2c76941`](https://github.com/nodejs/node-addon-api/commit/cec2c76941)] - **src**: wrap finalizer callback (Gabriel Schulhof) [#762](https://github.com/nodejs/node-addon-api/pull/762)
* [[`4ce40d22a6`](https://github.com/nodejs/node-addon-api/commit/4ce40d22a6)] - **test**: use assert.strictEqual() (Koki Nishihara) [#777](https://github.com/nodejs/node-addon-api/pull/777)
* [[`461e3640c6`](https://github.com/nodejs/node-addon-api/commit/461e3640c6)] - **test**: string tests together (Gabriel Schulhof) [#773](https://github.com/nodejs/node-addon-api/pull/773)
* [[`5af645f649`](https://github.com/nodejs/node-addon-api/commit/5af645f649)] - **src**: add Addon\<T\> class (Gabriel Schulhof) [#749](https://github.com/nodejs/node-addon-api/pull/749)
* [[`6148fb4bcc`](https://github.com/nodejs/node-addon-api/commit/6148fb4bcc)] - Synchronise Node.js versions in Appveyor Windows CI with Travis (#768) (Lovell Fuller)
## 2020-07-13 Version 3.0.1, @NickNaso
### Notable changes:
#### API
- Fixed the usage of `Napi::Reference` with `Napi::TypedArray`.
- Fixed `Napi::ObjectWrap` inheritance.
#### Documentation
- Updated the example for `Napi::ObjectWrap`.
- Added documentation for instance data APIs.
- Some minor corrections all over the documentation.
#### TEST
- Fixed test for `Napi::ArrayBuffer` and `Napi::Buffer`.
- Some minor corrections all over the test suite.
### Commits
* [[`40c7926342`](https://github.com/nodejs/node-addon-api/commit/40c7926342)] - **build**: ensure paths with spaces can be used (Lovell Fuller) [#757](https://github.com/nodejs/node-addon-api/pull/757)
* [[`ef16dfb4a2`](https://github.com/nodejs/node-addon-api/commit/ef16dfb4a2)] - **doc**: update ObjectWrap example (Gabriel Schulhof) [#754](https://github.com/nodejs/node-addon-api/pull/754)
* [[`48f6762bf6`](https://github.com/nodejs/node-addon-api/commit/48f6762bf6)] - **src**: add \_\_wasm32\_\_ guards (Gus Caplan)
* [[`bd2c5ec502`](https://github.com/nodejs/node-addon-api/commit/bd2c5ec502)] - Fixes issue 745. (#748) (Nicola Del Gobbo)
* [[`4c01af2d87`](https://github.com/nodejs/node-addon-api/commit/4c01af2d87)] - Fix typo in CHANGELOG (#715) (Kasumi Hanazuki)
* [[`36e1af96d5`](https://github.com/nodejs/node-addon-api/commit/36e1af96d5)] - **src**: fix use of Reference with typed arrays (Michael Dawson) [#726](https://github.com/nodejs/node-addon-api/pull/726)
* [[`d463f02bc7`](https://github.com/nodejs/node-addon-api/commit/d463f02bc7)] - **src**: fix testEnumerables on ObjectWrap (Ferdinand Holzer) [#736](https://github.com/nodejs/node-addon-api/pull/736)
* [[`ba7ad37d44`](https://github.com/nodejs/node-addon-api/commit/ba7ad37d44)] - **src**: fix ObjectWrap inheritance (David Halls) [#732](https://github.com/nodejs/node-addon-api/pull/732)
* [[`31504c862b`](https://github.com/nodejs/node-addon-api/commit/31504c862b)] - **doc**: fix minor typo in object\_wrap.md (#741) (Daniel Bevenius) [#741](https://github.com/nodejs/node-addon-api/pull/741)
* [[`beccf2145d`](https://github.com/nodejs/node-addon-api/commit/beccf2145d)] - **test**: fix up delays for array buffer test (Michael Dawson) [#737](https://github.com/nodejs/node-addon-api/pull/737)
* [[`45cb1d9748`](https://github.com/nodejs/node-addon-api/commit/45cb1d9748)] - Correct AsyncProgressWorker link in README (#716) (Jeroen Janssen)
* [[`381c0da60c`](https://github.com/nodejs/node-addon-api/commit/381c0da60c)] - **doc**: add instance data APIs (Gabriel Schulhof) [#708](https://github.com/nodejs/node-addon-api/pull/708)
## 2020-04-30 Version 3.0.0, @NickNaso
### Notable changes:
#### API
- `Napi::Object` added templated property descriptors.
- `Napi::ObjectWrap` added templated methods.
- `Napi::ObjectWrap` the wrap is removed only on failure.
- `Napi::ObjectWrap` the constructor's exceptions are gracefully handled.
- `Napi::Function` added templated factory functions.
- Added `Env::RunScript` method to run JavaScript code contained in a string.
- Added templated version of `Napi::Function`.
- Added benchmarking framework.
- Added support for native addon instance data.
- Added `Napi::AsyncProgressQueueWorker` api.
- Changed the guards to `NAPI_VERSION > 5`.
- Removed N-API implementation (v6.x and v8.x support).
- `Napi::AsyncWorker::OnWorkComplete` and `Napi::AsyncWorker::OnExecute` methods
are override-able.
- Removed erroneous finalizer cleanup in `Napi::ThreadSafeFunction`.
- Disabled caching in `Napi::ArrayBuffer`.
- Explicitly disallow assign and copy operator.
- Some minor corrections and improvements.
#### Documentation
- Updated documentation for `Napi::Object`.
- Updated documentation for `Napi::Function`.
- Updated documentation for `Napi::ObjectWrap`.
- Added documentation on how to add benchmark.
- Added documentation for `Napi::AsyncProgressQueueWorker`.
- Added suggestion about tags to use on NPM.
- Added reference to N-API badges.
- Some minor corrections all over the documentation.
#### TEST
- Updated test cases for `Napi::Object`.
- Updated test cases for `Napi::Function`.
- Updated test cases for `Napi::ObjectWrap`.
- Updated test cases for `Napi::Env`.
- Added test cases for `Napi::AsyncProgressQueueWorker`.
- Some minor corrections all over the test suite.
### Commits
* [[`187318e37f`](https://github.com/nodejs/node-addon-api/commit/187318e37f)] - **doc**: Removed references to Node.js lower than 10.x. (#709) (Nicola Del Gobbo)
* [[`9c9accfbbe`](https://github.com/nodejs/node-addon-api/commit/9c9accfbbe)] - **src**: add support for addon instance data (Gabriel Schulhof) [#663](https://github.com/nodejs/node-addon-api/pull/663)
* [[`82a96502a4`](https://github.com/nodejs/node-addon-api/commit/82a96502a4)] - **src**: change guards to NAPI\_VERSION \> 5 (Gabriel Schulhof) [#697](https://github.com/nodejs/node-addon-api/pull/697)
* [[`a64e8a5641`](https://github.com/nodejs/node-addon-api/commit/a64e8a5641)] - **ci**: move travis from 13 to 14 (#707) (Gabriel Schulhof)
* [[`4de23c9d6b`](https://github.com/nodejs/node-addon-api/commit/4de23c9d6b)] - **doc**: fix support bigint64/biguint64 guards (Yulong Wang) [#705](https://github.com/nodejs/node-addon-api/pull/705)
* [[`fedc8195e3`](https://github.com/nodejs/node-addon-api/commit/fedc8195e3)] - **doc**: fix semicolon missing in async\_worker.md (Azlan Mukhtar) [#701](https://github.com/nodejs/node-addon-api/pull/701)
* [[`cdb662506c`](https://github.com/nodejs/node-addon-api/commit/cdb662506c)] - **doc**: fix typo in bigint.md (#700) (Kelvin)
* [[`e1a827ae29`](https://github.com/nodejs/node-addon-api/commit/e1a827ae29)] - **src**: fix AsyncProgressQueueWorker compilation (#696) (Gabriel Schulhof) [#696](https://github.com/nodejs/node-addon-api/pull/696)
* [[`2c3d5df463`](https://github.com/nodejs/node-addon-api/commit/2c3d5df463)] - Merge pull request #692 from kelvinhammond/patch-1 (Nicola Del Gobbo)
* [[`623e876949`](https://github.com/nodejs/node-addon-api/commit/623e876949)] - Merge pull request #688 from NickNaso/badges (Nicola Del Gobbo)
* [[`6c97913d1f`](https://github.com/nodejs/node-addon-api/commit/6c97913d1f)] - Fix minor typo in object\_lifetime\_management.md (Kelvin)
* [[`6b8dd47c55`](https://github.com/nodejs/node-addon-api/commit/6b8dd47c55)] - Added badge section to documentation. (NickNaso)
* [[`89e62a9154`](https://github.com/nodejs/node-addon-api/commit/89e62a9154)] - **doc**: recommend tags of addon helpers (legendecas) [#683](https://github.com/nodejs/node-addon-api/pull/683)
* [[`ab018444ae`](https://github.com/nodejs/node-addon-api/commit/ab018444ae)] - **src**: implement AsyncProgressQueueWorker (legendecas) [#585](https://github.com/nodejs/node-addon-api/pull/585)
* [[`d43da6ac2b`](https://github.com/nodejs/node-addon-api/commit/d43da6ac2b)] - **doc**: add @legendecas to active member list (legendecas)
* [[`cb498bbe7f`](https://github.com/nodejs/node-addon-api/commit/cb498bbe7f)] - **doc**: Add Napi::BigInt::New() overload for uint64\_t (ikokostya)
* [[`baaaa8452c`](https://github.com/nodejs/node-addon-api/commit/baaaa8452c)] - **doc**: link threadsafe function from JS function (legendecas)
* [[`7f56a78ff7`](https://github.com/nodejs/node-addon-api/commit/7f56a78ff7)] - **objectwrap**: remove wrap only on failure (Gabriel Schulhof)
* [[`4d816183da`](https://github.com/nodejs/node-addon-api/commit/4d816183da)] - **doc**: fix example code (András Timár, Dr) [#657](https://github.com/nodejs/node-addon-api/pull/657)
* [[`7ac6e21801`](https://github.com/nodejs/node-addon-api/commit/7ac6e21801)] - **gyp**: fix gypfile name in index.js (Anna Henningsen) [#658](https://github.com/nodejs/node-addon-api/pull/658)
* [[`46484202ca`](https://github.com/nodejs/node-addon-api/commit/46484202ca)] - **test**: user data in function property descriptor (Kevin Eady) [#652](https://github.com/nodejs/node-addon-api/pull/652)
* [[`0f8d730483`](https://github.com/nodejs/node-addon-api/commit/0f8d730483)] - **doc**: fix syntax error in example (András Timár, Dr) [#650](https://github.com/nodejs/node-addon-api/pull/650)
* [[`4e885069f1`](https://github.com/nodejs/node-addon-api/commit/4e885069f1)] - **src**: call `napi\_remove\_wrap()` in `ObjectWrap` dtor (Anna Henningsen) [#475](https://github.com/nodejs/node-addon-api/pull/475)
* [[`2fde5c3ca3`](https://github.com/nodejs/node-addon-api/commit/2fde5c3ca3)] - **test**: update BigInt test for recent change in core (Michael Dawson) [#649](https://github.com/nodejs/node-addon-api/pull/649)
* [[`e8935bd8d9`](https://github.com/nodejs/node-addon-api/commit/e8935bd8d9)] - **test**: add test for own properties on ObjectWrap (Guenter Sandner) [#645](https://github.com/nodejs/node-addon-api/pull/645)
* [[`23ff7f0b24`](https://github.com/nodejs/node-addon-api/commit/23ff7f0b24)] - **src**: make OnWorkComplete and OnExecute override-able (legendecas) [#589](https://github.com/nodejs/node-addon-api/pull/589)
* [[`86384f94d3`](https://github.com/nodejs/node-addon-api/commit/86384f94d3)] - **objectwrap**: gracefully handle constructor exceptions (Gabriel Schulhof)
* [[`9af69da01f`](https://github.com/nodejs/node-addon-api/commit/9af69da01f)] - remove N-API implementation, v6.x and v8.x support (Gabriel Schulhof) [#643](https://github.com/nodejs/node-addon-api/pull/643)
* [[`920d544779`](https://github.com/nodejs/node-addon-api/commit/920d544779)] - **benchmark**: add templated version of Function (Gabriel Schulhof) [#637](https://github.com/nodejs/node-addon-api/pull/637)
* [[`03759f7759`](https://github.com/nodejs/node-addon-api/commit/03759f7759)] - ignore benchmark built archives (legendecas) [#631](https://github.com/nodejs/node-addon-api/pull/631)
* [[`5eeabb0214`](https://github.com/nodejs/node-addon-api/commit/5eeabb0214)] - **tsfn**: Remove erroneous finalizer cleanup (Kevin Eady) [#636](https://github.com/nodejs/node-addon-api/pull/636)
* [[`9e0e0f31e4`](https://github.com/nodejs/node-addon-api/commit/9e0e0f31e4)] - **src**: remove unnecessary forward declarations (Gabriel Schulhof) [#633](https://github.com/nodejs/node-addon-api/pull/633)
* [[`79deefb6f3`](https://github.com/nodejs/node-addon-api/commit/79deefb6f3)] - **src**: explicitly disallow assign and copy (legendecas) [#590](https://github.com/nodejs/node-addon-api/pull/590)
* [[`af50ac281b`](https://github.com/nodejs/node-addon-api/commit/af50ac281b)] - **error**: do not replace pending exception (Gabriel Schulhof) [#629](https://github.com/nodejs/node-addon-api/pull/629)
* [[`b72f1d6978`](https://github.com/nodejs/node-addon-api/commit/b72f1d6978)] - Disable caching in ArrayBuffer (Tobias Nießen) [#611](https://github.com/nodejs/node-addon-api/pull/611)
* [[`0e7483eb7b`](https://github.com/nodejs/node-addon-api/commit/0e7483eb7b)] - Fix code format in tests (Tobias Nießen) [#617](https://github.com/nodejs/node-addon-api/pull/617)
* [[`6a0646356d`](https://github.com/nodejs/node-addon-api/commit/6a0646356d)] - add benchmarking framework (Gabriel Schulhof) [#623](https://github.com/nodejs/node-addon-api/pull/623)
* [[`ffc71edd54`](https://github.com/nodejs/node-addon-api/commit/ffc71edd54)] - Add Env::RunScript (Tobias Nießen) [#616](https://github.com/nodejs/node-addon-api/pull/616)
* [[`a1b106066e`](https://github.com/nodejs/node-addon-api/commit/a1b106066e)] - **src**: add templated function factories (Gabriel Schulhof) [#608](https://github.com/nodejs/node-addon-api/pull/608)
* [[`c584343217`](https://github.com/nodejs/node-addon-api/commit/c584343217)] - Add GetPropertyNames, HasOwnProperty, Delete (#615) (Tobias Nießen) [#615](https://github.com/nodejs/node-addon-api/pull/615)
* [[`3acc4b32f5`](https://github.com/nodejs/node-addon-api/commit/3acc4b32f5)] - Fix std::string encoding (#619) (Tobias Nießen) [#619](https://github.com/nodejs/node-addon-api/pull/619)
* [[`e71d0eadcc`](https://github.com/nodejs/node-addon-api/commit/e71d0eadcc)] - \[doc\] Fixed links to array documentation (#613) (Nicola Del Gobbo)
* [[`3dfb1f0591`](https://github.com/nodejs/node-addon-api/commit/3dfb1f0591)] - Change "WG" to "team" (Tobias Nießen)
* [[`ce91e14860`](https://github.com/nodejs/node-addon-api/commit/ce91e14860)] - **objectwrap**: add template methods (Dmitry Ashkadov) [#604](https://github.com/nodejs/node-addon-api/pull/604)
* [[`cfa71b60f7`](https://github.com/nodejs/node-addon-api/commit/cfa71b60f7)] - **object**: add templated property descriptors (Gabriel Schulhof) [#610](https://github.com/nodejs/node-addon-api/pull/610)
* [[`734725e971`](https://github.com/nodejs/node-addon-api/commit/734725e971)] - Correctly define copy assignment operators. (Rolf Timmermans)
## 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`.
### Commits
* [[`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.
### Commits
* [[`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`.
### Commits
* [[`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.
### Commits
* [[`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.
### Commits
* [[`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.
### Commits
* [[`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

4
node_modules/node-addon-api/CODE_OF_CONDUCT.md generated vendored Normal file
View File

@@ -0,0 +1,4 @@
# 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.

66
node_modules/node-addon-api/CONTRIBUTING.md generated vendored Normal file
View File

@@ -0,0 +1,66 @@
# **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**

13
node_modules/node-addon-api/LICENSE.md generated vendored Normal file
View File

@@ -0,0 +1,13 @@
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.

273
node_modules/node-addon-api/README.md generated vendored Normal file
View File

@@ -0,0 +1,273 @@
# **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.
There are three options for implementing addons: N-API, nan, or direct
use of internal V8, libuv and Node.js libraries. Unless there is a need for
direct access to functionality which is not exposed by N-API as outlined
in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html)
in Node.js core, use N-API. Refer to
[C/C++ addons with N-API](https://nodejs.org/dist/latest/docs/api/n-api.html)
for more information on N-API.
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 an active LTS version of Node.js) 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**.
The [N-API Resource](https://nodejs.github.io/node-addon-examples/) offers an
excellent orientation and tips for developers just getting started with N-API
and node-addon-api.
- **[Setup](#setup)**
- **[API Documentation](#api)**
- **[Examples](#examples)**
- **[Tests](#tests)**
- **[More resource and info about native Addons](#resources)**
- **[Badges](#badges)**
- **[Code of Conduct](CODE_OF_CONDUCT.md)**
- **[Contributors](#contributors)**
- **[License](#license)**
## **Current version: 3.1.0**
(See [CHANGELOG.md](CHANGELOG.md) for complete Changelog)
[![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/)
<a name="setup"></a>
node-addon-api is based on [N-API](https://nodejs.org/api/n-api.html) and supports using different N-API versions.
This allows addons built with it to run with Node.js versions which support the targeted N-API version.
**However** the node-addon-api support model is to support only the active LTS Node.js versions. This means that
every year there will be a new major which drops support for the Node.js LTS version which has gone out of service.
The oldest Node.js version supported by the current version of node-addon-api is Node.js 10.x.
## 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.
- [Full Class Hierarchy](doc/hierarchy.md)
- [Addon Structure](doc/addon.md)
- Data Types:
- [Env](doc/env.md)
- [CallbackInfo](doc/callbackinfo.md)
- [Reference](doc/reference.md)
- [Value](doc/value.md)
- [Name](doc/name.md)
- [Symbol](doc/symbol.md)
- [String](doc/string.md)
- [Number](doc/number.md)
- [Date](doc/date.md)
- [BigInt](doc/bigint.md)
- [Boolean](doc/boolean.md)
- [External](doc/external.md)
- [Object](doc/object.md)
- [Array](doc/array.md)
- [ObjectReference](doc/object_reference.md)
- [PropertyDescriptor](doc/property_descriptor.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)
- [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)
- [Memory Management](doc/memory_management.md)
- [Async Operations](doc/async_operations.md)
- [AsyncWorker](doc/async_worker.md)
- [AsyncContext](doc/async_context.md)
- [AsyncWorker Variants](doc/async_worker_variants.md)
- [Thread-safe Functions](doc/threadsafe.md)
- [ThreadSafeFunction](doc/threadsafe_function.md)
- [TypedThreadSafeFunction](doc/typed_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
```
To run the tests targetting a specific version of N-API run
```
npm install
export NAPI_VERSION=X
npm test --NAPI_VERSION=X
```
where X is the version of N-API you want to target.
### **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)**
### **Benchmarks**
You can run the available benchmarks using the following command:
```
npm run-script benchmark
```
See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks.
<a name="resources"></a>
### **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)**
As node-addon-api's core mission is to expose the plain C N-API as C++
wrappers, tools that facilitate n-api/node-addon-api providing more
convenient patterns on developing a Node.js add-ons with n-api/node-addon-api
can be published to NPM as standalone packages. It is also recommended to tag
such packages with `node-addon-api` to provide more visibility to the community.
Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api).
<a name="badges"></a>
### **Badges**
The use of badges is recommended to indicate the minimum version of N-API
required for the module. This helps to determine which Node.js major versions are
supported. Addon maintainers can consult the [N-API support matrix][] to determine
which Node.js versions provide a given N-API version. The following badges are
available:
![N-API v1 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/N-API%20v1%20Badge.svg)
![N-API v2 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/N-API%20v2%20Badge.svg)
![N-API v3 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/N-API%20v3%20Badge.svg)
![N-API v4 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/N-API%20v4%20Badge.svg)
![N-API v5 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/N-API%20v5%20Badge.svg)
![N-API v6 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/N-API%20v6%20Badge.svg)
![N-API Experimental Version Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/N-API%20Experimental%20Version%20Badge.svg)
## **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.
<a name="contributors"></a>
## Team members
### Active
| Name | GitHub Link |
| ------------------- | ----------------------------------------------------- |
| Anna Henningsen | [addaleax](https://github.com/addaleax) |
| Chengzhong Wu | [legendecas](https://github.com/legendecas) |
| 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/
[N-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix

37
node_modules/node-addon-api/appveyor.yml generated vendored Normal file
View File

@@ -0,0 +1,37 @@
environment:
# https://github.com/jasongin/nvs/blob/master/doc/CI.md
NVS_VERSION: 1.4.2
matrix:
- NODEJS_VERSION: node/10
- NODEJS_VERSION: node/12
- NODEJS_VERSION: node/14
- NODEJS_VERSION: nightly
os: Visual Studio 2017
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

47
node_modules/node-addon-api/benchmark/README.md generated vendored Normal file
View File

@@ -0,0 +1,47 @@
# Benchmarks
## Running the benchmarks
From the parent directory, run
```bash
npm run-script benchmark
```
The above script supports the following arguments:
* `--benchmarks=...`: A semicolon-separated list of benchmark names. These names
will be mapped to file names in this directory by appending `.js`.
## Adding benchmarks
The steps below should be followed when adding new benchmarks.
0. Decide on a name for the benchmark. This name will be used in several places.
This example will use the name `new_benchmark`.
0. Create files `new_benchmark.cc` and `new_benchmark.js` in this directory.
0. Copy an existing benchmark in `binding.gyp` and change the target name prefix
and the source file name to `new_benchmark`. This should result in two new
targets which look like this:
```gyp
{
'target_name': 'new_benchmark',
'sources': [ 'new_benchmark.cc' ],
'includes': [ '../except.gypi' ],
},
{
'target_name': 'new_benchmark_noexcept',
'sources': [ 'new_benchmark.cc' ],
'includes': [ '../noexcept.gypi' ],
},
```
There should always be a pair of targets: one bearing the name of the
benchmark and configured with C++ exceptions enabled, and one bearing the
same name followed by the suffix `_noexcept` and configured with C++
exceptions disabled. This will ensure that the benchmark can be written to
cover both the case where C++ exceptions are enabled and the case where they
are disabled.

25
node_modules/node-addon-api/benchmark/binding.gyp generated vendored Normal file
View File

@@ -0,0 +1,25 @@
{
'target_defaults': { 'includes': ['../common.gypi'] },
'targets': [
{
'target_name': 'function_args',
'sources': [ 'function_args.cc' ],
'includes': [ '../except.gypi' ],
},
{
'target_name': 'function_args_noexcept',
'sources': [ 'function_args.cc' ],
'includes': [ '../noexcept.gypi' ],
},
{
'target_name': 'property_descriptor',
'sources': [ 'property_descriptor.cc' ],
'includes': [ '../except.gypi' ],
},
{
'target_name': 'property_descriptor_noexcept',
'sources': [ 'property_descriptor.cc' ],
'includes': [ '../noexcept.gypi' ],
},
]
}

217
node_modules/node-addon-api/benchmark/function_args.cc generated vendored Normal file
View File

@@ -0,0 +1,217 @@
#include "napi.h"
static napi_value NoArgFunction_Core(napi_env env, napi_callback_info info) {
(void) env;
(void) info;
return nullptr;
}
static napi_value OneArgFunction_Core(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value argv;
if (napi_get_cb_info(env, info, &argc, &argv, nullptr, nullptr) != napi_ok) {
return nullptr;
}
(void) argv;
return nullptr;
}
static napi_value TwoArgFunction_Core(napi_env env, napi_callback_info info) {
size_t argc = 2;
napi_value argv[2];
if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok) {
return nullptr;
}
(void) argv[0];
(void) argv[1];
return nullptr;
}
static napi_value ThreeArgFunction_Core(napi_env env, napi_callback_info info) {
size_t argc = 3;
napi_value argv[3];
if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok) {
return nullptr;
}
(void) argv[0];
(void) argv[1];
(void) argv[2];
return nullptr;
}
static napi_value FourArgFunction_Core(napi_env env, napi_callback_info info) {
size_t argc = 4;
napi_value argv[4];
if (napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok) {
return nullptr;
}
(void) argv[0];
(void) argv[1];
(void) argv[2];
(void) argv[3];
return nullptr;
}
static void NoArgFunction(const Napi::CallbackInfo& info) {
(void) info;
}
static void OneArgFunction(const Napi::CallbackInfo& info) {
Napi::Value argv0 = info[0]; (void) argv0;
}
static void TwoArgFunction(const Napi::CallbackInfo& info) {
Napi::Value argv0 = info[0]; (void) argv0;
Napi::Value argv1 = info[1]; (void) argv1;
}
static void ThreeArgFunction(const Napi::CallbackInfo& info) {
Napi::Value argv0 = info[0]; (void) argv0;
Napi::Value argv1 = info[1]; (void) argv1;
Napi::Value argv2 = info[2]; (void) argv2;
}
static void FourArgFunction(const Napi::CallbackInfo& info) {
Napi::Value argv0 = info[0]; (void) argv0;
Napi::Value argv1 = info[1]; (void) argv1;
Napi::Value argv2 = info[2]; (void) argv2;
Napi::Value argv3 = info[3]; (void) argv3;
}
#if NAPI_VERSION > 5
class FunctionArgsBenchmark : public Napi::Addon<FunctionArgsBenchmark> {
public:
FunctionArgsBenchmark(Napi::Env env, Napi::Object exports) {
DefineAddon(exports, {
InstanceValue("addon", DefineProperties(Napi::Object::New(env), {
InstanceMethod("noArgFunction", &FunctionArgsBenchmark::NoArgFunction),
InstanceMethod("oneArgFunction",
&FunctionArgsBenchmark::OneArgFunction),
InstanceMethod("twoArgFunction",
&FunctionArgsBenchmark::TwoArgFunction),
InstanceMethod("threeArgFunction",
&FunctionArgsBenchmark::ThreeArgFunction),
InstanceMethod("fourArgFunction",
&FunctionArgsBenchmark::FourArgFunction),
}), napi_enumerable),
InstanceValue("addon_templated",
DefineProperties(Napi::Object::New(env), {
InstanceMethod<&FunctionArgsBenchmark::NoArgFunction>(
"noArgFunction"),
InstanceMethod<&FunctionArgsBenchmark::OneArgFunction>(
"oneArgFunction"),
InstanceMethod<&FunctionArgsBenchmark::TwoArgFunction>(
"twoArgFunction"),
InstanceMethod<&FunctionArgsBenchmark::ThreeArgFunction>(
"threeArgFunction"),
InstanceMethod<&FunctionArgsBenchmark::FourArgFunction>(
"fourArgFunction"),
}), napi_enumerable),
});
}
private:
void NoArgFunction(const Napi::CallbackInfo& info) {
(void) info;
}
void OneArgFunction(const Napi::CallbackInfo& info) {
Napi::Value argv0 = info[0]; (void) argv0;
}
void TwoArgFunction(const Napi::CallbackInfo& info) {
Napi::Value argv0 = info[0]; (void) argv0;
Napi::Value argv1 = info[1]; (void) argv1;
}
void ThreeArgFunction(const Napi::CallbackInfo& info) {
Napi::Value argv0 = info[0]; (void) argv0;
Napi::Value argv1 = info[1]; (void) argv1;
Napi::Value argv2 = info[2]; (void) argv2;
}
void FourArgFunction(const Napi::CallbackInfo& info) {
Napi::Value argv0 = info[0]; (void) argv0;
Napi::Value argv1 = info[1]; (void) argv1;
Napi::Value argv2 = info[2]; (void) argv2;
Napi::Value argv3 = info[3]; (void) argv3;
}
};
#endif // NAPI_VERSION > 5
static Napi::Object Init(Napi::Env env, Napi::Object exports) {
napi_value no_arg_function, one_arg_function, two_arg_function,
three_arg_function, four_arg_function;
napi_status status;
status = napi_create_function(env,
"noArgFunction",
NAPI_AUTO_LENGTH,
NoArgFunction_Core,
nullptr,
&no_arg_function);
NAPI_THROW_IF_FAILED(env, status, Napi::Object());
status = napi_create_function(env,
"oneArgFunction",
NAPI_AUTO_LENGTH,
OneArgFunction_Core,
nullptr,
&one_arg_function);
NAPI_THROW_IF_FAILED(env, status, Napi::Object());
status = napi_create_function(env,
"twoArgFunction",
NAPI_AUTO_LENGTH,
TwoArgFunction_Core,
nullptr,
&two_arg_function);
NAPI_THROW_IF_FAILED(env, status, Napi::Object());
status = napi_create_function(env,
"threeArgFunction",
NAPI_AUTO_LENGTH,
ThreeArgFunction_Core,
nullptr,
&three_arg_function);
NAPI_THROW_IF_FAILED(env, status, Napi::Object());
status = napi_create_function(env,
"fourArgFunction",
NAPI_AUTO_LENGTH,
FourArgFunction_Core,
nullptr,
&four_arg_function);
NAPI_THROW_IF_FAILED(env, status, Napi::Object());
Napi::Object core = Napi::Object::New(env);
core["noArgFunction"] = Napi::Value(env, no_arg_function);
core["oneArgFunction"] = Napi::Value(env, one_arg_function);
core["twoArgFunction"] = Napi::Value(env, two_arg_function);
core["threeArgFunction"] = Napi::Value(env, three_arg_function);
core["fourArgFunction"] = Napi::Value(env, four_arg_function);
exports["core"] = core;
Napi::Object cplusplus = Napi::Object::New(env);
cplusplus["noArgFunction"] = Napi::Function::New(env, NoArgFunction);
cplusplus["oneArgFunction"] = Napi::Function::New(env, OneArgFunction);
cplusplus["twoArgFunction"] = Napi::Function::New(env, TwoArgFunction);
cplusplus["threeArgFunction"] = Napi::Function::New(env, ThreeArgFunction);
cplusplus["fourArgFunction"] = Napi::Function::New(env, FourArgFunction);
exports["cplusplus"] = cplusplus;
Napi::Object templated = Napi::Object::New(env);
templated["noArgFunction"] = Napi::Function::New<NoArgFunction>(env);
templated["oneArgFunction"] = Napi::Function::New<OneArgFunction>(env);
templated["twoArgFunction"] = Napi::Function::New<TwoArgFunction>(env);
templated["threeArgFunction"] = Napi::Function::New<ThreeArgFunction>(env);
templated["fourArgFunction"] = Napi::Function::New<FourArgFunction>(env);
exports["templated"] = templated;
#if NAPI_VERSION > 5
FunctionArgsBenchmark::Init(env, exports);
#endif // NAPI_VERSION > 5
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)

60
node_modules/node-addon-api/benchmark/function_args.js generated vendored Normal file
View File

@@ -0,0 +1,60 @@
const path = require('path');
const Benchmark = require('benchmark');
const addonName = path.basename(__filename, '.js');
[ addonName, addonName + '_noexcept' ]
.forEach((addonName) => {
const rootAddon = require('bindings')({
bindings: addonName,
module_root: __dirname
});
delete rootAddon.path;
const implems = Object.keys(rootAddon);
const maxNameLength =
implems.reduce((soFar, value) => Math.max(soFar, value.length), 0);
const anObject = {};
console.log(`\n${addonName}: `);
console.log('no arguments:');
implems.reduce((suite, implem) => {
const fn = rootAddon[implem].noArgFunction;
return suite.add(implem.padStart(maxNameLength, ' '), () => fn());
}, new Benchmark.Suite)
.on('cycle', (event) => console.log(String(event.target)))
.run();
console.log('one argument:');
implems.reduce((suite, implem) => {
const fn = rootAddon[implem].oneArgFunction;
return suite.add(implem.padStart(maxNameLength, ' '), () => fn('x'));
}, new Benchmark.Suite)
.on('cycle', (event) => console.log(String(event.target)))
.run();
console.log('two arguments:');
implems.reduce((suite, implem) => {
const fn = rootAddon[implem].twoArgFunction;
return suite.add(implem.padStart(maxNameLength, ' '), () => fn('x', 12));
}, new Benchmark.Suite)
.on('cycle', (event) => console.log(String(event.target)))
.run();
console.log('three arguments:');
implems.reduce((suite, implem) => {
const fn = rootAddon[implem].threeArgFunction;
return suite.add(implem.padStart(maxNameLength, ' '),
() => fn('x', 12, true));
}, new Benchmark.Suite)
.on('cycle', (event) => console.log(String(event.target)))
.run();
console.log('four arguments:');
implems.reduce((suite, implem) => {
const fn = rootAddon[implem].fourArgFunction;
return suite.add(implem.padStart(maxNameLength, ' '),
() => fn('x', 12, true, anObject));
}, new Benchmark.Suite)
.on('cycle', (event) => console.log(String(event.target)))
.run();
});

34
node_modules/node-addon-api/benchmark/index.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
'use strict';
const { readdirSync } = require('fs');
const { spawnSync } = require('child_process');
const path = require('path');
let benchmarks = [];
if (!!process.env.npm_config_benchmarks) {
benchmarks = process.env.npm_config_benchmarks
.split(';')
.map((item) => (item + '.js'));
}
// Run each file in this directory or the list given on the command line except
// index.js as a Node.js process.
(benchmarks.length > 0 ? benchmarks : readdirSync(__dirname))
.filter((item) => (item !== 'index.js' && item.match(/\.js$/)))
.map((item) => path.join(__dirname, item))
.forEach((item) => {
const child = spawnSync(process.execPath, [
'--expose-gc',
item
], { stdio: 'inherit' });
if (child.signal) {
console.error(`Tests aborted with ${child.signal}`);
process.exitCode = 1;
} else {
process.exitCode = child.status;
}
if (child.status !== 0) {
process.exit(process.exitCode);
}
});

View File

@@ -0,0 +1,91 @@
#include "napi.h"
static napi_value Getter_Core(napi_env env, napi_callback_info info) {
(void) info;
napi_value result;
napi_status status = napi_create_uint32(env, 42, &result);
NAPI_THROW_IF_FAILED(env, status, nullptr);
return result;
}
static napi_value Setter_Core(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value argv;
napi_status status =
napi_get_cb_info(env, info, &argc, &argv, nullptr, nullptr);
NAPI_THROW_IF_FAILED(env, status, nullptr);
(void) argv;
return nullptr;
}
static Napi::Value Getter(const Napi::CallbackInfo& info) {
return Napi::Number::New(info.Env(), 42);
}
static void Setter(const Napi::CallbackInfo& info) {
(void) info[0];
}
#if NAPI_VERSION > 5
class PropDescBenchmark : public Napi::Addon<PropDescBenchmark> {
public:
PropDescBenchmark(Napi::Env, Napi::Object exports) {
DefineAddon(exports, {
InstanceAccessor("addon",
&PropDescBenchmark::Getter,
&PropDescBenchmark::Setter,
napi_enumerable),
InstanceAccessor<&PropDescBenchmark::Getter,
&PropDescBenchmark::Setter>("addon_templated",
napi_enumerable),
});
}
private:
Napi::Value Getter(const Napi::CallbackInfo& info) {
return Napi::Number::New(info.Env(), 42);
}
void Setter(const Napi::CallbackInfo& info, const Napi::Value& val) {
(void) info[0];
(void) val;
}
};
#endif // NAPI_VERSION > 5
static Napi::Object Init(Napi::Env env, Napi::Object exports) {
napi_status status;
napi_property_descriptor core_prop = {
"core",
nullptr,
nullptr,
Getter_Core,
Setter_Core,
nullptr,
napi_enumerable,
nullptr
};
status = napi_define_properties(env, exports, 1, &core_prop);
NAPI_THROW_IF_FAILED(env, status, Napi::Object());
exports.DefineProperty(
Napi::PropertyDescriptor::Accessor(env,
exports,
"cplusplus",
Getter,
Setter,
napi_enumerable));
exports.DefineProperty(
Napi::PropertyDescriptor::Accessor<Getter, Setter>("templated",
napi_enumerable));
#if NAPI_VERSION > 5
PropDescBenchmark::Init(env, exports);
#endif // NAPI_VERSION > 5
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)

View File

@@ -0,0 +1,37 @@
const path = require('path');
const Benchmark = require('benchmark');
const addonName = path.basename(__filename, '.js');
[ addonName, addonName + '_noexcept' ]
.forEach((addonName) => {
const rootAddon = require('bindings')({
bindings: addonName,
module_root: __dirname
});
delete rootAddon.path;
const getters = new Benchmark.Suite;
const setters = new Benchmark.Suite;
const maxNameLength = Object.keys(rootAddon)
.reduce((soFar, value) => Math.max(soFar, value.length), 0);
console.log(`\n${addonName}: `);
Object.keys(rootAddon).forEach((key) => {
getters.add(`${key} getter`.padStart(maxNameLength + 7), () => {
const x = rootAddon[key];
});
setters.add(`${key} setter`.padStart(maxNameLength + 7), () => {
rootAddon[key] = 5;
})
});
getters
.on('cycle', (event) => console.log(String(event.target)))
.run();
console.log('');
setters
.on('cycle', (event) => console.log(String(event.target)))
.run();
});

21
node_modules/node-addon-api/common.gypi generated vendored Normal file
View File

@@ -0,0 +1,21 @@
{
'variables': {
'NAPI_VERSION%': "<!(node -p \"process.versions.napi\")",
'disable_deprecated': "<!(node -p \"process.env['npm_config_disable_deprecated']\")"
},
'conditions': [
['NAPI_VERSION!=""', { 'defines': ['NAPI_VERSION=<@(NAPI_VERSION)'] } ],
['disable_deprecated=="true"', {
'defines': ['NODE_ADDON_API_DISABLE_DEPRECATED']
}],
['OS=="mac"', {
'cflags+': ['-fvisibility=hidden'],
'xcode_settings': {
'OTHER_CFLAGS': ['-fvisibility=hidden']
}
}]
],
'include_dirs': ["<!(node -p \"require('../').include_dir\")"],
'cflags': [ '-Werror', '-Wall', '-Wextra', '-Wpedantic', '-Wunused-parameter' ],
'cflags_cc': [ '-Werror', '-Wall', '-Wextra', '-Wpedantic', '-Wunused-parameter' ]
}

157
node_modules/node-addon-api/doc/addon.md generated vendored Normal file
View File

@@ -0,0 +1,157 @@
# Add-on Structure
Class `Napi::Addon<T>` inherits from class [`Napi::InstanceWrap<T>`][].
Creating add-ons that work correctly when loaded multiple times from the same
source package into multiple Node.js threads and/or multiple times into the same
Node.js thread requires that all global data they hold be associated with the
environment in which they run. It is not safe to store global data in static
variables because doing so does not take into account the fact that an add-on
may be loaded into multiple threads nor that an add-on may be loaded multiple
times into a single thread.
The `Napi::Addon<T>` class can be used to define an entire add-on. Instances of
`Napi::Addon<T>` subclasses become instances of the add-on, stored safely by
Node.js on its various threads and into its various contexts. Thus, any data
stored in the instance variables of a `Napi::Addon<T>` subclass instance are
stored safely by Node.js. Functions exposed to JavaScript using
`Napi::Addon<T>::InstanceMethod` and/or `Napi::Addon<T>::DefineAddon` are
instance methods of the `Napi::Addon` subclass and thus have access to data
stored inside the instance.
`Napi::Addon<T>::DefineProperties` may be used to attach `Napi::Addon<T>`
subclass instance methods to objects other than the one that will be returned to
Node.js as the add-on instance.
The `Napi::Addon<T>` class can be used together with the `NODE_API_ADDON()` and
`NODE_API_NAMED_ADDON()` macros to define add-ons.
## Example
```cpp
#include <napi.h>
class ExampleAddon : public Napi::Addon<ExampleAddon> {
public:
ExampleAddon(Napi::Env env, Napi::Object exports) {
// In the constructor we declare the functions the add-on makes available
// to JavaScript.
DefineAddon(exports, {
InstanceMethod("increment", &ExampleAddon::Increment),
// We can also attach plain objects to `exports`, and instance methods as
// properties of those sub-objects.
InstanceValue("subObject", DefineProperties(Napi::Object::New(env), {
InstanceMethod("decrement", &ExampleAddon::Decrement)
}), napi_enumerable)
});
}
private:
// This method has access to the data stored in the environment because it is
// an instance method of `ExampleAddon` and because it was listed among the
// property descriptors passed to `DefineAddon()` in the constructor.
Napi::Value Increment(const Napi::CallbackInfo& info) {
return Napi::Number::New(info.Env(), ++value);
}
// This method has access to the data stored in the environment because it is
// an instance method of `ExampleAddon` and because it was exposed to
// JavaScript by calling `DefineProperties()` with the object onto which it is
// attached.
Napi::Value Decrement(const Napi::CallbackInfo& info) {
return Napi::Number::New(info.Env(), --value);
}
// Data stored in these variables is unique to each instance of the add-on.
uint32_t value = 42;
};
// The macro announces that instances of the class `ExampleAddon` will be
// created for each instance of the add-on that must be loaded into Node.js.
NODE_API_ADDON(ExampleAddon)
```
The above code can be used from JavaScript as follows:
```js
'use strict'
const exampleAddon = require('bindings')('example_addon');
console.log(exampleAddon.increment()); // prints 43
console.log(exampleAddon.increment()); // prints 44
console.log(exampleAddon.subObject.decrement()); // prints 43
```
When Node.js loads an instance of the add-on, a new instance of the class is
created. Its constructor receives the environment `Napi::Env env` and the
exports object `Napi::Object exports`. It can then use the method `DefineAddon`
to either attach methods, accessors, and/or values to the `exports` object or to
create its own `exports` object and attach methods, accessors, and/or values to
it.
Functions created with `Napi::Function::New()`, accessors created with
`PropertyDescriptor::Accessor()`, and values can also be attached. If their
implementation requires the `ExampleAddon` instance, it can be retrieved from
the `Napi::Env env` with `GetInstanceData()`:
```cpp
void ExampleBinding(const Napi::CallbackInfo& info) {
ExampleAddon* addon = info.Env().GetInstanceData<ExampleAddon>();
}
```
## Methods
### Constructor
Creates a new instance of the add-on.
```cpp
Napi::Addon(Napi::Env env, Napi::Object exports);
```
- `[in] env`: The environment into which the add-on is being loaded.
- `[in] exports`: The exports object received from JavaScript.
Typically, the constructor calls `DefineAddon()` to attach methods, accessors,
and/or values to `exports`. The constructor may also create a new object and
pass it to `DefineAddon()` as its first parameter if it wishes to replace the
`exports` object as provided by Node.js.
### DefineAddon
Defines an add-on instance with functions, accessors, and/or values.
```cpp
template <typename T>
void Napi::Addon<T>::DefineAddon(Napi::Object exports,
const std::initializer_list<PropertyDescriptor>& properties);
```
* `[in] exports`: The object to return to Node.js as an instance of the add-on.
* `[in] properties`: Initializer list of add-on property descriptors of the
methods, property accessors, and values that define the add-on. They will be
set on `exports`.
See: [`Class property and descriptor`](class_property_descriptor.md).
### DefineProperties
Defines function, accessor, and/or value properties on an object using add-on
instance methods.
```cpp
template <typename T>
Napi::Object
Napi::Addon<T>::DefineProperties(Napi::Object object,
const std::initializer_list<PropertyDescriptor>& properties);
```
* `[in] object`: The object that will receive the new properties.
* `[in] properties`: Initializer list of property descriptors of the methods,
property accessors, and values to attach to `object`.
See: [`Class property and descriptor`](class_property_descriptor.md).
Returns `object`.
[`Napi::InstanceWrap<T>`]: ./instance_wrap.md

81
node_modules/node-addon-api/doc/array.md generated vendored Normal file
View File

@@ -0,0 +1,81 @@
# Array
Class [`Napi::Array`][] inherits from class [`Napi::Object`][].
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 [`Napi::Int32Array`][] and [`Napi::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::ArrayBuffer`]: ./array_buffer.md
[`Napi::Int32Array`]: ./typed_array_of.md
[`Napi::Object`]: ./object.md
[`Napi::TypedArray`]: ./typed_array.md

149
node_modules/node-addon-api/doc/array_buffer.md generated vendored Normal file
View File

@@ -0,0 +1,149 @@
# ArrayBuffer
Class `Napi::ArrayBuffer` inherits from class [`Napi::Object`][].
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.
### Detach
```cpp
void Napi::ArrayBuffer::Detach();
```
Invokes the `ArrayBuffer` detach operation on a detachable `ArrayBuffer`.
### IsDetached
```cpp
bool Napi::ArrayBuffer::IsDetached() const;
```
Returns `true` if this `ArrayBuffer` has been detached.
[`Napi::Object`]: ./object.md

86
node_modules/node-addon-api/doc/async_context.md generated vendored Normal file
View File

@@ -0,0 +1,86 @@
# 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>();
// Create 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`.
}
```

31
node_modules/node-addon-api/doc/async_operations.md generated vendored Normal file
View File

@@ -0,0 +1,31 @@
# 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)**

427
node_modules/node-addon-api/doc/async_worker.md generated vendored Normal file
View File

@@ -0,0 +1,427 @@
# 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);
```
### OnWorkComplete
This method is invoked after the work has completed on JavaScript thread.
The default implementation of this method checks the status of the work and
tries to dispatch the result to `Napi::AsyncWorker::OnOk` or `Napi::AsyncWorker::Error`
if the work has committed an error. If the work was cancelled, neither
`Napi::AsyncWorker::OnOk` nor `Napi::AsyncWorker::Error` will be invoked.
After the result is dispatched, the default implementation will call into
`Napi::AsyncWorker::Destroy` if `SuppressDestruct()` was not called.
```cpp
virtual void OnWorkComplete(Napi::Env env, napi_status status);
```
### OnExecute
This method is invoked immediately on the work thread when scheduled.
The default implementation of this method just calls the `Napi::AsyncWorker::Execute`
and handles exceptions if cpp exceptions were enabled.
The `OnExecute` method receives an `napi_env` argument. However, the `napi_env`
must NOT be used within this method, as it does not run on the JavaScript
thread and must not run any method that would cause JavaScript to run. In
practice, this means that almost any use of `napi_env` will be incorrect.
```cpp
virtual void OnExecute(Napi::Env env);
```
### 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>
using 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() override {
// Need to simulate cpu heavy task
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void OnOK() override {
HandleScope scope(Env());
Callback().Call({Env().Null(), String::New(Env(), echo)});
}
private:
std::string echo;
};
```
The `EchoWorker`'s constructor 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
// ..
using 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.

View File

@@ -0,0 +1,557 @@
# 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. If you would like to guarantee that there is one invocation of
`OnProgress` for every `Send` call, you should use the `Napi::AsyncProgressQueueWorker`
class instead which is documented further down this page.
```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 along with an
example of how the counterpart in Javascript would appear:
```cpp
#include <napi.h>
#include <chrono>
#include <thread>
using namespace Napi;
class EchoWorker : public AsyncProgressWorker<uint32_t> {
public:
EchoWorker(Function& okCallback, std::string& echo)
: AsyncProgressWorker(okCallback), echo(echo) {}
~EchoWorker() {}
// This code will be executed on the worker thread
void Execute(const ExecutionProgress& progress) {
// Need to simulate cpu heavy task
// Note: This Send() call is not guaranteed to trigger an equal
// number of OnProgress calls (read documentation above for more info)
for (uint32_t i = 0; i < 100; ++i) {
progress.Send(&i, 1)
}
}
void OnError(const Error &e) {
HandleScope scope(Env());
// Pass error onto JS, no data for other parameters
Callback().Call({String::New(Env(), e.Message())});
}
void OnOK() {
HandleScope scope(Env());
// Pass no error, give back original data
Callback().Call({Env().Null(), String::New(Env(), echo)});
}
void OnProgress(const uint32_t* data, size_t /* count */) {
HandleScope scope(Env());
// Pass no error, no echo data, but do pass on the progress data
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
// ..
using namespace Napi;
Value Echo(const CallbackInfo& info) {
// We need to validate the arguments here
std::string in = info[0].As<String>();
Function cb = info[1].As<Function>();
EchoWorker* wk = new EchoWorker(cb, in);
wk->Queue();
return info.Env().Undefined();
}
// Register the native method for JS to access
Object Init(Env env, Object exports)
{
exports.Set(String::New(env, "echo"), Function::New(env, Echo));
return exports;
}
// Register our native addon
NODE_API_MODULE(nativeAddon, Init)
```
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.
Lastly, the following Javascript (ES6+) code would be associated the above example:
```js
const { nativeAddon } = require('binding.node');
const exampleCallback = (errorResponse, okResponse, progressData) => {
// Use the data accordingly
// ...
};
// Call our native addon with the paramters of a string and a function
nativeAddon.echo("example", exampleCallback);
```
# AsyncProgressQueueWorker
`Napi::AsyncProgressQueueWorker` acts exactly like `Napi::AsyncProgressWorker`
except that each progress committed by `Napi::AsyncProgressQueueWorker::ExecutionProgress::Send`
during `Napi::AsyncProgressQueueWorker::Execute` is guaranteed to be
processed by `Napi::AsyncProgressQueueWorker::OnProgress` on the JavaScript
thread in the order it was committed.
For the most basic use, only the `Napi::AsyncProgressQueueWorker::Execute` and
`Napi::AsyncProgressQueueWorker::OnProgress` method must be implemented in a subclass.
# AsyncProgressQueueWorker::ExecutionProcess
A bridge class created before the worker thread execution of `Napi::AsyncProgressQueueWorker::Execute`.
## Methods
### Send
`Napi::AsyncProgressQueueWorker::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::AsyncProgressQueueWorker` so
after the call to `Napi::AsyncProgressQueueWorker::ExecutionProcess::Send` the data can
be safely released.
`Napi::AsyncProgressQueueWorker::ExecutionProcess::Send` guarantees invocation
of `Napi::AsyncProgressQueueWorker::OnProgress`, which means multiple `Send`
call will result in the in-order invocation of `Napi::AsyncProgressQueueWorker::OnProgress`
with each data item.
```cpp
void Napi::AsyncProgressQueueWorker::ExecutionProcess::Send(const T* data, size_t count) const;
```
## Example
The code below show an example of the `Napi::AsyncProgressQueueWorker` implementation, but
also demonsrates how to use multiple `Napi::Function`'s if you wish to provide multiple
callback functions for more object oriented code:
```cpp
#include <napi.h>
#include <chrono>
#include <thread>
using namespace Napi;
class EchoWorker : public AsyncProgressQueueWorker<uint32_t> {
public:
EchoWorker(Function& okCallback, Function& errorCallback, Function& progressCallback, std::string& echo)
: AsyncProgressQueueWorker(okCallback), echo(echo) {
// Set our function references to use them below
this->errorCallback.Reset(errorCallback, 1);
this->progressCallback.Reset(progressCallback, 1);
}
~EchoWorker() {}
// This code will be executed on the worker thread
void Execute(const ExecutionProgress& progress) {
// Need to simulate cpu heavy task to demonstrate that
// every call to Send() will trigger an OnProgress function call
for (uint32_t i = 0; i < 100; ++i) {
progress.Send(&i, 1);
}
}
void OnOK() {
HandleScope scope(Env());
// Call our onOkCallback in javascript with the data we were given originally
Callback().Call({String::New(Env(), echo)});
}
void OnError(const Error &e) {
HandleScope scope(Env());
// We call our callback provided in the constructor with 2 parameters
if (!this->errorCallback.IsEmpty()) {
// Call our onErrorCallback in javascript with the error message
this->errorCallback.Call(Receiver().Value(), {String::New(Env(), e.Message())});
}
}
void OnProgress(const uint32_t* data, size_t /* count */) {
HandleScope scope(Env());
if (!this->progressCallback.IsEmpty()) {
// Call our onProgressCallback in javascript with each integer from 0 to 99 (inclusive)
// as this function is triggered from the above Send() calls
this->progressCallback.Call(Receiver().Value(), {Number::New(Env(), *data)});
}
}
private:
std::string echo;
FunctionReference progressCallback;
FunctionReference errorCallback;
};
```
The `EchoWorker`'s constructor calls the base class' constructor to pass in the
callback that the `Napi::AsyncProgressQueueWorker` base class will store
persistently. When the work on the `Napi::AsyncProgressQueueWorker::Execute`
method is done the `Napi::AsyncProgressQueueWorker::OnOk` method is called and
the results are returned 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::AsyncProgressQueueWorker`.
```cpp
#include <napi.h>
// Include EchoWorker class
// ..
using namespace Napi;
Value Echo(const CallbackInfo& info) {
// We need to validate the arguments here.
std::string in = info[0].As<String>();
Function errorCb = info[1].As<Function>();
Function okCb = info[2].As<Function>();
Function progressCb = info[3].As<Function>();
EchoWorker* wk = new EchoWorker(okCb, errorCb, progressCb, in);
wk->Queue();
return info.Env().Undefined();
}
// Register the native method for JS to access
Object Init(Env env, Object exports)
{
exports.Set(String::New(env, "echo"), Function::New(env, Echo));
return exports;
}
// Register our native addon
NODE_API_MODULE(nativeAddon, Init)
```
The implementation of a `Napi::AsyncProgressQueueWorker` 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::AsyncProgressQueueWorker::Queue`
method that will queue the created worker for execution.
Lastly, the following Javascript (ES6+) code would be associated the above example:
```js
const { nativeAddon } = require('binding.node');
const onErrorCallback = (msg) => {
// Use the data accordingly
// ...
};
const onOkCallback = (echo) => {
// Use the data accordingly
// ...
};
const onProgressCallback = (num) => {
// Use the data accordingly
// ...
};
// Call our native addon with the paramters of a string and three callback functions
nativeAddon.echo("example", onErrorCallback, onOkCallback, onProgressCallback);
```
[`Napi::AsyncWorker`]: ./async_worker.md

97
node_modules/node-addon-api/doc/bigint.md generated vendored Normal file
View File

@@ -0,0 +1,97 @@
# BigInt
Class `Napi::Bigint` inherits from class [`Napi::Value`][].
A JavaScript BigInt value.
## Methods
### New
```cpp
static Napi::BigInt Napi::BigInt::New(Napi::Env env, int64_t value);
static Napi::BigInt Napi::BigInt::New(Napi::Env env, uint64_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::BigInt::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(int* sign_bit, size_t* word_count, 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.
[`Napi::Value`]: ./value.md

68
node_modules/node-addon-api/doc/boolean.md generated vendored Normal file
View File

@@ -0,0 +1,68 @@
# Boolean
Class `Napi::Boolean` inherits from class [`Napi::Value`][].
`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.
### Constructor
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.
[`Napi::Value`]: ./value.md

144
node_modules/node-addon-api/doc/buffer.md generated vendored Normal file
View File

@@ -0,0 +1,144 @@
# Buffer
Class `Napi::Buffer` inherits from class [`Napi::Uint8Array`][].
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.
[`Napi::Uint8Array`]: ./typed_array_of.md

54
node_modules/node-addon-api/doc/callback_scope.md generated vendored Normal file
View File

@@ -0,0 +1,54 @@
# 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.

97
node_modules/node-addon-api/doc/callbackinfo.md generated vendored Normal file
View File

@@ -0,0 +1,97 @@
# 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;
```

32
node_modules/node-addon-api/doc/checker-tool.md generated vendored Normal file
View File

@@ -0,0 +1,32 @@
# 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 omitted it will
start checking from the current directory (`.`).
[checker tool]: ../tools/check-napi.js

View File

@@ -0,0 +1,117 @@
# 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<&Example::GetValue, &Example::SetValue>("value"),
// We can also register a readonly accessor by omitting the setter.
InstanceAccessor<&Example::GetValue>("readOnlyProp")
});
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`

68
node_modules/node-addon-api/doc/cmake-js.md generated vendored Normal file
View File

@@ -0,0 +1,68 @@
# 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)

28
node_modules/node-addon-api/doc/conversion-tool.md generated vendored Normal file
View File

@@ -0,0 +1,28 @@
# 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.

62
node_modules/node-addon-api/doc/creating_a_release.md generated vendored Normal file
View File

@@ -0,0 +1,62 @@
# 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 update 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-new/)**
to validate tests pass (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.

248
node_modules/node-addon-api/doc/dataview.md generated vendored Normal file
View File

@@ -0,0 +1,248 @@
# DataView
Class `Napi::DataView` inherits from class [`Napi::Object`][].
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.
[`Napi::Object`]: ./object.md

68
node_modules/node-addon-api/doc/date.md generated vendored Normal file
View File

@@ -0,0 +1,68 @@
# Date
`Napi::Date` class is a representation of the JavaScript `Date` object. The
`Napi::Date` 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 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();
```

132
node_modules/node-addon-api/doc/env.md generated vendored Normal file
View File

@@ -0,0 +1,132 @@
# 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.
### RunScript
```cpp
Napi::Value Napi::Env::RunScript(____ script);
```
- `[in] script`: A string containing JavaScript code to execute.
Runs JavaScript code contained in a string and returns its result.
The `script` can be any of the following types:
- [`Napi::String`](string.md)
- `const char *`
- `const std::string &`
### GetInstanceData
```cpp
template <typename T> T* GetInstanceData();
```
Returns the instance data that was previously associated with the environment,
or `nullptr` if none was associated.
### SetInstanceData
```cpp
template <typename T> using Finalizer = void (*)(Env, T*);
template <typename T, Finalizer<T> fini = Env::DefaultFini<T>>
void SetInstanceData(T* data);
```
- `[template] fini`: A function to call when the instance data is to be deleted.
Accepts a function of the form `void CleanupData(Napi::Env env, T* data)`. If
not given, the default finalizer will be used, which simply uses the `delete`
operator to destroy `T*` when the addon instance is unloaded.
- `[in] data`: A pointer to data that will be associated with the instance of
the addon for the duration of its lifecycle.
Associates a data item stored at `T* data` with the current instance of the
addon. The item will be passed to the function `fini` which gets called when an
instance of the addon is unloaded.
### SetInstanceData
```cpp
template <typename DataType, typename HintType>
using FinalizerWithHint = void (*)(Env, DataType*, HintType*);
template <typename DataType,
typename HintType,
FinalizerWithHint<DataType, HintType> fini =
Env::DefaultFiniWithHint<DataType, HintType>>
void SetInstanceData(DataType* data, HintType* hint);
```
- `[template] fini`: A function to call when the instance data is to be deleted.
Accepts a function of the form
`void CleanupData(Napi::Env env, DataType* data, HintType* hint)`. If not given,
the default finalizer will be used, which simply uses the `delete` operator to
destroy `T*` when the addon instance is unloaded.
- `[in] data`: A pointer to data that will be associated with the instance of
the addon for the duration of its lifecycle.
- `[in] hint`: A pointer to data that will be associated with the instance of
the addon for the duration of its lifecycle and will be passed as a hint to
`fini` when the addon instance is unloaded.
Associates a data item stored at `T* data` with the current instance of the
addon. The item will be passed to the function `fini` which gets called when an
instance of the addon is unloaded. This overload accepts an additional hint to
be passed to `fini`.

120
node_modules/node-addon-api/doc/error.md generated vendored Normal file
View File

@@ -0,0 +1,120 @@
# Error
Class `Napi::Error` inherits from class [`Napi::ObjectReference`][] and class [`std::exception`][].
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.
[`Napi::ObjectReference`]: ./object_reference.md
[`std::exception`]: https://cplusplus.com/reference/exception/exception/

186
node_modules/node-addon-api/doc/error_handling.md generated vendored Normal file
View File

@@ -0,0 +1,186 @@
# 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.

View File

@@ -0,0 +1,82 @@
# 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 garbage 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`.

63
node_modules/node-addon-api/doc/external.md generated vendored Normal file
View File

@@ -0,0 +1,63 @@
# External (template)
Class `Napi::External<T>` inherits from class [`Napi::Value`][].
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.
[`Napi::Value`]: ./value.md

402
node_modules/node-addon-api/doc/function.md generated vendored Normal file
View File

@@ -0,0 +1,402 @@
# 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)).
> For callbacks that will be called with asynchronous events from a
> non-JavaScript thread, please refer to [`Napi::ThreadSafeFunction`][] for more
> examples.
## 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<Fn>(env));
return exports;
}
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).
## Type definitions
### Napi::Function::VoidCallback
This is the type describing a callback returning `void` that will be invoked
from JavaScript.
```cpp
typedef void (*VoidCallback)(const Napi::CallbackInfo& info);
```
### Napi::Function::Callback
This is the type describing a callback returning a value that will be invoked
from JavaScript.
```cpp
typedef Value (*Callback)(const Napi::CallbackInfo& info);
```
## 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 <Napi::VoidCallback cb>
static Napi::Function New(napi_env env,
const char* utf8name = nullptr,
void* data = nullptr);
```
- `[template] cb`: The native function to invoke when the JavaScript function is
invoked.
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object.
- `[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
Creates an instance of a `Napi::Function` object.
```cpp
template <Napi::Callback cb>
static Napi::Function New(napi_env env,
const char* utf8name = nullptr,
void* data = nullptr);
```
- `[template] cb`: The native function to invoke when the JavaScript function is
invoked.
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object.
- `[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
Creates an instance of a `Napi::Function` object.
```cpp
template <Napi::VoidCallback cb>
static Napi::Function New(napi_env env,
const std::string& utf8name,
void* data = nullptr);
```
- `[template] cb`: The native function to invoke when the JavaScript function is
invoked.
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object.
- `[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 an instance of a `Napi::Function` object.
```cpp
template <Napi::Callback cb>
static Napi::Function New(napi_env env,
const std::string& utf8name,
void* data = nullptr);
```
- `[template] cb`: The native function to invoke when the JavaScript function is
invoked.
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object.
- `[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 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 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(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 constructor 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.
[`Napi::ThreadSafeFunction`]: ./threadsafe_function.md

238
node_modules/node-addon-api/doc/function_reference.md generated vendored Normal file
View File

@@ -0,0 +1,238 @@
# 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 constructor 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.

13
node_modules/node-addon-api/doc/generator.md generated vendored Normal file
View File

@@ -0,0 +1,13 @@
# 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)

65
node_modules/node-addon-api/doc/handle_scope.md generated vendored Normal file
View File

@@ -0,0 +1,65 @@
# 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 garbage collector will do this.
### Env
```cpp
Napi::Env Napi::HandleScope::Env() const;
```
Returns the `Napi::Env` associated with the `Napi::HandleScope`.

91
node_modules/node-addon-api/doc/hierarchy.md generated vendored Normal file
View File

@@ -0,0 +1,91 @@
# Full Class Hierarchy
| Class | Parent Class(es) |
|---|---|
| [`Napi::Addon`][] | [`Napi::InstanceWrap`][] |
| [`Napi::Array`][] | [`Napi::Object`][] |
| [`Napi::ArrayBuffer`][] | [`Napi::Object`][] |
| [`Napi::AsyncContext`][] | |
| [`Napi::AsyncProgressQueueWorker`][] | `Napi::AsyncProgressWorkerBase` |
| [`Napi::AsyncProgressWorker`][] | `Napi::AsyncProgressWorkerBase` |
| [`Napi::AsyncWorker`][] | |
| [`Napi::BigInt`][] | [`Napi::Value`][] |
| [`Napi::Boolean`][] | [`Napi::Value`][] |
| [`Napi::Buffer`][] | [`Napi::Uint8Array`][] |
| [`Napi::CallbackInfo`][] | |
| [`Napi::CallbackScope`][] | |
| [`Napi::ClassPropertyDescriptor`][] | |
| [`Napi::DataView`][] | [`Napi::Object`][] |
| [`Napi::Date`][] | [`Napi::Value`][] |
| [`Napi::Env`][] | |
| [`Napi::Error`][] | [`Napi::ObjectReference`][], [`std::exception`][] |
| [`Napi::EscapableHandleScope`][] | |
| [`Napi::External`][] | [`Napi::Value`][] |
| [`Napi::Function`][] | [`Napi::Object`][] |
| [`Napi::FunctionReference`][] | [`Napi::Reference<Napi::Function>`][] |
| [`Napi::HandleScope`][] | |
| [`Napi::InstanceWrap`][] | |
| [`Napi::MemoryManagement`][] | |
| [`Napi::Name`][] | [`Napi::Value`][] |
| [`Napi::Number`][] | [`Napi::Value`][] |
| [`Napi::Object`][] | [`Napi::Value`][] |
| [`Napi::ObjectReference`][] | [`Napi::Reference<Napi::Object>`][] |
| [`Napi::ObjectWrap`][] | [`Napi::InstanceWrap`][], [`Napi::Reference<Napi::Object>`][] |
| [`Napi::Promise`][] | [`Napi::Object`][] |
| [`Napi::PropertyDescriptor`][] | |
| [`Napi::RangeError`][] | [`Napi::Error`][] |
| [`Napi::Reference`] | |
| [`Napi::String`][] | [`Napi::Name`][] |
| [`Napi::Symbol`][] | [`Napi::Name`][] |
| [`Napi::ThreadSafeFunction`][] | |
| [`Napi::TypeError`][] | [`Napi::Error`][] |
| [`Napi::TypedArray`][] | [`Napi::Object`][] |
| [`Napi::TypedArrayOf`][] | [`Napi::TypedArray`][] |
| [`Napi::Value`][] | |
| [`Napi::VersionManagement`][] | |
[`Napi::Addon`]: ./addon.md
[`Napi::Array`]: ./array.md
[`Napi::ArrayBuffer`]: ./array_buffer.md
[`Napi::AsyncContext`]: ./async_context.md
[`Napi::AsyncProgressQueueWorker`]: ./async_worker_variants.md#asyncprogressqueueworker
[`Napi::AsyncProgressWorker`]: ./async_worker_variants.md#asyncprogressworker
[`Napi::AsyncWorker`]: ./async_worker.md
[`Napi::BigInt`]: ./bigint.md
[`Napi::Boolean`]: ./boolean.md
[`Napi::Buffer`]: ./buffer.md
[`Napi::CallbackInfo`]: ./callbackinfo.md
[`Napi::CallbackScope`]: ./callback_scope.md
[`Napi::ClassPropertyDescriptor`]: ./class_property_descriptor.md
[`Napi::DataView`]: ./dataview.md
[`Napi::Date`]: ./date.md
[`Napi::Env`]: ./env.md
[`Napi::Error`]: ./error.md
[`Napi::EscapableHandleScope`]: ./escapable_handle_scope.md
[`Napi::External`]: ./external.md
[`Napi::Function`]: ./function.md
[`Napi::FunctionReference`]: ./function_reference.md
[`Napi::HandleScope`]: ./handle_scope.md
[`Napi::InstanceWrap`]: ./instance_wrap.md
[`Napi::MemoryManagement`]: ./memory_management.md
[`Napi::Name`]: ./name.md
[`Napi::Number`]: ./number.md
[`Napi::Object`]: ./object.md
[`Napi::ObjectReference`]: ./object_reference.md
[`Napi::ObjectWrap`]: ./object_wrap.md
[`Napi::Promise`]: ./promise.md
[`Napi::PropertyDescriptor`]: ./property_descriptor.md
[`Napi::RangeError`]: ./range_error.md
[`Napi::Reference`]: ./reference.md
[`Napi::Reference<Napi::Function>`]: ./reference.md
[`Napi::Reference<Napi::Object>`]: ./reference.md
[`Napi::String`]: ./string.md
[`Napi::Symbol`]: ./symbol.md
[`Napi::ThreadSafeFunction`]: ./thread_safe_function.md
[`Napi::TypeError`]: ./type_error.md
[`Napi::TypedArray`]: ./typed_array.md
[`Napi::TypedArrayOf`]: ./typed_array_of.md
[`Napi::Uint8Array`]: ./typed_array_of.md
[`Napi::Value`]: ./value.md
[`Napi::VersionManagement`]: ./version_management.md
[`std::exception`]: https://cplusplus.com/reference/exception/exception/

408
node_modules/node-addon-api/doc/instance_wrap.md generated vendored Normal file
View File

@@ -0,0 +1,408 @@
# InstanceWrap<T>
This class serves as the base class for [`Napi::ObjectWrap<T>`][] and
[`Napi::Addon<T>`][].
In the case of [`Napi::Addon<T>`][] it provides the
methods for exposing functions to JavaScript on instances of an add-on.
As a base class for [`Napi::ObjectWrap<T>`][] it provides the methods for
exposing instance methods of JavaScript objects instantiated from the JavaScript
class corresponding to the subclass of [`Napi::ObjectWrap<T>`][].
## Methods
### InstanceMethod
Creates a property descriptor that represents a method exposed on JavaScript
instances of this class.
```cpp
template <typename T>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::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 the method
provided by instances of the class.
- `[in] method`: The native function that represents a method provided by the
add-on.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the method when it is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents a method
provided by instances of the class. The method must be of the form
```cpp
void MethodName(const Napi::CallbackInfo& info);
```
### InstanceMethod
Creates a property descriptor that represents a method exposed on JavaScript
instances of this class.
```cpp
template <typename T>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::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 the method
provided by instances of the class.
- `[in] method`: The native function that represents a method provided by the
add-on.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the method when it is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents a method
provided by instances of the class. The method must be of the form
```cpp
Napi::Value MethodName(const Napi::CallbackInfo& info);
```
### InstanceMethod
Creates a property descriptor that represents a method exposed on JavaScript
instances of this class.
```cpp
template <typename T>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::InstanceMethod(Napi::Symbol name,
InstanceVoidMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] name`: JavaScript symbol that represents the name of the method provided
by instances of the class.
- `[in] method`: The native function that represents a method provided by the
add-on.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the method when it is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents a method
provided by instances of the class. The method must be of the form
```cpp
void MethodName(const Napi::CallbackInfo& info);
```
### InstanceMethod
Creates a property descriptor that represents a method exposed on JavaScript
instances of this class.
```cpp
template <typename T>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::InstanceMethod(Napi::Symbol name,
InstanceMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] name`: JavaScript symbol that represents the name of the method provided
by instances of the class.
- `[in] method`: The native function that represents a method provided by the
add-on.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the method when it is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents a method
provided by instances of the class. The method must be of the form
```cpp
Napi::Value MethodName(const Napi::CallbackInfo& info);
```
### InstanceMethod
Creates a property descriptor that represents a method exposed on JavaScript
instances of this class.
```cpp
<template typename T>
template <typename InstanceWrap<T>::InstanceVoidMethodCallback method>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap::InstanceMethod(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] method`: The native function that represents a method provided by the
add-on.
- `[in] utf8name`: Null-terminated string that represents the name of the method
provided by instances of the class.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the method when it is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents a method
provided by instances of the class. The method must be of the form
```cpp
void MethodName(const Napi::CallbackInfo& info);
```
### InstanceMethod
Creates a property descriptor that represents a method exposed on JavaScript
instances of this class.
```cpp
template <typename T>
template <typename InstanceWrap<T>::InstanceMethodCallback method>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::InstanceMethod(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] method`: The native function that represents a method provided by the
add-on.
- `[in] utf8name`: Null-terminated string that represents the name of the method
provided by instances of the class.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the method when it is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents a method
provided by instances of the class. The method must be of the form
```cpp
Napi::Value MethodName(const Napi::CallbackInfo& info);
```
### InstanceMethod
Creates a property descriptor that represents a method exposed on JavaScript
instances of this class.
```cpp
template <typename T>
template <typename InstanceWrap<T>::InstanceVoidMethodCallback method>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::InstanceMethod(Napi::Symbol name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] method`: The native function that represents a method provided by the
add-on.
- `[in] name`: The `Napi::Symbol` object whose value is used to identify the
instance method for the class.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the method when it is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents a method
provided by instances of the class. The method must be of the form
```cpp
void MethodName(const Napi::CallbackInfo& info);
```
### InstanceMethod
Creates a property descriptor that represents a method exposed on JavaScript
instances of this class.
```cpp
template <typename T>
template <InstanceWrap<T>::InstanceMethodCallback method>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::InstanceMethod(Napi::Symbol name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] method`: The native function that represents a method provided by the
add-on.
- `[in] name`: The `Napi::Symbol` object whose value is used to identify the
instance method for the class.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the method when it is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents a method
provided by instances of the class. The method must be of the form
```cpp
Napi::Value MethodName(const Napi::CallbackInfo& info);
```
### InstanceAccessor
Creates a property descriptor that represents a property exposed on JavaScript
instances of this class.
```cpp
template <typename T>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::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 the method
provided by instances of the class.
- `[in] getter`: The native function to call when a get access to the property
is performed.
- `[in] setter`: The native function to call when a set access to the property
is performed.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the getter or the setter when it
is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents an instance
accessor property provided by instances of the class.
### InstanceAccessor
Creates a property descriptor that represents a property exposed on JavaScript
instances of this class.
```cpp
template <typename T>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::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 property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the getter or the setter when it
is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents an instance
accessor property provided instances of the class.
### InstanceAccessor
Creates a property descriptor that represents a property exposed on JavaScript
instances of this class.
```cpp
template <typename T>
template <typename InstanceWrap<T>::InstanceGetterCallback getter,
typename InstanceWrap<T>::InstanceSetterCallback setter=nullptr>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::InstanceAccessor(const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[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] utf8name`: Null-terminated string that represents the name of the method
provided by instances of the class.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the getter or the setter when it
is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents an instance
accessor property provided by instances of the class.
### InstanceAccessor
Creates a property descriptor that represents a property exposed on JavaScript
instances of this class.
```cpp
template <typename T>
template <typename InstanceWrap<T>::InstanceGetterCallback getter,
typename InstanceWrap<T>::InstanceSetterCallback setter=nullptr>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::InstanceAccessor(Symbol name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[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] name`: The `Napi::Symbol` object whose value is used to identify the
instance accessor.
- `[in] attributes`: The attributes associated with the property. One or more of
`napi_property_attributes`.
- `[in] data`: User-provided data passed into the getter or the setter when it
is invoked.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents an instance
accessor property provided by instances of the class.
### InstanceValue
Creates property descriptor that represents a value exposed on JavaScript
instances of this class.
```cpp
template <typename T>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::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 associated with the property. One or more of
`napi_property_attributes`.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents an instance
value property of an add-on.
### InstanceValue
Creates property descriptor that represents a value exposed on JavaScript
instances of this class.
```cpp
template <typename T>
static Napi::ClassPropertyDescriptor<T>
Napi::InstanceWrap<T>::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 associated with the property. One or more of
`napi_property_attributes`.
Returns a `Napi::ClassPropertyDescriptor<T>` object that represents an instance
value property of an add-on.
[`Napi::Addon<T>`]: ./addon.md
[`Napi::ObjectWrap<T>`]: ./object_wrap.md

27
node_modules/node-addon-api/doc/memory_management.md generated vendored Normal file
View File

@@ -0,0 +1,27 @@
# 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.

29
node_modules/node-addon-api/doc/name.md generated vendored Normal file
View File

@@ -0,0 +1,29 @@
# Name
Class `Napi::Name` inherits from class [`Napi::Value`][].
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.
[`Napi::Value`]: ./value.md

82
node_modules/node-addon-api/doc/node-gyp.md generated vendored Normal file
View File

@@ -0,0 +1,82 @@
# 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)

163
node_modules/node-addon-api/doc/number.md generated vendored Normal file
View File

@@ -0,0 +1,163 @@
# 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.
### Constructor
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();
```

279
node_modules/node-addon-api/doc/object.md generated vendored Normal file
View File

@@ -0,0 +1,279 @@
# Object
Class `Napi::Object` inherits from class [`Napi::Value`][].
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::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`
### Delete()
```cpp
bool Napi::Object::Delete(____ key);
```
- `[in] key`: The name of the property to delete.
Deletes the property associated with the given key. Returns `true` if the property was deleted.
The `key` can be any of the following types:
- `napi_value`
- [`Napi::Value`](value.md)
- `const char *`
- `const std::string &`
- `uint32_t`
### 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()`.
### GetPropertyNames()
```cpp
Napi::Array Napi::Object::GetPropertyNames() const;
```
Returns the names of the enumerable properties of the object as a [`Napi::Array`](array.md) of strings.
The properties whose key is a `Symbol` will not be included.
### HasOwnProperty()
```cpp
bool Napi::Object::HasOwnProperty(____ key); const
```
- `[in] key` The name of the property to check.
Returns a `bool` that is *true* if the object has an own property named `key` and *false* otherwise.
The key can be any of the following types:
- `napi_value`
- [`Napi::Value`](value.md)
- `const char*`
- `const std::string&`
- `uint32_t`
### 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).
[`Napi::Value`]: ./value.md

View File

@@ -0,0 +1,83 @@
# 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 inner 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 newValue
};
```
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`.

117
node_modules/node-addon-api/doc/object_reference.md generated vendored Normal file
View File

@@ -0,0 +1,117 @@
# 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 namespace 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`

561
node_modules/node-addon-api/doc/object_wrap.md generated vendored Normal file
View File

@@ -0,0 +1,561 @@
# Object Wrap
Class `Napi::ObjectWrap<T>` inherits from class [`Napi::InstanceWrap<T>`][].
The `Napi::ObjectWrap<T>` 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<T>` 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);
static Napi::Value CreateNewItem(const Napi::CallbackInfo& info);
private:
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<&Example::GetValue>("GetValue"),
InstanceMethod<&Example::SetValue>("SetValue"),
StaticMethod<&Example::CreateNewItem>("CreateNewItem"),
});
Napi::FunctionReference* constructor = new Napi::FunctionReference();
// Create a persistent 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);
exports.Set("Example", func);
// Store the constructor as the add-on instance data. This will allow this
// add-on to support multiple instances of itself running on multiple worker
// threads, as well as multiple instances of itself running in different
// contexts on the same thread.
//
// By default, the value set on the environment here will be destroyed when
// the add-on is unloaded using the `delete` operator, but it is also
// possible to supply a custom deleter.
env.SetInstanceData<Napi::FunctionReference>(constructor);
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::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;
}
// Create a new item using the constructor stored during Init.
Napi::Value Example::CreateNewItem(const Napi::CallbackInfo& info) {
// Retrieve the instance data we stored during `Init()`. We only stored the
// constructor there, so we retrieve it here to create a new instance of the
// JS class the constructor represents.
Napi::FunctionReference* constructor =
info.Env().GetInstanceData<Napi::FunctionReference>();
return constructor->New({ Napi::Number::New(info.Env(), 42) });
}
// 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 instance 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.
### StaticMethod
Creates property descriptor that represents a static method of a JavaScript
class.
```cpp
template <StaticVoidMethodCallback method>
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(
const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] method`: The native function that represents a static method of a
JavaScript class. This function returns nothing.
- `[in] utf8name`: Null-terminated string that represents the name of a static
method for the 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
template <StaticMethodCallback method>
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(
const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] method`: The native function that represents a static method of a
JavaScript class.
- `[in] utf8name`: Null-terminated string that represents the name of a static
method for the 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
template <StaticVoidMethodCallback method>
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(Symbol name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] method`: The native function that represents a static method of a
JavaScript class.
- `[in] name`: Napi:Symbol that represents the name of a static
method for the 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
template <StaticMethodCallback method>
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(Symbol name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] method`: The native function that represents a static method of a
JavaScript class.
- `[in] name`: Napi:Symbol that represents the name of a static.
- `[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.
### StaticAccessor
Creates property descriptor that represents a static accessor property of a
JavaScript class.
```cpp
template <StaticGetterCallback getter, StaticSetterCallback setter=nullptr>
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticAccessor(
const char* utf8name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[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] utf8name`: Null-terminated string that represents the name of a static
accessor property for the class.
- `[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
template <StaticGetterCallback getter, StaticSetterCallback setter=nullptr>
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticAccessor(Symbol name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[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] name`: Napi:Symbol that represents the name of a static accessor.
- `[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.
### 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
[`Napi::InstanceWrap<T>`]: ./instance_wrap.md

16
node_modules/node-addon-api/doc/prebuild_tools.md generated vendored Normal file
View File

@@ -0,0 +1,16 @@
# 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 distribute the native add-on in pre-built form for different platform
and architectures. The prebuild tools help to create and distribute 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)**

79
node_modules/node-addon-api/doc/promises.md generated vendored Normal file
View File

@@ -0,0 +1,79 @@
# Promise
Class `Napi::Promise` inherits from class [`Napi::Object`][].
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`.
[`Napi::Object`]: ./object.md

286
node_modules/node-addon-api/doc/property_descriptor.md generated vendored Normal file
View File

@@ -0,0 +1,286 @@
# Property Descriptor
A [`Napi::Object`](object.md) can be assigned properties via its [`DefineProperty`](object.md#defineproperty) and [`DefineProperties`](object.md#defineproperties) functions, which take PropertyDescriptor(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<TestGetter>("pd1");
PropertyDescriptor pd2 =
PropertyDescriptor::Accessor<TestGetter, TestSetter>("pd2");
// 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});
}
```
## Types
### PropertyDescriptor::GetterCallback
```cpp
typedef Napi::Value (*GetterCallback)(const Napi::CallbackInfo& info);
```
This is the signature of a getter function to be passed as a template parameter
to `PropertyDescriptor::Accessor`.
### PropertyDescriptor::SetterCallback
```cpp
typedef void (*SetterCallback)(const Napi::CallbackInfo& info);
```
This is the signature of a setter function to be passed as a template parameter
to `PropertyDescriptor::Accessor`.
## 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
template <Napi::PropertyDescriptor::GetterCallback Getter>
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor (___ name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
* `[template] 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 read-only property.
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `napi_value value`
- `Napi::Name`
```cpp
template <
Napi::PropertyDescriptor::GetterCallback Getter,
Napi::PropertyDescriptor::SetterCallback Setter>
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor (___ name,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
* `[template] Getter`: A getter function.
* `[template] Setter`: A 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 PropertyDescriptor that contains a read-write property.
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `napi_value value`
- `Napi::Name`
```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 environment 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 environment 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).

59
node_modules/node-addon-api/doc/range_error.md generated vendored Normal file
View File

@@ -0,0 +1,59 @@
# 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.

111
node_modules/node-addon-api/doc/reference.md generated vendored Normal file
View File

@@ -0,0 +1,111 @@
# 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.

81
node_modules/node-addon-api/doc/setup.md generated vendored Normal file
View File

@@ -0,0 +1,81 @@
# 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_dir\")"],
```
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.

93
node_modules/node-addon-api/doc/string.md generated vendored Normal file
View File

@@ -0,0 +1,93 @@
# String
Class `Napi::String` inherits from class [`Napi::Name`][].
## 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 a UTF8 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.
[`Napi::Name`]: ./name.md

48
node_modules/node-addon-api/doc/symbol.md generated vendored Normal file
View File

@@ -0,0 +1,48 @@
# Symbol
Class `Napi::Symbol` inherits from class [`Napi::Name`][].
## 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&` - UTF8 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.
[`Napi::Name`]: ./name.md

121
node_modules/node-addon-api/doc/threadsafe.md generated vendored Normal file
View File

@@ -0,0 +1,121 @@
# Thread-safe Functions
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 two types --
[`Napi::ThreadSafeFunction`](threadsafe_function.md) and
[`Napi::TypedThreadSafeFunction`](typed_threadsafe_function.md) -- as well as
APIs to create, destroy, and call objects of this type. The differences between
the two are subtle and are [highlighted below](#implementation-differences).
Regardless of which type you choose, the APIs between the two are similar.
`Napi::[Typed]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::[Typed]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::[Typed]ThreadSafeFunction` is destroyed.
It is important that `Release()` be the last API call made in conjunction with a
given `Napi::[Typed]ThreadSafeFunction`, because after the call completes, there
is no guarantee that the `Napi::[Typed]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::[Typed]ThreadSafeFunction` can be freed in its `Finalizer`
callback which was passed to `[Typed]ThreadSafeFunction::New()`.
Once the number of threads making use of a `Napi::[Typed]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`.
## Implementation Differences
The choice between `Napi::ThreadSafeFunction` and
`Napi::TypedThreadSafeFunction` depends largely on how you plan to execute your
native C++ code (the "callback") on the Node.js thread.
### [`Napi::ThreadSafeFunction`](threadsafe_function.md)
This API is designed without N-API 5 native support for [the optional JavaScript
function callback feature](https://github.com/nodejs/node/commit/53297e66cb).
This API has some dynamic functionality, in that:
- The `[Non]BlockingCall()` methods provide a `Napi::Function` parameter as the
callback to run when processing the data item on the main thread -- the
`CallJs` callback. Since the callback is a parameter, it can be changed for
every call.
- Different C++ data types may be passed with each call of `[Non]BlockingCall()`
to match the specific data type as specified in the `CallJs` callback.
Note that this functionality comes with some **additional overhead** and
situational **memory leaks**:
- The API acts as a "broker" between the underlying `napi_threadsafe_function`,
and dynamically constructs a wrapper for your callback on the heap for every
call to `[Non]BlockingCall()`.
- In acting in this "broker" fashion, the API will call the underlying "make
call" N-API method on this packaged item. If the API has determined the
thread-safe function is no longer accessible (eg. all threads have released
yet there are still items on the queue), **the callback passed to
[Non]BlockingCall will not execute**. This means it is impossible to perform
clean-up for calls that never execute their `CallJs` callback. **This may lead
to memory leaks** if you are dynamically allocating memory.
- The `CallJs` does not receive the thread-safe function's context as a
parameter. In order for the callback to access the context, it must have a
reference to either (1) the context directly, or (2) the thread-safe function
to call `GetContext()`. Furthermore, the `GetContext()` method is not
_type-safe_, as the method returns an object that can be "any-casted", instead
of having a static type.
### [`Napi::TypedThreadSafeFunction`](typed_threadsafe_function.md)
The `TypedThreadSafeFunction` class is a new implementation to address the
drawbacks listed above. The API is designed with N-API 5's support of an
optional function callback. The API will correctly allow developers to pass
`std::nullptr` instead of a `const Function&` for the callback function
specified in `::New`. It also provides helper APIs to _target_ N-API 4 and
construct a no-op `Function` **or** to target N-API 5 and "construct" a
`std::nullptr` callback. This allows a single codebase to use the same APIs,
with just a switch of the `NAPI_VERSION` compile-time constant.
The removal of the dynamic call functionality has the following implications:
- The API does _not_ act as a "broker" compared to the
`Napi::ThreadSafeFunction`. Once Node.js finalizes the thread-safe function,
the `CallJs` callback will execute with an empty `Napi::Env` for any remaining
items on the queue. This provides the ability to handle any necessary cleanup
of the item's data.
- The callback _does_ receive the context as a parameter, so a call to
`GetContext()` is _not_ necessary. This context type is specified as the
**first template argument** specified to `::New`, ensuring type safety.
- The `New()` constructor accepts the `CallJs` callback as the **second type
argument**. The callback must be statically defined for the API to access it.
This affords the ability to statically pass the context as the correct type
across all methods.
- Only one C++ data type may be specified to every call to `[Non]BlockingCall()`
-- the **third template argument** specified to `::New`. Any "dynamic call
data" must be implemented by the user.
### Usage Suggestions
In summary, it may be best to use `Napi::TypedThreadSafeFunction` if:
- static, compile-time support for targeting N-API 4 or 5+ with an optional
JavaScript callback feature is desired;
- the callback can have `static` storage class and will not change across calls
to `[Non]BlockingCall()`;
- cleanup of items' data is required (eg. deleting dynamically-allocated data
that is created at the caller level).
Otherwise, `Napi::ThreadSafeFunction` may be a better choice.

290
node_modules/node-addon-api/doc/threadsafe_function.md generated vendored Normal file
View File

@@ -0,0 +1,290 @@
# ThreadSafeFunction
The `Napi::ThreadSafeFunction` type provides APIs for threads to communicate
with the addon's main thread to invoke JavaScript functions on their behalf.
Documentation can be found for an [overview of the API](threadsafe.md), as well
as [differences between the two thread-safe function
APIs](threadsafe.md#implementation-differences).
## 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`. It
can be retreived by calling `GetContext()`.
- `[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,
ContextType* hint)`, skipping `data` or `hint` if they are not provided. Can
be retrieved 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 attempting 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 attempting 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 attempting 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 ]
```

59
node_modules/node-addon-api/doc/type_error.md generated vendored Normal file
View File

@@ -0,0 +1,59 @@
# 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.

78
node_modules/node-addon-api/doc/typed_array.md generated vendored Normal file
View File

@@ -0,0 +1,78 @@
# TypedArray
Class `Napi::TypedArray` inherits from class [`Napi::Object`][].
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.
[`Napi::Object`]: ./object.md

137
node_modules/node-addon-api/doc/typed_array_of.md generated vendored Normal file
View File

@@ -0,0 +1,137 @@
# TypedArrayOf
Class `Napi::TypedArrayOf<T>` inherits from class [`Napi::TypedArray`][].
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.
[`Napi::TypedArray`]: ./typed_array.md

View File

@@ -0,0 +1,307 @@
# TypedThreadSafeFunction
The `Napi::TypedThreadSafeFunction` type provides APIs for threads to
communicate with the addon's main thread to invoke JavaScript functions on their
behalf. The type is a three-argument templated class, each argument representing
the type of:
- `ContextType = std::nullptr_t`: The thread-safe function's context. By
default, a TSFN has no context.
- `DataType = void*`: The data to use in the native callback. By default, a TSFN
can accept any data type.
- `Callback = void(*)(Napi::Env, Napi::Function jsCallback, ContextType*,
DataType*)`: The callback to run for each item added to the queue. If no
`Callback` is given, the API will call the function `jsCallback` with no
arguments.
Documentation can be found for an [overview of the API](threadsafe.md), as well
as [differences between the two thread-safe function
APIs](threadsafe.md#implementation-differences).
## Methods
### Constructor
Creates a new empty instance of `Napi::TypedThreadSafeFunction`.
```cpp
Napi::Function::TypedThreadSafeFunction<ContextType, DataType, Callback>::TypedThreadSafeFunction();
```
### Constructor
Creates a new instance of the `Napi::TypedThreadSafeFunction` object.
```cpp
Napi::TypedThreadSafeFunction<ContextType, DataType, Callback>::TypedThreadSafeFunction(napi_threadsafe_function tsfn);
```
- `tsfn`: The `napi_threadsafe_function` which is a handle for an existing
thread-safe function.
Returns a non-empty `Napi::TypedThreadSafeFunction` instance. To ensure the API
statically handles the correct return type for `GetContext()` and
`[Non]BlockingCall()`, pass the proper template arguments to
`Napi::TypedThreadSafeFunction`.
### New
Creates a new instance of the `Napi::TypedThreadSafeFunction` 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,
CallbackType callback,
const Object& resource,
ResourceString resourceName,
size_t maxQueueSize,
size_t initialThreadCount,
ContextType* context,
Finalizer finalizeCallback,
FinalizerDataType* data = nullptr);
```
- `env`: The `napi_env` environment in which to construct the
`Napi::ThreadSafeFunction` object.
- `[optional] 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`. It
can be retreived via `GetContext()`.
- `[optional] finalizeCallback`: Function to call when the
`TypedThreadSafeFunction` 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,
FinalizerDataType* data, ContextType* hint)`.
- `[optional] data`: Data to be passed to `finalizeCallback`.
Returns a non-empty `Napi::TypedThreadSafeFunction` instance.
Depending on the targetted `NAPI_VERSION`, the API has different implementations
for `CallbackType callback`.
When targetting version 4, `callback` may be:
- of type `const Function&`
- not provided as a parameter, in which case the API creates a new no-op
`Function`
When targetting version 5+, `callback` may be:
- of type `const Function&`
- of type `std::nullptr_t`
- not provided as a parameter, in which case the API passes `std::nullptr`
### Acquire
Adds 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::TypedThreadSafeFunction<ContextType, DataType, Callback>::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
Indicates 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 the thread-safe function may
have been destroyed.
```cpp
napi_status Napi::TypedThreadSafeFunction<ContextType, DataType, Callback>::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
"Aborts" 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::TypedThreadSafeFunction<ContextType, DataType, Callback>::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.
```cpp
napi_status Napi::TypedThreadSafeFunction<ContextType, DataType, Callback>::BlockingCall(DataType* data = nullptr) const
napi_status Napi::TypedThreadSafeFunction<ContextType, DataType, Callback>::NonBlockingCall(DataType* data = nullptr) const
```
- `[optional] data`: Data to pass to the callback which was passed to
`TypedThreadSafeFunction::New()`.
Returns one of:
- `napi_ok`: `data` 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 no further calls can
be made.
- `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 <napi.h>
#include <thread>
using namespace Napi;
using Context = Reference<Value>;
using DataType = int;
void CallJs(Napi::Env env, Function callback, Context *context, DataType *data);
using TSFN = TypedThreadSafeFunction<Context, DataType, CallJs>;
using FinalizerDataType = void;
std::thread nativeThread;
TSFN 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 new context set to the the receiver (ie, `this`) of the function
// call
Context *context = new Reference<Value>(Persistent(info.This()));
// Create a ThreadSafeFunction
tsfn = TSFN::New(
env,
info[0].As<Function>(), // JavaScript function called asynchronously
"Resource Name", // Name
0, // Unlimited queue
1, // Only one thread will use this initially
context,
[](Napi::Env, FinalizerDataType *,
Context *ctx) { // Finalizer used to clean threads up
nativeThread.join();
delete ctx;
});
// Create a native thread
nativeThread = std::thread([count] {
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);
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);
}
// Transform native data into JS data, passing it to the provided
// `callback` -- the TSFN's JavaScript function.
void CallJs(Napi::Env env, Function callback, Context *context,
DataType *data) {
// Is the JavaScript environment still available to call into, eg. the TSFN is
// not aborted
if (env != nullptr) {
// On N-API 5+, the `callback` parameter is optional; however, this example
// does ensure a callback is provided.
if (callback != nullptr) {
callback.Call(context->Value(), {Number::New(env, *data)});
}
}
if (data != nullptr) {
// We're finished with the data.
delete data;
}
}
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.call(new Date(), function (clock) {
const context = this;
console.log(context, clock);
}, 5);
```
When executed, the output will show the value of `clock()` five times at one
second intervals, prefixed with the TSFN's context -- `start`'s receiver (ie,
`new Date()`):
```
2020-08-18T21:04:25.116Z 49824
2020-08-18T21:04:25.116Z 62493
2020-08-18T21:04:25.116Z 62919
2020-08-18T21:04:25.116Z 63228
2020-08-18T21:04:25.116Z 63531
```

340
node_modules/node-addon-api/doc/value.md generated vendored Normal file
View File

@@ -0,0 +1,340 @@
# Value
`Napi::Value` is the C++ manifestation of a JavaScript value. It is the base
class upon which other JavaScript values such as `Napi::Number`,
`Napi::Boolean`, `Napi::String`, and `Napi::Object` are based. 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.
## Constructors
### 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`
## 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 Napi::Value& other) const;
```
Returns `true` if this value strictly equals another value, or `false`
otherwise.
### operator !=
```cpp
bool Napi::Value::operator !=(const Napi::Value& other) const;
```
Returns `false` if this value strictly equals another value, or `true`
otherwise.
## Methods
### 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`.
### Env
```cpp
Napi::Env Napi::Value::Env() const;
```
Returns the `Napi::Env` environment this value is associated with. See
[`Napi::Env`](env.md) for more details about environments.
### 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.
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`.
### 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.
### 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.
### IsBuffer
```cpp
bool Napi::Value::IsBuffer() const;
```
Returns `true` if the underlying value is a Node.js `Napi::Buffer` or `false`
otherwise.
### IsDataView
```cpp
bool Napi::Value::IsDataView() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::DataView` or
`false` otherwise.
### IsDate
```cpp
bool Napi::Value::IsDate() const;
```
Returns `true` if the underlying value is a JavaScript `Date` or `false`
otherwise.
### IsEmpty
```cpp
bool Napi::Value::IsEmpty() const;
```
Returns `true` if the value is uninitialized.
An empty `Napi::Value` is invalid, and most attempts to perform an operation on
an empty `Napi::Value` will result in an exception. 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 `Napi::Value` to indicate a pending exception.
Thus, when C++ exceptions are not being used, callers should check the result of
`Env::IsExceptionPending` before attempting to use the value.
### IsExternal
```cpp
bool Napi::Value::IsExternal() const;
```
Returns `true` if the underlying value is a N-API external 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.
### IsNull
```cpp
bool Napi::Value::IsNull() const;
```
Returns `true` if the underlying value is a JavaScript `null` or `false`
otherwise.
### IsNumber
```cpp
bool Napi::Value::IsNumber() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Number` or `false`
otherwise.
### IsObject
```cpp
bool Napi::Value::IsObject() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Object` or `false`
otherwise.
### IsPromise
```cpp
bool Napi::Value::IsPromise() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Promise` 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.
### IsTypedArray
```cpp
bool Napi::Value::IsTypedArray() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::TypedArray` or
`false` otherwise.
### IsUndefined
```cpp
bool Napi::Value::IsUndefined() const;
```
Returns `true` if the underlying value is a JavaScript `undefined` or `false`
otherwise.
### 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`.
### 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 the `Napi::Value` coerced to a JavaScript number.
### ToObject
```cpp
Napi::Object Napi::Value::ToObject() const;
```
Returns the `Napi::Value` coerced to a JavaScript object.
### ToString
```cpp
Napi::String Napi::Value::ToString() const;
```
Returns the `Napi::Value` coerced to a JavaScript string.
### Type
```cpp
napi_valuetype Napi::Value::Type() const;
```
Returns the `napi_valuetype` type of the `Napi::Value`.
[`Napi::Boolean`]: ./boolean.md
[`Napi::BigInt`]: ./bigint.md
[`Napi::Date`]: ./date.md
[`Napi::External`]: ./external.md
[`Napi::Name`]: ./name.md
[`Napi::Number`]: ./number.md
[`Napi::Object`]: ./object.md

43
node_modules/node-addon-api/doc/version_management.md generated vendored Normal file
View File

@@ -0,0 +1,43 @@
# 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
Retrieves information about Node.js version present on the system. All the
information is stored in the `napi_node_version` structure 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.

16
node_modules/node-addon-api/except.gypi generated vendored Normal file
View File

@@ -0,0 +1,16 @@
{
'defines': [ 'NAPI_CPP_EXCEPTIONS' ],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'msvs_settings': {
'VCCLCompilerTool': {
'ExceptionHandling': 1,
'EnablePREfast': 'true',
},
},
'xcode_settings': {
'CLANG_CXX_LIBRARY': 'libc++',
'MACOSX_DEPLOYMENT_TARGET': '10.7',
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
},
}

11
node_modules/node-addon-api/index.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
const path = require('path');
const include_dir = path.relative('.', __dirname);
module.exports = {
include: `"${__dirname}"`, // deprecated, can be removed as part of 4.0.0
include_dir,
gyp: path.join(include_dir, 'node_api.gyp:nothing'),
isNodeApiBuiltin: true,
needsFlag: false
};

192
node_modules/node-addon-api/napi-inl.deprecated.h generated vendored Normal file
View File

@@ -0,0 +1,192 @@
#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_

5633
node_modules/node-addon-api/napi-inl.h generated vendored Normal file

File diff suppressed because it is too large Load Diff

2638
node_modules/node-addon-api/napi.h generated vendored Normal file

File diff suppressed because it is too large Load Diff

9
node_modules/node-addon-api/node_api.gyp generated vendored Normal file
View File

@@ -0,0 +1,9 @@
{
'targets': [
{
'target_name': 'nothing',
'type': 'static_library',
'sources': [ 'nothing.c' ]
}
]
}

16
node_modules/node-addon-api/noexcept.gypi generated vendored Normal file
View File

@@ -0,0 +1,16 @@
{
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
'cflags': [ '-fno-exceptions' ],
'cflags_cc': [ '-fno-exceptions' ],
'msvs_settings': {
'VCCLCompilerTool': {
'ExceptionHandling': 0,
'EnablePREfast': 'true',
},
},
'xcode_settings': {
'CLANG_CXX_LIBRARY': 'libc++',
'MACOSX_DEPLOYMENT_TARGET': '10.7',
'GCC_ENABLE_CPP_EXCEPTIONS': 'NO',
},
}

0
node_modules/node-addon-api/nothing.c generated vendored Normal file
View File

21
node_modules/node-addon-api/package-support.json generated vendored Normal file
View File

@@ -0,0 +1,21 @@
{
"versions": [
{
"version": "*",
"target": {
"node": "active"
},
"response": {
"type": "time-permitting",
"paid": false,
"contact": {
"name": "node-addon-api team",
"url": "https://github.com/nodejs/node-addon-api/issues"
}
},
"backing": [ { "project": "https://github.com/nodejs" },
{ "foundation": "https://openjsf.org/" }
]
}
]
}

372
node_modules/node-addon-api/package.json generated vendored Normal file
View File

@@ -0,0 +1,372 @@
{
"_from": "node-addon-api@^3.1.0",
"_id": "node-addon-api@3.1.0",
"_inBundle": false,
"_integrity": "sha512-flmrDNB06LIl5lywUz7YlNGZH/5p0M7W28k8hzd9Lshtdh1wshD2Y+U4h9LD6KObOy1f+fEVdgprPrEymjM5uw==",
"_location": "/node-addon-api",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "node-addon-api@^3.1.0",
"name": "node-addon-api",
"escapedName": "node-addon-api",
"rawSpec": "^3.1.0",
"saveSpec": null,
"fetchSpec": "^3.1.0"
},
"_requiredBy": [
"/@discordjs/opus"
],
"_resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.1.0.tgz",
"_shasum": "98b21931557466c6729e51cb77cd39c965f42239",
"_spec": "node-addon-api@^3.1.0",
"_where": "C:\\Users\\MCGFX\\OneDrive\\Dokumente\\GitHub\\UnknownBot\\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": "András Timár, Dr",
"url": "https://github.com/timarandras"
},
{
"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": "Azlan Mukhtar",
"url": "https://github.com/azlan"
},
{
"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": "blagoev",
"url": "https://github.com/blagoev"
},
{
"name": "Bruce A. MacNaughton",
"url": "https://github.com/bmacnaughton"
},
{
"name": "Cory Mickelson",
"url": "https://github.com/corymickelson"
},
{
"name": "Daniel Bevenius",
"url": "https://github.com/danbev"
},
{
"name": "Darshan Sen",
"url": "https://github.com/RaisinTen"
},
{
"name": "David Halls",
"url": "https://github.com/davedoesdev"
},
{
"name": "Dmitry Ashkadov",
"url": "https://github.com/dmitryash"
},
{
"name": "Dongjin Na",
"url": "https://github.com/nadongguri"
},
{
"name": "Ferdinand Holzer",
"url": "https://github.com/fholzer"
},
{
"name": "Eric Bickle",
"url": "https://github.com/ebickle"
},
{
"name": "Gabriel Schulhof",
"url": "https://github.com/gabrielschulhof"
},
{
"name": "Guenter Sandner",
"url": "https://github.com/gms1"
},
{
"name": "Gus Caplan",
"url": "https://github.com/devsnek"
},
{
"name": "Helio Frota",
"url": "https://github.com/helio-frota"
},
{
"name": "Hitesh Kanwathirtha",
"url": "https://github.com/digitalinfinity"
},
{
"name": "ikokostya",
"url": "https://github.com/ikokostya"
},
{
"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": "Jeroen Janssen",
"url": "https://github.com/japj"
},
{
"name": "Jim Schlight",
"url": "https://github.com/jschlight"
},
{
"name": "Jinho Bang",
"url": "https://github.com/romandev"
},
{
"name": "joshgarde",
"url": "https://github.com/joshgarde"
},
{
"name": "Kasumi Hanazuki",
"url": "https://github.com/hanazuki"
},
{
"name": "Kelvin",
"url": "https://github.com/kelvinhammond"
},
{
"name": "Kevin Eady",
"url": "https://github.com/KevinEady"
},
{
"name": "kidneysolo",
"url": "https://github.com/kidneysolo"
},
{
"name": "Koki Nishihara",
"url": "https://github.com/Nishikoh"
},
{
"name": "Konstantin Tarkus",
"url": "https://github.com/koistya"
},
{
"name": "Kyle Farnung",
"url": "https://github.com/kfarnung"
},
{
"name": "legendecas",
"url": "https://github.com/legendecas"
},
{
"name": "Lovell Fuller",
"url": "https://github.com/lovell"
},
{
"name": "Luciano Martorella",
"url": "https://github.com/lmartorella"
},
{
"name": "mastergberry",
"url": "https://github.com/mastergberry"
},
{
"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": "nempoBu4",
"url": "https://github.com/nempoBu4"
},
{
"name": "Nicola Del Gobbo",
"url": "https://github.com/NickNaso"
},
{
"name": "Nick Soggin",
"url": "https://github.com/iSkore"
},
{
"name": "Nikolai Vavilov",
"url": "https://github.com/seishun"
},
{
"name": "Nurbol Alpysbayev",
"url": "https://github.com/anurbol"
},
{
"name": "pacop",
"url": "https://github.com/pacop"
},
{
"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": "Vlad Velmisov",
"url": "https://github.com/Velmisov"
},
{
"name": "Yohei Kishimoto",
"url": "https://github.com/morokosi"
},
{
"name": "Yulong Wang",
"url": "https://github.com/fs-eire"
},
{
"name": "Ziqiu Zhao",
"url": "https://github.com/ZzqiZQute"
}
],
"dependencies": {},
"deprecated": false,
"description": "Node.js API (N-API)",
"devDependencies": {
"benchmark": "^2.1.4",
"bindings": "^1.5.0",
"clang-format": "^1.4.0",
"fs-extra": "^9.0.1",
"pre-commit": "^1.2.2",
"safe-buffer": "^5.1.1"
},
"directories": {},
"gypfile": false,
"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": {},
"pre-commit": "lint",
"repository": {
"type": "git",
"url": "git://github.com/nodejs/node-addon-api.git"
},
"scripts": {
"benchmark": "node benchmark",
"dev": "node test",
"dev:incremental": "node test",
"doc": "doxygen doc/Doxyfile",
"lint": "node tools/clang-format.js",
"lint:fix": "git-clang-format '*.h', '*.cc'",
"prebenchmark": "node-gyp rebuild -C benchmark",
"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"
},
"support": true,
"version": "3.1.0"
}

73
node_modules/node-addon-api/tools/README.md generated vendored Normal file
View File

@@ -0,0 +1,73 @@
# Tools
## clang-format
The clang-format checking tools is designed to check changed lines of code compared to given git-refs.
## 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.
```
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<&[ClassName]::Func1>("Func1"),
InstanceMethod<&[ClassName]::Func2>("Func2"),
InstanceAccessor<&[ClassName]::ValueGetter>("Value"),
StaticMethod<&[ClassName]::StaticMethod>("MethodName"),
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.

100
node_modules/node-addon-api/tools/check-napi.js generated vendored Normal file
View File

@@ -0,0 +1,100 @@
'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] : '.');

47
node_modules/node-addon-api/tools/clang-format.js generated vendored Normal file
View File

@@ -0,0 +1,47 @@
#!/usr/bin/env node
const spawn = require('child_process').spawnSync;
const path = require('path');
const filesToCheck = ['*.h', '*.cc'];
const CLANG_FORMAT_START = process.env.CLANG_FORMAT_START || 'master';
function main(args) {
let clangFormatPath = path.dirname(require.resolve('clang-format'));
const options = ['--binary=node_modules/.bin/clang-format', '--style=file'];
const gitClangFormatPath = path.join(clangFormatPath,
'bin/git-clang-format');
const result = spawn('python', [
gitClangFormatPath,
...options,
'--diff',
CLANG_FORMAT_START,
'HEAD',
...filesToCheck
], { encoding: 'utf-8' });
if (result.error) {
console.error('Error running git-clang-format:', result.error);
return 2;
}
const clangFormatOutput = result.stdout.trim();
if (clangFormatOutput !== '' &&
clangFormatOutput !== ('no modified files to format') &&
clangFormatOutput !== ('clang-format did not modify any files')) {
console.error(clangFormatOutput);
const fixCmd = '"npm run lint:fix"';
console.error(`
ERROR: please run ${fixCmd} to format changes in your commit
Note that when running the command locally, please keep your local
master branch and working branch up to date with nodejs/node-addon-api
to exclude un-related complains.
Or you can run "env CLANG_FORMAT_START=upstream/master ${fixCmd}".`);
return 1;
}
}
if (require.main === module) {
process.exitCode = main(process.argv.slice(2));
}

309
node_modules/node-addon-api/tools/conversion.js generated vendored Normal file
View File

@@ -0,0 +1,309 @@
#! /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_dir")\',' ],
[ /([ ]*)"include_dirs": \[/g, '$1"include_dirs": [\n$1 "<!(node -p \\"require(\'node-addon-api\').include_dir\\")",' ],
[ /[ ]*("|')<!\(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_dir")\',' ],
[ /([ ]*)"include_dirs": \[/g, '$1"include_dirs": [\n$1 "<!(node -p \'require(\\\"node-addon-api\\\").include_dir\')",' ],
[ /[ ]*("|')<!\(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;
});
});
}