init express project, add xml2json and ignore for sources

This commit is contained in:
Tykayn 2021-02-27 10:26:37 +01:00 committed by tykayn
commit 0bb9948660
309 changed files with 102459 additions and 0 deletions

0
.ginitgnore Normal file
View File

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
sources/
.idea

0
CONTRIBUTE Normal file
View File

0
LICENSE Normal file
View File

0
README.md Normal file
View File

41
app.js Normal file
View File

@ -0,0 +1,41 @@
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

90
bin/www Executable file
View File

@ -0,0 +1,90 @@
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('gtg2nodejs:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}

1
node_modules/.bin/xml2json generated vendored Symbolic link
View File

@ -0,0 +1 @@
../xml2json/bin/xml2json

22
node_modules/bindings/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net>
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.

98
node_modules/bindings/README.md generated vendored Normal file
View File

@ -0,0 +1,98 @@
node-bindings
=============
### Helper module for loading your native module's `.node` file
This is a helper module for authors of Node.js native addon modules.
It is basically the "swiss army knife" of `require()`ing your native module's
`.node` file.
Throughout the course of Node's native addon history, addons have ended up being
compiled in a variety of different places, depending on which build tool and which
version of node was used. To make matters worse, now the `gyp` build tool can
produce either a __Release__ or __Debug__ build, each being built into different
locations.
This module checks _all_ the possible locations that a native addon would be built
at, and returns the first one that loads successfully.
Installation
------------
Install with `npm`:
``` bash
$ npm install --save bindings
```
Or add it to the `"dependencies"` section of your `package.json` file.
Example
-------
`require()`ing the proper bindings file for the current node version, platform
and architecture is as simple as:
``` js
var bindings = require('bindings')('binding.node')
// Use your bindings defined in your C files
bindings.your_c_function()
```
Nice Error Output
-----------------
When the `.node` file could not be loaded, `node-bindings` throws an Error with
a nice error message telling you exactly what was tried. You can also check the
`err.tries` Array property.
```
Error: Could not load the bindings file. Tried:
→ /Users/nrajlich/ref/build/binding.node
→ /Users/nrajlich/ref/build/Debug/binding.node
→ /Users/nrajlich/ref/build/Release/binding.node
→ /Users/nrajlich/ref/out/Debug/binding.node
→ /Users/nrajlich/ref/Debug/binding.node
→ /Users/nrajlich/ref/out/Release/binding.node
→ /Users/nrajlich/ref/Release/binding.node
→ /Users/nrajlich/ref/build/default/binding.node
→ /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node
at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13)
at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
...
```
The searching for the `.node` file will originate from the first directory in which has a `package.json` file is found.
License
-------
(The MIT License)
Copyright (c) 2012 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
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.

221
node_modules/bindings/bindings.js generated vendored Normal file
View File

@ -0,0 +1,221 @@
/**
* Module dependencies.
*/
var fs = require('fs'),
path = require('path'),
fileURLToPath = require('file-uri-to-path'),
join = path.join,
dirname = path.dirname,
exists =
(fs.accessSync &&
function(path) {
try {
fs.accessSync(path);
} catch (e) {
return false;
}
return true;
}) ||
fs.existsSync ||
path.existsSync,
defaults = {
arrow: process.env.NODE_BINDINGS_ARROW || ' → ',
compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled',
platform: process.platform,
arch: process.arch,
nodePreGyp:
'node-v' +
process.versions.modules +
'-' +
process.platform +
'-' +
process.arch,
version: process.versions.node,
bindings: 'bindings.node',
try: [
// node-gyp's linked version in the "build" dir
['module_root', 'build', 'bindings'],
// node-waf and gyp_addon (a.k.a node-gyp)
['module_root', 'build', 'Debug', 'bindings'],
['module_root', 'build', 'Release', 'bindings'],
// Debug files, for development (legacy behavior, remove for node v0.9)
['module_root', 'out', 'Debug', 'bindings'],
['module_root', 'Debug', 'bindings'],
// Release files, but manually compiled (legacy behavior, remove for node v0.9)
['module_root', 'out', 'Release', 'bindings'],
['module_root', 'Release', 'bindings'],
// Legacy from node-waf, node <= 0.4.x
['module_root', 'build', 'default', 'bindings'],
// Production "Release" buildtype binary (meh...)
['module_root', 'compiled', 'version', 'platform', 'arch', 'bindings'],
// node-qbs builds
['module_root', 'addon-build', 'release', 'install-root', 'bindings'],
['module_root', 'addon-build', 'debug', 'install-root', 'bindings'],
['module_root', 'addon-build', 'default', 'install-root', 'bindings'],
// node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
['module_root', 'lib', 'binding', 'nodePreGyp', 'bindings']
]
};
/**
* The main `bindings()` function loads the compiled bindings for a given module.
* It uses V8's Error API to determine the parent filename that this function is
* being invoked from, which is then used to find the root directory.
*/
function bindings(opts) {
// Argument surgery
if (typeof opts == 'string') {
opts = { bindings: opts };
} else if (!opts) {
opts = {};
}
// maps `defaults` onto `opts` object
Object.keys(defaults).map(function(i) {
if (!(i in opts)) opts[i] = defaults[i];
});
// Get the module root
if (!opts.module_root) {
opts.module_root = exports.getRoot(exports.getFileName());
}
// Ensure the given bindings name ends with .node
if (path.extname(opts.bindings) != '.node') {
opts.bindings += '.node';
}
// https://github.com/webpack/webpack/issues/4175#issuecomment-342931035
var requireFunc =
typeof __webpack_require__ === 'function'
? __non_webpack_require__
: require;
var tries = [],
i = 0,
l = opts.try.length,
n,
b,
err;
for (; i < l; i++) {
n = join.apply(
null,
opts.try[i].map(function(p) {
return opts[p] || p;
})
);
tries.push(n);
try {
b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
if (!opts.path) {
b.path = n;
}
return b;
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND' &&
e.code !== 'QUALIFIED_PATH_RESOLUTION_FAILED' &&
!/not find/i.test(e.message)) {
throw e;
}
}
}
err = new Error(
'Could not locate the bindings file. Tried:\n' +
tries
.map(function(a) {
return opts.arrow + a;
})
.join('\n')
);
err.tries = tries;
throw err;
}
module.exports = exports = bindings;
/**
* Gets the filename of the JavaScript file that invokes this function.
* Used to help find the root directory of a module.
* Optionally accepts an filename argument to skip when searching for the invoking filename
*/
exports.getFileName = function getFileName(calling_file) {
var origPST = Error.prepareStackTrace,
origSTL = Error.stackTraceLimit,
dummy = {},
fileName;
Error.stackTraceLimit = 10;
Error.prepareStackTrace = function(e, st) {
for (var i = 0, l = st.length; i < l; i++) {
fileName = st[i].getFileName();
if (fileName !== __filename) {
if (calling_file) {
if (fileName !== calling_file) {
return;
}
} else {
return;
}
}
}
};
// run the 'prepareStackTrace' function above
Error.captureStackTrace(dummy);
dummy.stack;
// cleanup
Error.prepareStackTrace = origPST;
Error.stackTraceLimit = origSTL;
// handle filename that starts with "file://"
var fileSchema = 'file://';
if (fileName.indexOf(fileSchema) === 0) {
fileName = fileURLToPath(fileName);
}
return fileName;
};
/**
* Gets the root directory of a module, given an arbitrary filename
* somewhere in the module tree. The "root directory" is the directory
* containing the `package.json` file.
*
* In: /home/nate/node-native-module/lib/index.js
* Out: /home/nate/node-native-module
*/
exports.getRoot = function getRoot(file) {
var dir = dirname(file),
prev;
while (true) {
if (dir === '.') {
// Avoids an infinite loop in rare cases, like the REPL
dir = process.cwd();
}
if (
exists(join(dir, 'package.json')) ||
exists(join(dir, 'node_modules'))
) {
// Found the 'package.json' file or 'node_modules' dir; we're done
return dir;
}
if (prev === dir) {
// Got to the top
throw new Error(
'Could not find module root given file: "' +
file +
'". Do you have a `package.json` file? '
);
}
// Try the parent dir next
prev = dir;
dir = join(dir, '..');
}
};

57
node_modules/bindings/package.json generated vendored Normal file
View File

@ -0,0 +1,57 @@
{
"_from": "bindings@^1.5.0",
"_id": "bindings@1.5.0",
"_inBundle": false,
"_integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
"_location": "/bindings",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "bindings@^1.5.0",
"name": "bindings",
"escapedName": "bindings",
"rawSpec": "^1.5.0",
"saveSpec": null,
"fetchSpec": "^1.5.0"
},
"_requiredBy": [
"/node-expat"
],
"_resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
"_shasum": "10353c9e945334bc0511a6d90b38fbc7c9c504df",
"_spec": "bindings@^1.5.0",
"_where": "/var/www/html/gtg2nodejs/node_modules/node-expat",
"author": {
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://tootallnate.net"
},
"bugs": {
"url": "https://github.com/TooTallNate/node-bindings/issues"
},
"bundleDependencies": false,
"dependencies": {
"file-uri-to-path": "1.0.0"
},
"deprecated": false,
"description": "Helper module for loading your native module's .node file",
"homepage": "https://github.com/TooTallNate/node-bindings",
"keywords": [
"native",
"addon",
"bindings",
"gyp",
"waf",
"c",
"c++"
],
"license": "MIT",
"main": "./bindings.js",
"name": "bindings",
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-bindings.git"
},
"version": "1.5.0"
}

1
node_modules/file-uri-to-path/.npmignore generated vendored Normal file
View File

@ -0,0 +1 @@
/node_modules

30
node_modules/file-uri-to-path/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,30 @@
sudo: false
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
- "1"
- "2"
- "3"
- "4"
- "5"
- "6"
- "7"
- "8"
install:
- PATH="`npm bin`:`npm bin -g`:$PATH"
# Node 0.8 comes with a too obsolete npm
- if [[ "`node --version`" =~ ^v0\.8\. ]]; then npm install -g npm@1.4.28 ; fi
# Install dependencies and build
- npm install
script:
# Output useful info for debugging
- node --version
- npm --version
# Run tests
- npm test

21
node_modules/file-uri-to-path/History.md generated vendored Normal file
View File

@ -0,0 +1,21 @@
1.0.0 / 2017-07-06
==================
* update "mocha" to v3
* fixed unicode URI decoding (#6)
* add typings for Typescript
* README: use SVG Travis-CI badge
* add LICENSE file (MIT)
* add .travis.yml file (testing Node.js 0.8 through 8 currently)
* add README.md file
0.0.2 / 2014-01-27
==================
* index: invert the path separators on Windows
0.0.1 / 2014-01-27
==================
* initial commit

20
node_modules/file-uri-to-path/LICENSE generated vendored Normal file
View File

@ -0,0 +1,20 @@
Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net>
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.

74
node_modules/file-uri-to-path/README.md generated vendored Normal file
View File

@ -0,0 +1,74 @@
file-uri-to-path
================
### Convert a `file:` URI to a file path
[![Build Status](https://travis-ci.org/TooTallNate/file-uri-to-path.svg?branch=master)](https://travis-ci.org/TooTallNate/file-uri-to-path)
Accepts a `file:` URI and returns a regular file path suitable for use with the
`fs` module functions.
Installation
------------
Install with `npm`:
``` bash
$ npm install file-uri-to-path
```
Example
-------
``` js
var uri2path = require('file-uri-to-path');
uri2path('file://localhost/c|/WINDOWS/clock.avi');
// "c:\\WINDOWS\\clock.avi"
uri2path('file:///c|/WINDOWS/clock.avi');
// "c:\\WINDOWS\\clock.avi"
uri2path('file://localhost/c:/WINDOWS/clock.avi');
// "c:\\WINDOWS\\clock.avi"
uri2path('file://hostname/path/to/the%20file.txt');
// "\\\\hostname\\path\\to\\the file.txt"
uri2path('file:///c:/path/to/the%20file.txt');
// "c:\\path\\to\\the file.txt"
```
API
---
### fileUriToPath(String uri) → String
License
-------
(The MIT License)
Copyright (c) 2014 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
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.

2
node_modules/file-uri-to-path/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,2 @@
declare function fileUriToPath(uri: string): string;
export = fileUriToPath;

66
node_modules/file-uri-to-path/index.js generated vendored Normal file
View File

@ -0,0 +1,66 @@
/**
* Module dependencies.
*/
var sep = require('path').sep || '/';
/**
* Module exports.
*/
module.exports = fileUriToPath;
/**
* File URI to Path function.
*
* @param {String} uri
* @return {String} path
* @api public
*/
function fileUriToPath (uri) {
if ('string' != typeof uri ||
uri.length <= 7 ||
'file://' != uri.substring(0, 7)) {
throw new TypeError('must pass in a file:// URI to convert to a file path');
}
var rest = decodeURI(uri.substring(7));
var firstSlash = rest.indexOf('/');
var host = rest.substring(0, firstSlash);
var path = rest.substring(firstSlash + 1);
// 2. Scheme Definition
// As a special case, <host> can be the string "localhost" or the empty
// string; this is interpreted as "the machine from which the URL is
// being interpreted".
if ('localhost' == host) host = '';
if (host) {
host = sep + sep + host;
}
// 3.2 Drives, drive letters, mount points, file system root
// Drive letters are mapped into the top of a file URI in various ways,
// depending on the implementation; some applications substitute
// vertical bar ("|") for the colon after the drive letter, yielding
// "file:///c|/tmp/test.txt". In some cases, the colon is left
// unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
// colon is simply omitted, as in "file:///c/tmp/test.txt".
path = path.replace(/^(.+)\|/, '$1:');
// for Windows, we need to invert the path separators from what a URI uses
if (sep == '\\') {
path = path.replace(/\//g, '\\');
}
if (/^.+\:/.test(path)) {
// has Windows drive at beginning of path
} else {
// unix path…
path = sep + path;
}
return host + path;
}

61
node_modules/file-uri-to-path/package.json generated vendored Normal file
View File

@ -0,0 +1,61 @@
{
"_from": "file-uri-to-path@1.0.0",
"_id": "file-uri-to-path@1.0.0",
"_inBundle": false,
"_integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
"_location": "/file-uri-to-path",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "file-uri-to-path@1.0.0",
"name": "file-uri-to-path",
"escapedName": "file-uri-to-path",
"rawSpec": "1.0.0",
"saveSpec": null,
"fetchSpec": "1.0.0"
},
"_requiredBy": [
"/bindings"
],
"_resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
"_shasum": "553a7b8446ff6f684359c445f1e37a05dacc33dd",
"_spec": "file-uri-to-path@1.0.0",
"_where": "/var/www/html/gtg2nodejs/node_modules/bindings",
"author": {
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://n8.io/"
},
"bugs": {
"url": "https://github.com/TooTallNate/file-uri-to-path/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Convert a file: URI to a file path",
"devDependencies": {
"mocha": "3"
},
"directories": {
"test": "test"
},
"homepage": "https://github.com/TooTallNate/file-uri-to-path",
"keywords": [
"file",
"uri",
"convert",
"path"
],
"license": "MIT",
"main": "index.js",
"name": "file-uri-to-path",
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/file-uri-to-path.git"
},
"scripts": {
"test": "mocha --reporter spec"
},
"types": "index.d.ts",
"version": "1.0.0"
}

24
node_modules/file-uri-to-path/test/test.js generated vendored Normal file
View File

@ -0,0 +1,24 @@
var sep = require('path').sep || '/';
var assert = require('assert');
var uri2path = require('../');
var tests = require('./tests.json');
describe('file-uri-to-path', function () {
Object.keys(tests).forEach(function (uri) {
// the test cases were generated from Windows' PathCreateFromUrlA() function.
// On Unix, we have to replace the path separator with the Unix one instead of
// the Windows one.
var expected = tests[uri].replace(/\\/g, sep);
it('should convert ' + JSON.stringify(uri) + ' to ' + JSON.stringify(expected),
function () {
var actual = uri2path(uri);
assert.equal(actual, expected);
});
});
});

13
node_modules/file-uri-to-path/test/tests.json generated vendored Normal file
View File

@ -0,0 +1,13 @@
{
"file://host/path": "\\\\host\\path",
"file://localhost/etc/fstab": "\\etc\\fstab",
"file:///etc/fstab": "\\etc\\fstab",
"file:///c:/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi",
"file://localhost/c|/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi",
"file:///c|/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi",
"file://localhost/c:/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi",
"file://hostname/path/to/the%20file.txt": "\\\\hostname\\path\\to\\the file.txt",
"file:///c:/path/to/the%20file.txt": "c:\\path\\to\\the file.txt",
"file:///C:/Documents%20and%20Settings/davris/FileSchemeURIs.doc": "C:\\Documents and Settings\\davris\\FileSchemeURIs.doc",
"file:///C:/caf%C3%A9/%C3%A5r/d%C3%BCnn/%E7%89%9B%E9%93%83/Ph%E1%BB%9F/%F0%9F%98%B5.exe": "C:\\café\\år\\dünn\\牛铃\\Phở\\😵.exe"
}

3
node_modules/hoek/.npmignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
*
!lib/**
!.npmignore

32
node_modules/hoek/LICENSE generated vendored Normal file
View File

@ -0,0 +1,32 @@
Copyright (c) 2011-2016, Project contributors
Copyright (c) 2011-2014, Walmart
Copyright (c) 2011, Yahoo Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of any contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* * *
The complete list of contributors can be found at: https://github.com/hapijs/hapi/graphs/contributors
Portions of this project were initially based on the Yahoo! Inc. Postmile project,
published at https://github.com/yahoo/postmile.

30
node_modules/hoek/README.md generated vendored Normal file
View File

@ -0,0 +1,30 @@
![hoek Logo](https://raw.github.com/hapijs/hoek/master/images/hoek.png)
Utility methods for the hapi ecosystem. This module is not intended to solve every problem for everyone, but rather as a central place to store hapi-specific methods. If you're looking for a general purpose utility module, check out [lodash](https://github.com/lodash/lodash) or [underscore](https://github.com/jashkenas/underscore).
[![Build Status](https://secure.travis-ci.org/hapijs/hoek.svg)](http://travis-ci.org/hapijs/hoek)
<a href="https://andyet.com"><img src="https://s3.amazonaws.com/static.andyet.com/images/%26yet-logo.svg" align="right" /></a>
Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf)
**hoek** is sponsored by [&yet](https://andyet.com)
## Usage
The *Hoek* library contains some common functions used within the hapi ecosystem. It comes with useful methods for Arrays (clone, merge, applyToDefaults), Objects (removeKeys, copy), Asserting and more.
For example, to use Hoek to set configuration with default options:
```javascript
const Hoek = require('hoek');
const default = {url : "www.github.com", port : "8000", debug : true};
const config = Hoek.applyToDefaults(default, {port : "3000", admin : true});
// In this case, config would be { url: 'www.github.com', port: '3000', debug: true, admin: true }
```
## Documentation
[**API Reference**](API.md)

168
node_modules/hoek/lib/escape.js generated vendored Executable file
View File

@ -0,0 +1,168 @@
'use strict';
// Declare internals
const internals = {};
exports.escapeJavaScript = function (input) {
if (!input) {
return '';
}
let escaped = '';
for (let i = 0; i < input.length; ++i) {
const charCode = input.charCodeAt(i);
if (internals.isSafe(charCode)) {
escaped += input[i];
}
else {
escaped += internals.escapeJavaScriptChar(charCode);
}
}
return escaped;
};
exports.escapeHtml = function (input) {
if (!input) {
return '';
}
let escaped = '';
for (let i = 0; i < input.length; ++i) {
const charCode = input.charCodeAt(i);
if (internals.isSafe(charCode)) {
escaped += input[i];
}
else {
escaped += internals.escapeHtmlChar(charCode);
}
}
return escaped;
};
exports.escapeJson = function (input) {
if (!input) {
return '';
}
const lessThan = 0x3C;
const greaterThan = 0x3E;
const andSymbol = 0x26;
const lineSeperator = 0x2028;
// replace method
let charCode;
return input.replace(/[<>&\u2028\u2029]/g, (match) => {
charCode = match.charCodeAt(0);
if (charCode === lessThan) {
return '\\u003c';
}
else if (charCode === greaterThan) {
return '\\u003e';
}
else if (charCode === andSymbol) {
return '\\u0026';
}
else if (charCode === lineSeperator) {
return '\\u2028';
}
return '\\u2029';
});
};
internals.escapeJavaScriptChar = function (charCode) {
if (charCode >= 256) {
return '\\u' + internals.padLeft('' + charCode, 4);
}
const hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
return '\\x' + internals.padLeft(hexValue, 2);
};
internals.escapeHtmlChar = function (charCode) {
const namedEscape = internals.namedHtml[charCode];
if (typeof namedEscape !== 'undefined') {
return namedEscape;
}
if (charCode >= 256) {
return '&#' + charCode + ';';
}
const hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
return '&#x' + internals.padLeft(hexValue, 2) + ';';
};
internals.padLeft = function (str, len) {
while (str.length < len) {
str = '0' + str;
}
return str;
};
internals.isSafe = function (charCode) {
return (typeof internals.safeCharCodes[charCode] !== 'undefined');
};
internals.namedHtml = {
'38': '&amp;',
'60': '&lt;',
'62': '&gt;',
'34': '&quot;',
'160': '&nbsp;',
'162': '&cent;',
'163': '&pound;',
'164': '&curren;',
'169': '&copy;',
'174': '&reg;'
};
internals.safeCharCodes = (function () {
const safe = {};
for (let i = 32; i < 123; ++i) {
if ((i >= 97) || // a-z
(i >= 65 && i <= 90) || // A-Z
(i >= 48 && i <= 57) || // 0-9
i === 32 || // space
i === 46 || // .
i === 44 || // ,
i === 45 || // -
i === 58 || // :
i === 95) { // _
safe[i] = null;
}
}
return safe;
}());

978
node_modules/hoek/lib/index.js generated vendored Executable file
View File

@ -0,0 +1,978 @@
'use strict';
// Load modules
const Crypto = require('crypto');
const Path = require('path');
const Util = require('util');
const Escape = require('./escape');
// Declare internals
const internals = {};
// Clone object or array
exports.clone = function (obj, seen) {
if (typeof obj !== 'object' ||
obj === null) {
return obj;
}
seen = seen || new Map();
const lookup = seen.get(obj);
if (lookup) {
return lookup;
}
let newObj;
let cloneDeep = false;
if (!Array.isArray(obj)) {
if (Buffer.isBuffer(obj)) {
newObj = new Buffer(obj);
}
else if (obj instanceof Date) {
newObj = new Date(obj.getTime());
}
else if (obj instanceof RegExp) {
newObj = new RegExp(obj);
}
else {
const proto = Object.getPrototypeOf(obj);
if (proto &&
proto.isImmutable) {
newObj = obj;
}
else {
newObj = Object.create(proto);
cloneDeep = true;
}
}
}
else {
newObj = [];
cloneDeep = true;
}
seen.set(obj, newObj);
if (cloneDeep) {
const keys = Object.getOwnPropertyNames(obj);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor &&
(descriptor.get ||
descriptor.set)) {
Object.defineProperty(newObj, key, descriptor);
}
else {
newObj[key] = exports.clone(obj[key], seen);
}
}
}
return newObj;
};
// Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied
/*eslint-disable */
exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) {
/*eslint-enable */
exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object');
exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
if (!source) {
return target;
}
if (Array.isArray(source)) {
exports.assert(Array.isArray(target), 'Cannot merge array onto an object');
if (isMergeArrays === false) { // isMergeArrays defaults to true
target.length = 0; // Must not change target assignment
}
for (let i = 0; i < source.length; ++i) {
target.push(exports.clone(source[i]));
}
return target;
}
const keys = Object.keys(source);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (key === '__proto__') {
continue;
}
const value = source[key];
if (value &&
typeof value === 'object') {
if (!target[key] ||
typeof target[key] !== 'object' ||
(Array.isArray(target[key]) !== Array.isArray(value)) ||
value instanceof Date ||
Buffer.isBuffer(value) ||
value instanceof RegExp) {
target[key] = exports.clone(value);
}
else {
exports.merge(target[key], value, isNullOverride, isMergeArrays);
}
}
else {
if (value !== null &&
value !== undefined) { // Explicit to preserve empty strings
target[key] = value;
}
else if (isNullOverride !== false) { // Defaults to true
target[key] = value;
}
}
}
return target;
};
// Apply options to a copy of the defaults
exports.applyToDefaults = function (defaults, options, isNullOverride) {
exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
if (!options) { // If no options, return null
return null;
}
const copy = exports.clone(defaults);
if (options === true) { // If options is set to true, use defaults
return copy;
}
return exports.merge(copy, options, isNullOverride === true, false);
};
// Clone an object except for the listed keys which are shallow copied
exports.cloneWithShallow = function (source, keys) {
if (!source ||
typeof source !== 'object') {
return source;
}
const storage = internals.store(source, keys); // Move shallow copy items to storage
const copy = exports.clone(source); // Deep copy the rest
internals.restore(copy, source, storage); // Shallow copy the stored items and restore
return copy;
};
internals.store = function (source, keys) {
const storage = {};
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const value = exports.reach(source, key);
if (value !== undefined) {
storage[key] = value;
internals.reachSet(source, key, undefined);
}
}
return storage;
};
internals.restore = function (copy, source, storage) {
const keys = Object.keys(storage);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
internals.reachSet(copy, key, storage[key]);
internals.reachSet(source, key, storage[key]);
}
};
internals.reachSet = function (obj, key, value) {
const path = key.split('.');
let ref = obj;
for (let i = 0; i < path.length; ++i) {
const segment = path[i];
if (i + 1 === path.length) {
ref[segment] = value;
}
ref = ref[segment];
}
};
// Apply options to defaults except for the listed keys which are shallow copied from option without merging
exports.applyToDefaultsWithShallow = function (defaults, options, keys) {
exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
exports.assert(keys && Array.isArray(keys), 'Invalid keys');
if (!options) { // If no options, return null
return null;
}
const copy = exports.cloneWithShallow(defaults, keys);
if (options === true) { // If options is set to true, use defaults
return copy;
}
const storage = internals.store(options, keys); // Move shallow copy items to storage
exports.merge(copy, options, false, false); // Deep copy the rest
internals.restore(copy, options, storage); // Shallow copy the stored items and restore
return copy;
};
// Deep object or array comparison
exports.deepEqual = function (obj, ref, options, seen) {
options = options || { prototype: true };
const type = typeof obj;
if (type !== typeof ref) {
return false;
}
if (type !== 'object' ||
obj === null ||
ref === null) {
if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql
return obj !== 0 || 1 / obj === 1 / ref; // -0 / +0
}
return obj !== obj && ref !== ref; // NaN
}
seen = seen || [];
if (seen.indexOf(obj) !== -1) {
return true; // If previous comparison failed, it would have stopped execution
}
seen.push(obj);
if (Array.isArray(obj)) {
if (!Array.isArray(ref)) {
return false;
}
if (!options.part && obj.length !== ref.length) {
return false;
}
for (let i = 0; i < obj.length; ++i) {
if (options.part) {
let found = false;
for (let j = 0; j < ref.length; ++j) {
if (exports.deepEqual(obj[i], ref[j], options)) {
found = true;
break;
}
}
return found;
}
if (!exports.deepEqual(obj[i], ref[i], options)) {
return false;
}
}
return true;
}
if (Buffer.isBuffer(obj)) {
if (!Buffer.isBuffer(ref)) {
return false;
}
if (obj.length !== ref.length) {
return false;
}
for (let i = 0; i < obj.length; ++i) {
if (obj[i] !== ref[i]) {
return false;
}
}
return true;
}
if (obj instanceof Date) {
return (ref instanceof Date && obj.getTime() === ref.getTime());
}
if (obj instanceof RegExp) {
return (ref instanceof RegExp && obj.toString() === ref.toString());
}
if (options.prototype) {
if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) {
return false;
}
}
const keys = Object.getOwnPropertyNames(obj);
if (!options.part && keys.length !== Object.getOwnPropertyNames(ref).length) {
return false;
}
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor.get) {
if (!exports.deepEqual(descriptor, Object.getOwnPropertyDescriptor(ref, key), options, seen)) {
return false;
}
}
else if (!exports.deepEqual(obj[key], ref[key], options, seen)) {
return false;
}
}
return true;
};
// Remove duplicate items from array
exports.unique = (array, key) => {
let result;
if (key) {
result = [];
const index = new Set();
array.forEach((item) => {
const identifier = item[key];
if (!index.has(identifier)) {
index.add(identifier);
result.push(item);
}
});
}
else {
result = Array.from(new Set(array));
}
return result;
};
// Convert array into object
exports.mapToObject = function (array, key) {
if (!array) {
return null;
}
const obj = {};
for (let i = 0; i < array.length; ++i) {
if (key) {
if (array[i][key]) {
obj[array[i][key]] = true;
}
}
else {
obj[array[i]] = true;
}
}
return obj;
};
// Find the common unique items in two arrays
exports.intersect = function (array1, array2, justFirst) {
if (!array1 || !array2) {
return [];
}
const common = [];
const hash = (Array.isArray(array1) ? exports.mapToObject(array1) : array1);
const found = {};
for (let i = 0; i < array2.length; ++i) {
if (hash[array2[i]] && !found[array2[i]]) {
if (justFirst) {
return array2[i];
}
common.push(array2[i]);
found[array2[i]] = true;
}
}
return (justFirst ? null : common);
};
// Test if the reference contains the values
exports.contain = function (ref, values, options) {
/*
string -> string(s)
array -> item(s)
object -> key(s)
object -> object (key:value)
*/
let valuePairs = null;
if (typeof ref === 'object' &&
typeof values === 'object' &&
!Array.isArray(ref) &&
!Array.isArray(values)) {
valuePairs = values;
values = Object.keys(values);
}
else {
values = [].concat(values);
}
options = options || {}; // deep, once, only, part
exports.assert(arguments.length >= 2, 'Insufficient arguments');
exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object');
exports.assert(values.length, 'Values array cannot be empty');
let compare;
let compareFlags;
if (options.deep) {
compare = exports.deepEqual;
const hasOnly = options.hasOwnProperty('only');
const hasPart = options.hasOwnProperty('part');
compareFlags = {
prototype: hasOnly ? options.only : hasPart ? !options.part : false,
part: hasOnly ? !options.only : hasPart ? options.part : true
};
}
else {
compare = (a, b) => a === b;
}
let misses = false;
const matches = new Array(values.length);
for (let i = 0; i < matches.length; ++i) {
matches[i] = 0;
}
if (typeof ref === 'string') {
let pattern = '(';
for (let i = 0; i < values.length; ++i) {
const value = values[i];
exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value');
pattern += (i ? '|' : '') + exports.escapeRegex(value);
}
const regex = new RegExp(pattern + ')', 'g');
const leftovers = ref.replace(regex, ($0, $1) => {
const index = values.indexOf($1);
++matches[index];
return ''; // Remove from string
});
misses = !!leftovers;
}
else if (Array.isArray(ref)) {
for (let i = 0; i < ref.length; ++i) {
let matched = false;
for (let j = 0; j < values.length && matched === false; ++j) {
matched = compare(values[j], ref[i], compareFlags) && j;
}
if (matched !== false) {
++matches[matched];
}
else {
misses = true;
}
}
}
else {
const keys = Object.getOwnPropertyNames(ref);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const pos = values.indexOf(key);
if (pos !== -1) {
if (valuePairs &&
!compare(valuePairs[key], ref[key], compareFlags)) {
return false;
}
++matches[pos];
}
else {
misses = true;
}
}
}
let result = false;
for (let i = 0; i < matches.length; ++i) {
result = result || !!matches[i];
if ((options.once && matches[i] > 1) ||
(!options.part && !matches[i])) {
return false;
}
}
if (options.only &&
misses) {
return false;
}
return result;
};
// Flatten array
exports.flatten = function (array, target) {
const result = target || [];
for (let i = 0; i < array.length; ++i) {
if (Array.isArray(array[i])) {
exports.flatten(array[i], result);
}
else {
result.push(array[i]);
}
}
return result;
};
// Convert an object key chain string ('a.b.c') to reference (object[a][b][c])
exports.reach = function (obj, chain, options) {
if (chain === false ||
chain === null ||
typeof chain === 'undefined') {
return obj;
}
options = options || {};
if (typeof options === 'string') {
options = { separator: options };
}
const path = chain.split(options.separator || '.');
let ref = obj;
for (let i = 0; i < path.length; ++i) {
let key = path[i];
if (key[0] === '-' && Array.isArray(ref)) {
key = key.slice(1, key.length);
key = ref.length - key;
}
if (!ref ||
!((typeof ref === 'object' || typeof ref === 'function') && key in ref) ||
(typeof ref !== 'object' && options.functions === false)) { // Only object and function can have properties
exports.assert(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain);
exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
ref = options.default;
break;
}
ref = ref[key];
}
return ref;
};
exports.reachTemplate = function (obj, template, options) {
return template.replace(/{([^}]+)}/g, ($0, chain) => {
const value = exports.reach(obj, chain, options);
return (value === undefined || value === null ? '' : value);
});
};
exports.formatStack = function (stack) {
const trace = [];
for (let i = 0; i < stack.length; ++i) {
const item = stack[i];
trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]);
}
return trace;
};
exports.formatTrace = function (trace) {
const display = [];
for (let i = 0; i < trace.length; ++i) {
const row = trace[i];
display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')');
}
return display;
};
exports.callStack = function (slice) {
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
const v8 = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) {
return stack;
};
const capture = {};
Error.captureStackTrace(capture, this); // arguments.callee is not supported in strict mode so we use this and slice the trace of this off the result
const stack = capture.stack;
Error.prepareStackTrace = v8;
const trace = exports.formatStack(stack);
return trace.slice(1 + slice);
};
exports.displayStack = function (slice) {
const trace = exports.callStack(slice === undefined ? 1 : slice + 1);
return exports.formatTrace(trace);
};
exports.abortThrow = false;
exports.abort = function (message, hideStack) {
if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) {
throw new Error(message || 'Unknown error');
}
let stack = '';
if (!hideStack) {
stack = exports.displayStack(1).join('\n\t');
}
console.log('ABORT: ' + message + '\n\t' + stack);
process.exit(1);
};
exports.assert = function (condition /*, msg1, msg2, msg3 */) {
if (condition) {
return;
}
if (arguments.length === 2 && arguments[1] instanceof Error) {
throw arguments[1];
}
let msgs = [];
for (let i = 1; i < arguments.length; ++i) {
if (arguments[i] !== '') {
msgs.push(arguments[i]); // Avoids Array.slice arguments leak, allowing for V8 optimizations
}
}
msgs = msgs.map((msg) => {
return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : exports.stringify(msg);
});
throw new Error(msgs.join(' ') || 'Unknown error');
};
exports.Timer = function () {
this.ts = 0;
this.reset();
};
exports.Timer.prototype.reset = function () {
this.ts = Date.now();
};
exports.Timer.prototype.elapsed = function () {
return Date.now() - this.ts;
};
exports.Bench = function () {
this.ts = 0;
this.reset();
};
exports.Bench.prototype.reset = function () {
this.ts = exports.Bench.now();
};
exports.Bench.prototype.elapsed = function () {
return exports.Bench.now() - this.ts;
};
exports.Bench.now = function () {
const ts = process.hrtime();
return (ts[0] * 1e3) + (ts[1] / 1e6);
};
// Escape string for Regex construction
exports.escapeRegex = function (string) {
// Escape ^$.*+-?=!:|\/()[]{},
return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
};
// Base64url (RFC 4648) encode
exports.base64urlEncode = function (value, encoding) {
exports.assert(typeof value === 'string' || Buffer.isBuffer(value), 'value must be string or buffer');
const buf = (Buffer.isBuffer(value) ? value : new Buffer(value, encoding || 'binary'));
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
};
// Base64url (RFC 4648) decode
exports.base64urlDecode = function (value, encoding) {
if (typeof value !== 'string') {
return new Error('Value not a string');
}
if (!/^[\w\-]*$/.test(value)) {
return new Error('Invalid character');
}
const buf = new Buffer(value, 'base64');
return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary'));
};
// Escape attribute value for use in HTTP header
exports.escapeHeaderAttribute = function (attribute) {
// Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "
exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')');
return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash
};
exports.escapeHtml = function (string) {
return Escape.escapeHtml(string);
};
exports.escapeJavaScript = function (string) {
return Escape.escapeJavaScript(string);
};
exports.escapeJson = function (string) {
return Escape.escapeJson(string);
};
exports.nextTick = function (callback) {
return function () {
const args = arguments;
process.nextTick(() => {
callback.apply(null, args);
});
};
};
exports.once = function (method) {
if (method._hoekOnce) {
return method;
}
let once = false;
const wrapped = function () {
if (!once) {
once = true;
method.apply(null, arguments);
}
};
wrapped._hoekOnce = true;
return wrapped;
};
exports.isInteger = Number.isSafeInteger;
exports.ignore = function () { };
exports.inherits = Util.inherits;
exports.format = Util.format;
exports.transform = function (source, transform, options) {
exports.assert(source === null || source === undefined || typeof source === 'object' || Array.isArray(source), 'Invalid source object: must be null, undefined, an object, or an array');
const separator = (typeof options === 'object' && options !== null) ? (options.separator || '.') : '.';
if (Array.isArray(source)) {
const results = [];
for (let i = 0; i < source.length; ++i) {
results.push(exports.transform(source[i], transform, options));
}
return results;
}
const result = {};
const keys = Object.keys(transform);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const path = key.split(separator);
const sourcePath = transform[key];
exports.assert(typeof sourcePath === 'string', 'All mappings must be "." delineated strings');
let segment;
let res = result;
while (path.length > 1) {
segment = path.shift();
if (!res[segment]) {
res[segment] = {};
}
res = res[segment];
}
segment = path.shift();
res[segment] = exports.reach(source, sourcePath, options);
}
return result;
};
exports.uniqueFilename = function (path, extension) {
if (extension) {
extension = extension[0] !== '.' ? '.' + extension : extension;
}
else {
extension = '';
}
path = Path.resolve(path);
const name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension;
return Path.join(path, name);
};
exports.stringify = function () {
try {
return JSON.stringify.apply(null, arguments);
}
catch (err) {
return '[Cannot display object: ' + err.message + ']';
}
};
exports.shallow = function (source) {
const target = {};
const keys = Object.keys(source);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
target[key] = source[key];
}
return target;
};

55
node_modules/hoek/package.json generated vendored Normal file
View File

@ -0,0 +1,55 @@
{
"_from": "hoek@^4.2.1",
"_id": "hoek@4.2.1",
"_inBundle": false,
"_integrity": "sha512-QLg82fGkfnJ/4iy1xZ81/9SIJiq1NGFUMGs6ParyjBZr6jW2Ufj/snDqTHixNlHdPNwN2RLVD0Pi3igeK9+JfA==",
"_location": "/hoek",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "hoek@^4.2.1",
"name": "hoek",
"escapedName": "hoek",
"rawSpec": "^4.2.1",
"saveSpec": null,
"fetchSpec": "^4.2.1"
},
"_requiredBy": [
"/xml2json"
],
"_resolved": "https://registry.npmjs.org/hoek/-/hoek-4.2.1.tgz",
"_shasum": "9634502aa12c445dd5a7c5734b572bb8738aacbb",
"_spec": "hoek@^4.2.1",
"_where": "/var/www/html/gtg2nodejs/node_modules/xml2json",
"bugs": {
"url": "https://github.com/hapijs/hoek/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": "This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).",
"description": "General purpose node utilities",
"devDependencies": {
"code": "4.x.x",
"lab": "13.x.x"
},
"engines": {
"node": ">=4.0.0"
},
"homepage": "https://github.com/hapijs/hoek#readme",
"keywords": [
"utilities"
],
"license": "BSD-3-Clause",
"main": "lib/index.js",
"name": "hoek",
"repository": {
"type": "git",
"url": "git://github.com/hapijs/hoek.git"
},
"scripts": {
"test": "lab -a code -t 100 -L",
"test-cov-html": "lab -a code -t 100 -L -r html -o coverage.html"
},
"version": "4.2.1"
}

32
node_modules/isemail/LICENSE generated vendored Normal file
View File

@ -0,0 +1,32 @@
Copyright (c) 2014-2015, Eli Skeggs and Project contributors
Copyright (c) 2013-2014, GlobeSherpa
Copyright (c) 2008-2011, Dominic Sayers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of any contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* * *
The complete list of contributors can be found at: https://github.com/hapijs/isemail/graphs/contributors
Previously published under the 2-Clause-BSD license published here: https://github.com/hapijs/isemail/blob/v1.2.0/LICENSE

84
node_modules/isemail/README.md generated vendored Executable file
View File

@ -0,0 +1,84 @@
# isemail
Node email address validation library
[![Build Status](https://travis-ci.org/hapijs/isemail.svg?branch=master)](https://travis-ci.org/hapijs/isemail)<a href="#footnote-1"><sup>&#91;1&#93;</sup></a>
Lead Maintainer: [Eli Skeggs][skeggse]
This library is a port of the PHP `is_email` function by Dominic Sayers.
Install
=======
```sh
$ npm install isemail
```
Test
====
The tests were pulled from `is_email`'s extensive [test suite][tests] on October 15, 2013. Many thanks to the contributors! Additional tests have been added to increase code coverage and verify edge-cases.
Run any of the following.
```sh
$ lab
$ npm test
$ make test
```
_remember to_ `npm install` to get the development dependencies!
API
===
validate(email, [options])
--------------------------
Determines whether the `email` is valid or not, for various definitions thereof. Optionally accepts an `options` object. Options may include `errorLevel`.
Use `errorLevel` to specify the type of result for `validate()`. Passing a `false` literal will result in a true or false boolean indicating whether the email address is sufficiently defined for use in sending an email. Passing a `true` literal will result in a more granular numeric status, with zero being a perfectly valid email address. Passing a number will return `0` if the numeric status is below the `errorLevel` and the numeric status otherwise.
The `tldBlacklist` option can be either an object lookup table or an array of invalid top-level domains. If the email address has a top-level domain that is in the whitelist, the email will be marked as invalid.
The `tldWhitelist` option can be either an object lookup table or an array of valid top-level domains. If the email address has a top-level domain that is not in the whitelist, the email will be marked as invalid.
The `allowUnicode` option governs whether non-ASCII characters are allowed. Defaults to `true` per RFC 6530.
Only one of `tldBlacklist` and `tldWhitelist` will be consulted for TLD validity.
The `minDomainAtoms` option is an optional positive integer that specifies the minimum number of domain atoms that must be included for the email address to be considered valid. Be careful with the option, as some top-level domains, like `io`, directly support email addresses.
As of `3.1.1`, the `callback` parameter is deprecated, and will be removed in `4.0.0`.
### Examples
```js
$ node
> var Isemail = require('isemail');
undefined
> Isemail.validate('test@iana.org');
true
> Isemail.validate('test@iana.123');
true
> Isemail.validate('test@iana.org', {errorLevel: true});
0
> Isemail.validate('test@iana.123', {errorLevel: true});
10
> Isemail.validate('test@iana.123', {errorLevel: 17});
0
> Isemail.validate('test@iana.123', {errorLevel: 10});
10
> Isemail.validate('test@iana&12');
false
> Isemail.validate('test@iana&12', {errorLevel: true});
65
> Isemail.validate('test@', {errorLevel: true});
131
```
<sup name="footnote-1">&#91;1&#93;</sup>: if this badge indicates the build is passing, then isemail has 100% code coverage.
[skeggse]: https://github.com/skeggse "Eli Skeggs"
[tests]: http://isemail.info/_system/is_email/test/?all "is_email test suite"

64
node_modules/isemail/lib/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,64 @@
// Code shows a string is valid,
// but docs require string array or object.
type TLDList = string | string[] | { [topLevelDomain: string]: any };
type BaseOptions = {
tldWhitelist?: TLDList;
tldBlacklist?: TLDList;
minDomainAtoms?: number;
allowUnicode?: boolean;
};
type OptionsWithBool = BaseOptions & {
errorLevel?: false;
};
type OptionsWithNumThreshold = BaseOptions & {
errorLevel?: true | number;
};
interface Validator {
/**
* Check that an email address conforms to RFCs 5321, 5322, 6530 and others.
*
* ```
* import * as IsEmail from "isemail";
*
* IsEmail.validate("test@e.com");
* // => true
* ```
*/
validate(email: string): boolean;
/**
* Check that an email address conforms to RFCs 5321, 5322, 6530 and others.
*
* ```
* import * as IsEmail from "isemail";
*
* IsEmail.validate("test@iana.org", { errorLevel: false });
* // => true
* ```
*/
validate(email: string, options: OptionsWithBool): boolean;
/**
* Check that an email address conforms to RFCs 5321, 5322, 6530 and others.
*
* ```
* import * as IsEmail from "isemail";
*
* IsEmail.validate("test@iana.org", { errorLevel: true });
* // => 0
* IsEmail.validate("test @e.com", { errorLevel: 50 });
* // => 0
* IsEmail.validate('test @e.com', { errorLevel: true })
* // => 49
* ```
*/
validate(email: string, options: OptionsWithNumThreshold): number;
}
declare const IsEmail: Validator;
export = IsEmail;

1499
node_modules/isemail/lib/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

68
node_modules/isemail/package.json generated vendored Normal file
View File

@ -0,0 +1,68 @@
{
"_from": "isemail@3.x.x",
"_id": "isemail@3.2.0",
"_inBundle": false,
"_integrity": "sha512-zKqkK+O+dGqevc93KNsbZ/TqTUFd46MwWjYOoMrjIMZ51eU7DtQG3Wmd9SQQT7i7RVnuTPEiYEWHU3MSbxC1Tg==",
"_location": "/isemail",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "isemail@3.x.x",
"name": "isemail",
"escapedName": "isemail",
"rawSpec": "3.x.x",
"saveSpec": null,
"fetchSpec": "3.x.x"
},
"_requiredBy": [
"/joi"
],
"_resolved": "https://registry.npmjs.org/isemail/-/isemail-3.2.0.tgz",
"_shasum": "59310a021931a9fb06bbb51e155ce0b3f236832c",
"_spec": "isemail@3.x.x",
"_where": "/var/www/html/gtg2nodejs/node_modules/joi",
"bugs": {
"url": "https://github.com/hapijs/isemail/issues"
},
"bundleDependencies": false,
"dependencies": {
"punycode": "2.x.x"
},
"deprecated": false,
"description": "Validate an email address according to RFCs 5321, 5322, and others",
"devDependencies": {
"code": "^5.2.0",
"lab": "^16.1.0"
},
"engines": {
"node": ">=4.0.0"
},
"files": [
"lib/"
],
"homepage": "https://github.com/hapijs/isemail#readme",
"keywords": [
"isemail",
"validation",
"check",
"checking",
"verification",
"email",
"address",
"email address"
],
"license": "BSD-3-Clause",
"main": "lib/index.js",
"name": "isemail",
"repository": {
"type": "git",
"url": "git://github.com/hapijs/isemail.git"
},
"scripts": {
"test": "lab -a code -t 100 -L -m 5000",
"test-cov-html": "lab -a code -r html -o coverage.html -m 5000"
},
"types": "lib/index.d.ts",
"version": "3.2.0"
}

3
node_modules/joi/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,3 @@
Breaking changes are documented using GitHub issues, see [issues labeled "release notes"](https://github.com/hapijs/joi/issues?q=is%3Aissue+label%3A%22release+notes%22).
If you want changes of a specific minor or patch release, you can browse the [GitHub milestones](https://github.com/hapijs/joi/milestones?state=closed&direction=asc&sort=due_date).

29
node_modules/joi/LICENSE generated vendored Normal file
View File

@ -0,0 +1,29 @@
Copyright (c) 2012-2018, Project contributors
Copyright (c) 2012-2014, Walmart
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of any contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* * *
The complete list of contributors can be found at: https://github.com/hapijs/joi/graphs/contributors

128
node_modules/joi/README.md generated vendored Normal file
View File

@ -0,0 +1,128 @@
![joi Logo](https://raw.github.com/hapijs/joi/master/images/joi.png)
Object schema description language and validator for JavaScript objects.
[![npm version](https://badge.fury.io/js/joi.svg)](http://badge.fury.io/js/joi)
[![Build Status](https://travis-ci.org/hapijs/joi.svg?branch=master)](https://travis-ci.org/hapijs/joi)
[![NSP Status](https://nodesecurity.io/orgs/hapijs/projects/0394bf83-b5bc-410b-878c-e8cf1b92033e/badge)](https://nodesecurity.io/orgs/hapijs/projects/0394bf83-b5bc-410b-878c-e8cf1b92033e)
[![Known Vulnerabilities](https://snyk.io/test/github/hapijs/joi/badge.svg)](https://snyk.io/test/github/hapijs/joi)
Lead Maintainer: [Nicolas Morel](https://github.com/marsup)
# Introduction
Imagine you run facebook and you want visitors to sign up on the website with real names and not something like `l337_p@nda` in the first name field. How would you define the limitations of what can be inputted and validate it against the set rules?
This is joi, joi allows you to create *blueprints* or *schemas* for JavaScript objects (an object that stores information) to ensure *validation* of key information.
# API
See the detailed [API Reference](https://github.com/hapijs/joi/blob/v13.7.0/API.md).
# Example
```javascript
const Joi = require('joi');
const schema = Joi.object().keys({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
access_token: [Joi.string(), Joi.number()],
birthyear: Joi.number().integer().min(1900).max(2013),
email: Joi.string().email({ minDomainAtoms: 2 })
}).with('username', 'birthyear').without('password', 'access_token');
// Return result.
const result = Joi.validate({ username: 'abc', birthyear: 1994 }, schema);
// result.error === null -> valid
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate({ username: 'abc', birthyear: 1994 }, schema, function (err, value) { }); // err === null -> valid
```
The above schema defines the following constraints:
* `username`
* a required string
* must contain only alphanumeric characters
* at least 3 characters long but no more than 30
* must be accompanied by `birthyear`
* `password`
* an optional string
* must satisfy the custom regex
* cannot appear together with `access_token`
* `access_token`
* an optional, unconstrained string or number
* `birthyear`
* an integer between 1900 and 2013
* `email`
* a valid email address string
* must have two domain parts e.g. `example.com`
# Usage
Usage is a two steps process. First, a schema is constructed using the provided types and constraints:
```javascript
const schema = {
a: Joi.string()
};
```
Note that **joi** schema objects are immutable which means every additional rule added (e.g. `.min(5)`) will return a
new schema object.
Then the value is validated against the schema:
```javascript
const {error, value} = Joi.validate({ a: 'a string' }, schema);
// or
Joi.validate({ a: 'a string' }, schema, function (err, value) { });
```
If the input is valid, then the error will be `null`, otherwise it will be an Error object.
The schema can be a plain JavaScript object where every key is assigned a **joi** type, or it can be a **joi** type directly:
```javascript
const schema = Joi.string().min(10);
```
If the schema is a **joi** type, the `schema.validate(value, callback)` can be called directly on the type. When passing a non-type schema object,
the module converts it internally to an object() type equivalent to:
```javascript
const schema = Joi.object().keys({
a: Joi.string()
});
```
When validating a schema:
* Values (or keys in case of objects) are optional by default.
```javascript
Joi.validate(undefined, Joi.string()); // validates fine
```
To disallow this behavior, you can either set the schema as `required()`, or set `presence` to `"required"` when passing `options`:
```javascript
Joi.validate(undefined, Joi.string().required());
// or
Joi.validate(undefined, Joi.string(), /* options */ { presence: "required" });
```
* Strings are utf-8 encoded by default.
* Rules are defined in an additive fashion and evaluated in order after whitelist and blacklist checks.
# Browsers
Joi doesn't directly support browsers, but you could use [joi-browser](https://github.com/jeffbski/joi-browser) for an ES5 build of Joi that works in browsers, or as a source of inspiration for your own builds.
## Acknowledgements
This project is kindly sponsored by:
[![nearForm logo](https://www.nearform.com/img/nearform-logotype.svg)](https://nearform.com)

64
node_modules/joi/lib/cast.js generated vendored Normal file
View File

@ -0,0 +1,64 @@
'use strict';
// Load modules
const Hoek = require('hoek');
const Ref = require('./ref');
// Type modules are delay-loaded to prevent circular dependencies
// Declare internals
const internals = {};
exports.schema = function (Joi, config) {
if (config !== undefined && config !== null && typeof config === 'object') {
if (config.isJoi) {
return config;
}
if (Array.isArray(config)) {
return Joi.alternatives().try(config);
}
if (config instanceof RegExp) {
return Joi.string().regex(config);
}
if (config instanceof Date) {
return Joi.date().valid(config);
}
return Joi.object().keys(config);
}
if (typeof config === 'string') {
return Joi.string().valid(config);
}
if (typeof config === 'number') {
return Joi.number().valid(config);
}
if (typeof config === 'boolean') {
return Joi.boolean().valid(config);
}
if (Ref.isRef(config)) {
return Joi.valid(config);
}
Hoek.assert(config === null, 'Invalid schema content:', config);
return Joi.valid(null);
};
exports.ref = function (id) {
return Ref.isRef(id) ? id : Ref.create(id);
};

363
node_modules/joi/lib/errors.js generated vendored Executable file
View File

@ -0,0 +1,363 @@
'use strict';
// Load modules
const Hoek = require('hoek');
const Language = require('./language');
// Declare internals
const internals = {
annotations: Symbol('joi-annotations')
};
internals.stringify = function (value, wrapArrays) {
const type = typeof value;
if (value === null) {
return 'null';
}
if (type === 'string') {
return value;
}
if (value instanceof exports.Err || type === 'function' || type === 'symbol') {
return value.toString();
}
if (type === 'object') {
if (Array.isArray(value)) {
let partial = '';
for (let i = 0; i < value.length; ++i) {
partial = partial + (partial.length ? ', ' : '') + internals.stringify(value[i], wrapArrays);
}
return wrapArrays ? '[' + partial + ']' : partial;
}
return value.toString();
}
return JSON.stringify(value);
};
exports.Err = class {
constructor(type, context, state, options, flags, message, template) {
this.isJoi = true;
this.type = type;
this.context = context || {};
this.context.key = state.path[state.path.length - 1];
this.context.label = state.key;
this.path = state.path;
this.options = options;
this.flags = flags;
this.message = message;
this.template = template;
const localized = this.options.language;
if (this.flags.label) {
this.context.label = this.flags.label;
}
else if (localized && // language can be null for arrays exclusion check
(this.context.label === '' ||
this.context.label === null)) {
this.context.label = localized.root || Language.errors.root;
}
}
toString() {
if (this.message) {
return this.message;
}
let format;
if (this.template) {
format = this.template;
}
const localized = this.options.language;
format = format || Hoek.reach(localized, this.type) || Hoek.reach(Language.errors, this.type);
if (format === undefined) {
return `Error code "${this.type}" is not defined, your custom type is missing the correct language definition`;
}
let wrapArrays = Hoek.reach(localized, 'messages.wrapArrays');
if (typeof wrapArrays !== 'boolean') {
wrapArrays = Language.errors.messages.wrapArrays;
}
if (format === null) {
const childrenString = internals.stringify(this.context.reason, wrapArrays);
if (wrapArrays) {
return childrenString.slice(1, -1);
}
return childrenString;
}
const hasKey = /\{\{\!?label\}\}/.test(format);
const skipKey = format.length > 2 && format[0] === '!' && format[1] === '!';
if (skipKey) {
format = format.slice(2);
}
if (!hasKey && !skipKey) {
const localizedKey = Hoek.reach(localized, 'key');
if (typeof localizedKey === 'string') {
format = localizedKey + format;
}
else {
format = Hoek.reach(Language.errors, 'key') + format;
}
}
return format.replace(/\{\{(\!?)([^}]+)\}\}/g, ($0, isSecure, name) => {
const value = Hoek.reach(this.context, name);
const normalized = internals.stringify(value, wrapArrays);
return (isSecure && this.options.escapeHtml ? Hoek.escapeHtml(normalized) : normalized);
});
}
};
exports.create = function (type, context, state, options, flags, message, template) {
return new exports.Err(type, context, state, options, flags, message, template);
};
exports.process = function (errors, object) {
if (!errors || !errors.length) {
return null;
}
// Construct error
let message = '';
const details = [];
const processErrors = function (localErrors, parent) {
for (let i = 0; i < localErrors.length; ++i) {
const item = localErrors[i];
if (item instanceof Error) {
return item;
}
if (item.flags.error && typeof item.flags.error !== 'function') {
return item.flags.error;
}
let itemMessage;
if (parent === undefined) {
itemMessage = item.toString();
message = message + (message ? '. ' : '') + itemMessage;
}
// Do not push intermediate errors, we're only interested in leafs
if (item.context.reason && item.context.reason.length) {
const override = processErrors(item.context.reason, item.path);
if (override) {
return override;
}
}
else {
details.push({
message: itemMessage || item.toString(),
path: item.path,
type: item.type,
context: item.context
});
}
}
};
const override = processErrors(errors);
if (override) {
return override;
}
const error = new Error(message);
error.isJoi = true;
error.name = 'ValidationError';
error.details = details;
error._object = object;
error.annotate = internals.annotate;
return error;
};
// Inspired by json-stringify-safe
internals.safeStringify = function (obj, spaces) {
return JSON.stringify(obj, internals.serializer(), spaces);
};
internals.serializer = function () {
const keys = [];
const stack = [];
const cycleReplacer = (key, value) => {
if (stack[0] === value) {
return '[Circular ~]';
}
return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';
};
return function (key, value) {
if (stack.length > 0) {
const thisPos = stack.indexOf(this);
if (~thisPos) {
stack.length = thisPos + 1;
keys.length = thisPos + 1;
keys[thisPos] = key;
}
else {
stack.push(this);
keys.push(key);
}
if (~stack.indexOf(value)) {
value = cycleReplacer.call(this, key, value);
}
}
else {
stack.push(value);
}
if (value) {
const annotations = value[internals.annotations];
if (annotations) {
if (Array.isArray(value)) {
const annotated = [];
for (let i = 0; i < value.length; ++i) {
if (annotations.errors[i]) {
annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`);
}
annotated.push(value[i]);
}
value = annotated;
}
else {
const errorKeys = Object.keys(annotations.errors);
for (let i = 0; i < errorKeys.length; ++i) {
const errorKey = errorKeys[i];
value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey];
value[errorKey] = undefined;
}
const missingKeys = Object.keys(annotations.missing);
for (let i = 0; i < missingKeys.length; ++i) {
const missingKey = missingKeys[i];
value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__';
}
}
return value;
}
}
if (value === Infinity || value === -Infinity || Number.isNaN(value) ||
typeof value === 'function' || typeof value === 'symbol') {
return '[' + value.toString() + ']';
}
return value;
};
};
internals.annotate = function (stripColorCodes) {
const redFgEscape = stripColorCodes ? '' : '\u001b[31m';
const redBgEscape = stripColorCodes ? '' : '\u001b[41m';
const endColor = stripColorCodes ? '' : '\u001b[0m';
if (typeof this._object !== 'object') {
return this.details[0].message;
}
const obj = Hoek.clone(this._object || {});
for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first
const pos = i + 1;
const error = this.details[i];
const path = error.path;
let ref = obj;
for (let j = 0; ; ++j) {
const seg = path[j];
if (ref.isImmutable) {
ref = ref.clone(); // joi schemas are not cloned by hoek, we have to take this extra step
}
if (j + 1 < path.length &&
ref[seg] &&
typeof ref[seg] !== 'string') {
ref = ref[seg];
}
else {
const refAnnotations = ref[internals.annotations] = ref[internals.annotations] || { errors: {}, missing: {} };
const value = ref[seg];
const cacheKey = seg || error.context.label;
if (value !== undefined) {
refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || [];
refAnnotations.errors[cacheKey].push(pos);
}
else {
refAnnotations.missing[cacheKey] = pos;
}
break;
}
}
}
const replacers = {
key: /_\$key\$_([, \d]+)_\$end\$_\"/g,
missing: /\"_\$miss\$_([^\|]+)\|(\d+)_\$end\$_\"\: \"__missing__\"/g,
arrayIndex: /\s*\"_\$idx\$_([, \d]+)_\$end\$_\",?\n(.*)/g,
specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)\]"/g
};
let message = internals.safeStringify(obj, 2)
.replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`)
.replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`)
.replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`)
.replace(replacers.specials, ($0, $1) => $1);
message = `${message}\n${redFgEscape}`;
for (let i = 0; i < this.details.length; ++i) {
const pos = i + 1;
message = `${message}\n[${pos}] ${this.details[i].message}`;
}
message = message + endColor;
return message;
};

447
node_modules/joi/lib/index.js generated vendored Normal file
View File

@ -0,0 +1,447 @@
'use strict';
// Load modules
const Hoek = require('hoek');
const Any = require('./types/any');
const Cast = require('./cast');
const Errors = require('./errors');
const Lazy = require('./types/lazy');
const Ref = require('./ref');
const Settings = require('./types/any/settings');
// Declare internals
const internals = {
alternatives: require('./types/alternatives'),
array: require('./types/array'),
boolean: require('./types/boolean'),
binary: require('./types/binary'),
date: require('./types/date'),
func: require('./types/func'),
number: require('./types/number'),
object: require('./types/object'),
string: require('./types/string'),
symbol: require('./types/symbol')
};
internals.callWithDefaults = function (schema, args) {
Hoek.assert(this, 'Must be invoked on a Joi instance.');
if (this._defaults) {
schema = this._defaults(schema);
}
schema._currentJoi = this;
return schema._init(...args);
};
internals.root = function () {
const any = new Any();
const root = any.clone();
Any.prototype._currentJoi = root;
root._currentJoi = root;
root.any = function (...args) {
Hoek.assert(args.length === 0, 'Joi.any() does not allow arguments.');
return internals.callWithDefaults.call(this, any, args);
};
root.alternatives = root.alt = function (...args) {
return internals.callWithDefaults.call(this, internals.alternatives, args);
};
root.array = function (...args) {
Hoek.assert(args.length === 0, 'Joi.array() does not allow arguments.');
return internals.callWithDefaults.call(this, internals.array, args);
};
root.boolean = root.bool = function (...args) {
Hoek.assert(args.length === 0, 'Joi.boolean() does not allow arguments.');
return internals.callWithDefaults.call(this, internals.boolean, args);
};
root.binary = function (...args) {
Hoek.assert(args.length === 0, 'Joi.binary() does not allow arguments.');
return internals.callWithDefaults.call(this, internals.binary, args);
};
root.date = function (...args) {
Hoek.assert(args.length === 0, 'Joi.date() does not allow arguments.');
return internals.callWithDefaults.call(this, internals.date, args);
};
root.func = function (...args) {
Hoek.assert(args.length === 0, 'Joi.func() does not allow arguments.');
return internals.callWithDefaults.call(this, internals.func, args);
};
root.number = function (...args) {
Hoek.assert(args.length === 0, 'Joi.number() does not allow arguments.');
return internals.callWithDefaults.call(this, internals.number, args);
};
root.object = function (...args) {
return internals.callWithDefaults.call(this, internals.object, args);
};
root.string = function (...args) {
Hoek.assert(args.length === 0, 'Joi.string() does not allow arguments.');
return internals.callWithDefaults.call(this, internals.string, args);
};
root.symbol = function (...args) {
Hoek.assert(args.length === 0, 'Joi.symbol() does not allow arguments.');
return internals.callWithDefaults.call(this, internals.symbol, args);
};
root.ref = function (...args) {
return Ref.create(...args);
};
root.isRef = function (ref) {
return Ref.isRef(ref);
};
root.validate = function (value, ...args /*, [schema], [options], callback */) {
const last = args[args.length - 1];
const callback = typeof last === 'function' ? last : null;
const count = args.length - (callback ? 1 : 0);
if (count === 0) {
return any.validate(value, callback);
}
const options = count === 2 ? args[1] : undefined;
const schema = root.compile(args[0]);
return schema._validateWithOptions(value, options, callback);
};
root.describe = function (...args) {
const schema = args.length ? root.compile(args[0]) : any;
return schema.describe();
};
root.compile = function (schema) {
try {
return Cast.schema(this, schema);
}
catch (err) {
if (err.hasOwnProperty('path')) {
err.message = err.message + '(' + err.path + ')';
}
throw err;
}
};
root.assert = function (value, schema, message) {
root.attempt(value, schema, message);
};
root.attempt = function (value, schema, message) {
const result = root.validate(value, schema);
const error = result.error;
if (error) {
if (!message) {
if (typeof error.annotate === 'function') {
error.message = error.annotate();
}
throw error;
}
if (!(message instanceof Error)) {
if (typeof error.annotate === 'function') {
error.message = `${message} ${error.annotate()}`;
}
throw error;
}
throw message;
}
return result.value;
};
root.reach = function (schema, path) {
Hoek.assert(schema && schema instanceof Any, 'you must provide a joi schema');
Hoek.assert(Array.isArray(path) || typeof path === 'string', 'path must be a string or an array of strings');
const reach = (sourceSchema, schemaPath) => {
if (!schemaPath.length) {
return sourceSchema;
}
const children = sourceSchema._inner.children;
if (!children) {
return;
}
const key = schemaPath.shift();
for (let i = 0; i < children.length; ++i) {
const child = children[i];
if (child.key === key) {
return reach(child.schema, schemaPath);
}
}
};
const schemaPath = typeof path === 'string' ? (path ? path.split('.') : []) : path.slice();
return reach(schema, schemaPath);
};
root.lazy = function (fn) {
return Lazy.set(fn);
};
root.defaults = function (fn) {
Hoek.assert(typeof fn === 'function', 'Defaults must be a function');
let joi = Object.create(this.any());
joi = fn(joi);
Hoek.assert(joi && joi instanceof this.constructor, 'defaults() must return a schema');
Object.assign(joi, this, joi.clone()); // Re-add the types from `this` but also keep the settings from joi's potential new defaults
joi._defaults = (schema) => {
if (this._defaults) {
schema = this._defaults(schema);
Hoek.assert(schema instanceof this.constructor, 'defaults() must return a schema');
}
schema = fn(schema);
Hoek.assert(schema instanceof this.constructor, 'defaults() must return a schema');
return schema;
};
return joi;
};
root.extend = function (...args) {
const extensions = Hoek.flatten(args);
Hoek.assert(extensions.length > 0, 'You need to provide at least one extension');
this.assert(extensions, root.extensionsSchema);
const joi = Object.create(this.any());
Object.assign(joi, this);
for (let i = 0; i < extensions.length; ++i) {
let extension = extensions[i];
if (typeof extension === 'function') {
extension = extension(joi);
}
this.assert(extension, root.extensionSchema);
const base = (extension.base || this.any()).clone(); // Cloning because we're going to override language afterwards
const ctor = base.constructor;
const type = class extends ctor { // eslint-disable-line no-loop-func
constructor() {
super();
if (extension.base) {
Object.assign(this, base);
}
this._type = extension.name;
if (extension.language) {
this._settings = Settings.concat(this._settings, {
language: {
[extension.name]: extension.language
}
});
}
}
};
if (extension.coerce) {
type.prototype._coerce = function (value, state, options) {
if (ctor.prototype._coerce) {
const baseRet = ctor.prototype._coerce.call(this, value, state, options);
if (baseRet.errors) {
return baseRet;
}
value = baseRet.value;
}
const ret = extension.coerce.call(this, value, state, options);
if (ret instanceof Errors.Err) {
return { value, errors: ret };
}
return { value: ret };
};
}
if (extension.pre) {
type.prototype._base = function (value, state, options) {
if (ctor.prototype._base) {
const baseRet = ctor.prototype._base.call(this, value, state, options);
if (baseRet.errors) {
return baseRet;
}
value = baseRet.value;
}
const ret = extension.pre.call(this, value, state, options);
if (ret instanceof Errors.Err) {
return { value, errors: ret };
}
return { value: ret };
};
}
if (extension.rules) {
for (let j = 0; j < extension.rules.length; ++j) {
const rule = extension.rules[j];
const ruleArgs = rule.params ?
(rule.params instanceof Any ? rule.params._inner.children.map((k) => k.key) : Object.keys(rule.params)) :
[];
const validateArgs = rule.params ? Cast.schema(this, rule.params) : null;
type.prototype[rule.name] = function (...rArgs) { // eslint-disable-line no-loop-func
if (rArgs.length > ruleArgs.length) {
throw new Error('Unexpected number of arguments');
}
let hasRef = false;
let arg = {};
for (let k = 0; k < ruleArgs.length; ++k) {
arg[ruleArgs[k]] = rArgs[k];
if (!hasRef && Ref.isRef(rArgs[k])) {
hasRef = true;
}
}
if (validateArgs) {
arg = joi.attempt(arg, validateArgs);
}
let schema;
if (rule.validate) {
const validate = function (value, state, options) {
return rule.validate.call(this, arg, value, state, options);
};
schema = this._test(rule.name, arg, validate, {
description: rule.description,
hasRef
});
}
else {
schema = this.clone();
}
if (rule.setup) {
const newSchema = rule.setup.call(schema, arg);
if (newSchema !== undefined) {
Hoek.assert(newSchema instanceof Any, `Setup of extension Joi.${this._type}().${rule.name}() must return undefined or a Joi object`);
schema = newSchema;
}
}
return schema;
};
}
}
if (extension.describe) {
type.prototype.describe = function () {
const description = ctor.prototype.describe.call(this);
return extension.describe.call(this, description);
};
}
const instance = new type();
joi[extension.name] = function (...extArgs) {
return internals.callWithDefaults.call(this, instance, extArgs);
};
}
return joi;
};
root.extensionSchema = internals.object.keys({
base: internals.object.type(Any, 'Joi object'),
name: internals.string.required(),
coerce: internals.func.arity(3),
pre: internals.func.arity(3),
language: internals.object,
describe: internals.func.arity(1),
rules: internals.array.items(internals.object.keys({
name: internals.string.required(),
setup: internals.func.arity(1),
validate: internals.func.arity(4),
params: [
internals.object.pattern(/.*/, internals.object.type(Any, 'Joi object')),
internals.object.type(internals.object.constructor, 'Joi object')
],
description: [internals.string, internals.func.arity(1)]
}).or('setup', 'validate'))
}).strict();
root.extensionsSchema = internals.array.items([internals.object, internals.func.arity(1)]).strict();
root.version = require('../package.json').version;
return root;
};
module.exports = internals.root();

165
node_modules/joi/lib/language.js generated vendored Normal file
View File

@ -0,0 +1,165 @@
'use strict';
// Load modules
// Declare internals
const internals = {};
exports.errors = {
root: 'value',
key: '"{{!label}}" ',
messages: {
wrapArrays: true
},
any: {
unknown: 'is not allowed',
invalid: 'contains an invalid value',
empty: 'is not allowed to be empty',
required: 'is required',
allowOnly: 'must be one of {{valids}}',
default: 'threw an error when running default method'
},
alternatives: {
base: 'not matching any of the allowed alternatives',
child: null
},
array: {
base: 'must be an array',
includes: 'at position {{pos}} does not match any of the allowed types',
includesSingle: 'single value of "{{!label}}" does not match any of the allowed types',
includesOne: 'at position {{pos}} fails because {{reason}}',
includesOneSingle: 'single value of "{{!label}}" fails because {{reason}}',
includesRequiredUnknowns: 'does not contain {{unknownMisses}} required value(s)',
includesRequiredKnowns: 'does not contain {{knownMisses}}',
includesRequiredBoth: 'does not contain {{knownMisses}} and {{unknownMisses}} other required value(s)',
excludes: 'at position {{pos}} contains an excluded value',
excludesSingle: 'single value of "{{!label}}" contains an excluded value',
min: 'must contain at least {{limit}} items',
max: 'must contain less than or equal to {{limit}} items',
length: 'must contain {{limit}} items',
ordered: 'at position {{pos}} fails because {{reason}}',
orderedLength: 'at position {{pos}} fails because array must contain at most {{limit}} items',
ref: 'references "{{ref}}" which is not a positive integer',
sparse: 'must not be a sparse array',
unique: 'position {{pos}} contains a duplicate value'
},
boolean: {
base: 'must be a boolean'
},
binary: {
base: 'must be a buffer or a string',
min: 'must be at least {{limit}} bytes',
max: 'must be less than or equal to {{limit}} bytes',
length: 'must be {{limit}} bytes'
},
date: {
base: 'must be a number of milliseconds or valid date string',
format: 'must be a string with one of the following formats {{format}}',
strict: 'must be a valid date',
min: 'must be larger than or equal to "{{limit}}"',
max: 'must be less than or equal to "{{limit}}"',
less: 'must be less than "{{limit}}"',
greater: 'must be greater than "{{limit}}"',
isoDate: 'must be a valid ISO 8601 date',
timestamp: {
javascript: 'must be a valid timestamp or number of milliseconds',
unix: 'must be a valid timestamp or number of seconds'
},
ref: 'references "{{ref}}" which is not a date'
},
function: {
base: 'must be a Function',
arity: 'must have an arity of {{n}}',
minArity: 'must have an arity greater or equal to {{n}}',
maxArity: 'must have an arity lesser or equal to {{n}}',
ref: 'must be a Joi reference',
class: 'must be a class'
},
lazy: {
base: '!!schema error: lazy schema must be set',
schema: '!!schema error: lazy schema function must return a schema'
},
object: {
base: 'must be an object',
child: '!!child "{{!child}}" fails because {{reason}}',
min: 'must have at least {{limit}} children',
max: 'must have less than or equal to {{limit}} children',
length: 'must have {{limit}} children',
allowUnknown: '!!"{{!child}}" is not allowed',
with: '!!"{{mainWithLabel}}" missing required peer "{{peerWithLabel}}"',
without: '!!"{{mainWithLabel}}" conflict with forbidden peer "{{peerWithLabel}}"',
missing: 'must contain at least one of {{peersWithLabels}}',
xor: 'contains a conflict between exclusive peers {{peersWithLabels}}',
or: 'must contain at least one of {{peersWithLabels}}',
and: 'contains {{presentWithLabels}} without its required peers {{missingWithLabels}}',
nand: '!!"{{mainWithLabel}}" must not exist simultaneously with {{peersWithLabels}}',
assert: '!!"{{ref}}" validation failed because "{{ref}}" failed to {{message}}',
rename: {
multiple: 'cannot rename child "{{from}}" because multiple renames are disabled and another key was already renamed to "{{to}}"',
override: 'cannot rename child "{{from}}" because override is disabled and target "{{to}}" exists',
regex: {
multiple: 'cannot rename children {{from}} because multiple renames are disabled and another key was already renamed to "{{to}}"',
override: 'cannot rename children {{from}} because override is disabled and target "{{to}}" exists'
}
},
type: 'must be an instance of "{{type}}"',
schema: 'must be a Joi instance'
},
number: {
base: 'must be a number',
min: 'must be larger than or equal to {{limit}}',
max: 'must be less than or equal to {{limit}}',
less: 'must be less than {{limit}}',
greater: 'must be greater than {{limit}}',
float: 'must be a float or double',
integer: 'must be an integer',
negative: 'must be a negative number',
positive: 'must be a positive number',
precision: 'must have no more than {{limit}} decimal places',
ref: 'references "{{ref}}" which is not a number',
multiple: 'must be a multiple of {{multiple}}',
port: 'must be a valid port'
},
string: {
base: 'must be a string',
min: 'length must be at least {{limit}} characters long',
max: 'length must be less than or equal to {{limit}} characters long',
length: 'length must be {{limit}} characters long',
alphanum: 'must only contain alpha-numeric characters',
token: 'must only contain alpha-numeric and underscore characters',
regex: {
base: 'with value "{{!value}}" fails to match the required pattern: {{pattern}}',
name: 'with value "{{!value}}" fails to match the {{name}} pattern',
invert: {
base: 'with value "{{!value}}" matches the inverted pattern: {{pattern}}',
name: 'with value "{{!value}}" matches the inverted {{name}} pattern'
}
},
email: 'must be a valid email',
uri: 'must be a valid uri',
uriRelativeOnly: 'must be a valid relative uri',
uriCustomScheme: 'must be a valid uri with a scheme matching the {{scheme}} pattern',
isoDate: 'must be a valid ISO 8601 date',
guid: 'must be a valid GUID',
hex: 'must only contain hexadecimal characters',
hexAlign: 'hex decoded representation must be byte aligned',
base64: 'must be a valid base64 string',
dataUri: 'must be a valid dataUri string',
hostname: 'must be a valid hostname',
normalize: 'must be unicode normalized in the {{form}} form',
lowercase: 'must only contain lowercase characters',
uppercase: 'must only contain uppercase characters',
trim: 'must not have leading or trailing whitespace',
creditCard: 'must be a credit card',
ref: 'references "{{ref}}" which is not a number',
ip: 'must be a valid ip address with a {{cidr}} CIDR',
ipVersion: 'must be a valid ip address of one of the following versions {{version}} with a {{cidr}} CIDR'
},
symbol: {
base: 'must be a symbol',
map: 'must be one of {{map}}'
}
};

53
node_modules/joi/lib/ref.js generated vendored Normal file
View File

@ -0,0 +1,53 @@
'use strict';
// Load modules
const Hoek = require('hoek');
// Declare internals
const internals = {};
exports.create = function (key, options) {
Hoek.assert(typeof key === 'string', 'Invalid reference key:', key);
const settings = Hoek.clone(options); // options can be reused and modified
const ref = function (value, validationOptions) {
return Hoek.reach(ref.isContext ? validationOptions.context : value, ref.key, settings);
};
ref.isContext = (key[0] === ((settings && settings.contextPrefix) || '$'));
ref.key = (ref.isContext ? key.slice(1) : key);
ref.path = ref.key.split((settings && settings.separator) || '.');
ref.depth = ref.path.length;
ref.root = ref.path[0];
ref.isJoi = true;
ref.toString = function () {
return (ref.isContext ? 'context:' : 'ref:') + ref.key;
};
return ref;
};
exports.isRef = function (ref) {
return typeof ref === 'function' && ref.isJoi;
};
exports.push = function (array, ref) {
if (exports.isRef(ref) &&
!ref.isContext) {
array.push(ref.root);
}
};

25
node_modules/joi/lib/schemas.js generated vendored Normal file
View File

@ -0,0 +1,25 @@
'use strict';
// Load modules
const Joi = require('./index');
// Declare internals
const internals = {};
exports.options = Joi.object({
abortEarly: Joi.boolean(),
convert: Joi.boolean(),
allowUnknown: Joi.boolean(),
skipFunctions: Joi.boolean(),
stripUnknown: [Joi.boolean(), Joi.object({ arrays: Joi.boolean(), objects: Joi.boolean() }).or('arrays', 'objects')],
language: Joi.object(),
presence: Joi.string().only('required', 'optional', 'forbidden', 'ignore'),
raw: Joi.boolean(),
context: Joi.object(),
strip: Joi.boolean(),
noDefaults: Joi.boolean(),
escapeHtml: Joi.boolean()
}).strict();

178
node_modules/joi/lib/set.js generated vendored Normal file
View File

@ -0,0 +1,178 @@
'use strict';
const Ref = require('./ref');
const internals = {};
internals.extendedCheckForValue = function (value, insensitive) {
const valueType = typeof value;
if (valueType === 'object') {
if (value instanceof Date) {
return (item) => {
return item instanceof Date && value.getTime() === item.getTime();
};
}
if (Buffer.isBuffer(value)) {
return (item) => {
return Buffer.isBuffer(item) && value.length === item.length && value.toString('binary') === item.toString('binary');
};
}
}
else if (insensitive && valueType === 'string') {
const lowercaseValue = value.toLowerCase();
return (item) => {
return typeof item === 'string' && lowercaseValue === item.toLowerCase();
};
}
return null;
};
module.exports = class InternalSet {
constructor(from) {
this._set = new Set(from);
this._hasRef = false;
}
add(value, refs) {
const isRef = Ref.isRef(value);
if (!isRef && this.has(value, null, null, false)) {
return this;
}
if (refs !== undefined) { // If it's a merge, we don't have any refs
Ref.push(refs, value);
}
this._set.add(value);
this._hasRef |= isRef;
return this;
}
merge(add, remove) {
for (const item of add._set) {
this.add(item);
}
for (const item of remove._set) {
this.remove(item);
}
return this;
}
remove(value) {
this._set.delete(value);
return this;
}
has(value, state, options, insensitive) {
if (!this._set.size) {
return false;
}
const hasValue = this._set.has(value);
if (hasValue) {
return hasValue;
}
const extendedCheck = internals.extendedCheckForValue(value, insensitive);
if (!extendedCheck) {
if (state && this._hasRef) {
for (let item of this._set) {
if (Ref.isRef(item)) {
item = item(state.reference || state.parent, options);
if (value === item || (Array.isArray(item) && item.includes(value))) {
return true;
}
}
}
}
return false;
}
return this._has(value, state, options, extendedCheck);
}
_has(value, state, options, check) {
const checkRef = !!(state && this._hasRef);
const isReallyEqual = function (item) {
if (value === item) {
return true;
}
return check(item);
};
for (let item of this._set) {
if (checkRef && Ref.isRef(item)) { // Only resolve references if there is a state, otherwise it's a merge
item = item(state.reference || state.parent, options);
if (Array.isArray(item)) {
if (item.find(isReallyEqual)) {
return true;
}
continue;
}
}
if (isReallyEqual(item)) {
return true;
}
}
return false;
}
values(options) {
if (options && options.stripUndefined) {
const values = [];
for (const item of this._set) {
if (item !== undefined) {
values.push(item);
}
}
return values;
}
return Array.from(this._set);
}
slice() {
const set = new InternalSet(this._set);
set._hasRef = this._hasRef;
return set;
}
concat(source) {
const set = new InternalSet([...this._set, ...source._set]);
set._hasRef = !!(this._hasRef | source._hasRef);
return set;
}
};

193
node_modules/joi/lib/types/alternatives/index.js generated vendored Normal file
View File

@ -0,0 +1,193 @@
'use strict';
// Load modules
const Hoek = require('hoek');
const Any = require('../any');
const Cast = require('../../cast');
const Ref = require('../../ref');
// Declare internals
const internals = {};
internals.Alternatives = class extends Any {
constructor() {
super();
this._type = 'alternatives';
this._invalids.remove(null);
this._inner.matches = [];
}
_init(...args) {
return args.length ? this.try(...args) : this;
}
_base(value, state, options) {
let errors = [];
const il = this._inner.matches.length;
const baseType = this._baseType;
for (let i = 0; i < il; ++i) {
const item = this._inner.matches[i];
if (!item.schema) {
const schema = item.peek || item.is;
const input = item.is ? item.ref(state.reference || state.parent, options) : value;
const failed = schema._validate(input, null, options, state.parent).errors;
if (failed) {
if (item.otherwise) {
return item.otherwise._validate(value, state, options);
}
}
else if (item.then) {
return item.then._validate(value, state, options);
}
if (i === (il - 1) && baseType) {
return baseType._validate(value, state, options);
}
continue;
}
const result = item.schema._validate(value, state, options);
if (!result.errors) { // Found a valid match
return result;
}
errors = errors.concat(result.errors);
}
if (errors.length) {
return { errors: this.createError('alternatives.child', { reason: errors }, state, options) };
}
return { errors: this.createError('alternatives.base', null, state, options) };
}
try(...schemas) {
schemas = Hoek.flatten(schemas);
Hoek.assert(schemas.length, 'Cannot add other alternatives without at least one schema');
const obj = this.clone();
for (let i = 0; i < schemas.length; ++i) {
const cast = Cast.schema(this._currentJoi, schemas[i]);
if (cast._refs.length) {
obj._refs = obj._refs.concat(cast._refs);
}
obj._inner.matches.push({ schema: cast });
}
return obj;
}
when(condition, options) {
let schemaCondition = false;
Hoek.assert(Ref.isRef(condition) || typeof condition === 'string' || (schemaCondition = condition instanceof Any), 'Invalid condition:', condition);
Hoek.assert(options, 'Missing options');
Hoek.assert(typeof options === 'object', 'Invalid options');
if (schemaCondition) {
Hoek.assert(!options.hasOwnProperty('is'), '"is" can not be used with a schema condition');
}
else {
Hoek.assert(options.hasOwnProperty('is'), 'Missing "is" directive');
}
Hoek.assert(options.then !== undefined || options.otherwise !== undefined, 'options must have at least one of "then" or "otherwise"');
const obj = this.clone();
let is;
if (!schemaCondition) {
is = Cast.schema(this._currentJoi, options.is);
if (options.is === null || !(Ref.isRef(options.is) || options.is instanceof Any)) {
// Only apply required if this wasn't already a schema or a ref, we'll suppose people know what they're doing
is = is.required();
}
}
const item = {
ref: schemaCondition ? null : Cast.ref(condition),
peek: schemaCondition ? condition : null,
is,
then: options.then !== undefined ? Cast.schema(this._currentJoi, options.then) : undefined,
otherwise: options.otherwise !== undefined ? Cast.schema(this._currentJoi, options.otherwise) : undefined
};
if (obj._baseType) {
item.then = item.then && obj._baseType.concat(item.then);
item.otherwise = item.otherwise && obj._baseType.concat(item.otherwise);
}
if (!schemaCondition) {
Ref.push(obj._refs, item.ref);
obj._refs = obj._refs.concat(item.is._refs);
}
if (item.then && item.then._refs) {
obj._refs = obj._refs.concat(item.then._refs);
}
if (item.otherwise && item.otherwise._refs) {
obj._refs = obj._refs.concat(item.otherwise._refs);
}
obj._inner.matches.push(item);
return obj;
}
describe() {
const description = super.describe();
const alternatives = [];
for (let i = 0; i < this._inner.matches.length; ++i) {
const item = this._inner.matches[i];
if (item.schema) {
// try()
alternatives.push(item.schema.describe());
}
else {
// when()
const when = item.is ? {
ref: item.ref.toString(),
is: item.is.describe()
} : {
peek: item.peek.describe()
};
if (item.then) {
when.then = item.then.describe();
}
if (item.otherwise) {
when.otherwise = item.otherwise.describe();
}
alternatives.push(when);
}
}
description.alternatives = alternatives;
return description;
}
};
module.exports = new internals.Alternatives();

889
node_modules/joi/lib/types/any/index.js generated vendored Normal file
View File

@ -0,0 +1,889 @@
'use strict';
// Load modules
const Hoek = require('hoek');
const Settings = require('./settings');
const Ref = require('../../ref');
const Errors = require('../../errors');
let Alternatives = null; // Delay-loaded to prevent circular dependencies
let Cast = null;
// Declare internals
const internals = {
Set: require('../../set')
};
internals.defaults = {
abortEarly: true,
convert: true,
allowUnknown: false,
skipFunctions: false,
stripUnknown: false,
language: {},
presence: 'optional',
strip: false,
noDefaults: false,
escapeHtml: false
// context: null
};
module.exports = internals.Any = class {
constructor() {
Cast = Cast || require('../../cast');
this.isJoi = true;
this._type = 'any';
this._settings = null;
this._valids = new internals.Set();
this._invalids = new internals.Set();
this._tests = [];
this._refs = [];
this._flags = {
/*
presence: 'optional', // optional, required, forbidden, ignore
allowOnly: false,
allowUnknown: undefined,
default: undefined,
forbidden: false,
encoding: undefined,
insensitive: false,
trim: false,
normalize: undefined, // NFC, NFD, NFKC, NFKD
case: undefined, // upper, lower
empty: undefined,
func: false,
raw: false
*/
};
this._description = null;
this._unit = null;
this._notes = [];
this._tags = [];
this._examples = [];
this._meta = [];
this._inner = {}; // Hash of arrays of immutable objects
}
_init() {
return this;
}
get schemaType() {
return this._type;
}
createError(type, context, state, options, flags = this._flags) {
return Errors.create(type, context, state, options, flags);
}
createOverrideError(type, context, state, options, message, template) {
return Errors.create(type, context, state, options, this._flags, message, template);
}
checkOptions(options) {
const Schemas = require('../../schemas');
const result = Schemas.options.validate(options);
if (result.error) {
throw new Error(result.error.details[0].message);
}
}
clone() {
const obj = Object.create(Object.getPrototypeOf(this));
obj.isJoi = true;
obj._currentJoi = this._currentJoi;
obj._type = this._type;
obj._settings = this._settings;
obj._baseType = this._baseType;
obj._valids = this._valids.slice();
obj._invalids = this._invalids.slice();
obj._tests = this._tests.slice();
obj._refs = this._refs.slice();
obj._flags = Hoek.clone(this._flags);
obj._description = this._description;
obj._unit = this._unit;
obj._notes = this._notes.slice();
obj._tags = this._tags.slice();
obj._examples = this._examples.slice();
obj._meta = this._meta.slice();
obj._inner = {};
const inners = Object.keys(this._inner);
for (let i = 0; i < inners.length; ++i) {
const key = inners[i];
obj._inner[key] = this._inner[key] ? this._inner[key].slice() : null;
}
return obj;
}
concat(schema) {
Hoek.assert(schema instanceof internals.Any, 'Invalid schema object');
Hoek.assert(this._type === 'any' || schema._type === 'any' || schema._type === this._type, 'Cannot merge type', this._type, 'with another type:', schema._type);
let obj = this.clone();
if (this._type === 'any' && schema._type !== 'any') {
// Reset values as if we were "this"
const tmpObj = schema.clone();
const keysToRestore = ['_settings', '_valids', '_invalids', '_tests', '_refs', '_flags', '_description', '_unit',
'_notes', '_tags', '_examples', '_meta', '_inner'];
for (let i = 0; i < keysToRestore.length; ++i) {
tmpObj[keysToRestore[i]] = obj[keysToRestore[i]];
}
obj = tmpObj;
}
obj._settings = obj._settings ? Settings.concat(obj._settings, schema._settings) : schema._settings;
obj._valids.merge(schema._valids, schema._invalids);
obj._invalids.merge(schema._invalids, schema._valids);
obj._tests = obj._tests.concat(schema._tests);
obj._refs = obj._refs.concat(schema._refs);
Hoek.merge(obj._flags, schema._flags);
obj._description = schema._description || obj._description;
obj._unit = schema._unit || obj._unit;
obj._notes = obj._notes.concat(schema._notes);
obj._tags = obj._tags.concat(schema._tags);
obj._examples = obj._examples.concat(schema._examples);
obj._meta = obj._meta.concat(schema._meta);
const inners = Object.keys(schema._inner);
const isObject = obj._type === 'object';
for (let i = 0; i < inners.length; ++i) {
const key = inners[i];
const source = schema._inner[key];
if (source) {
const target = obj._inner[key];
if (target) {
if (isObject && key === 'children') {
const keys = {};
for (let j = 0; j < target.length; ++j) {
keys[target[j].key] = j;
}
for (let j = 0; j < source.length; ++j) {
const sourceKey = source[j].key;
if (keys[sourceKey] >= 0) {
target[keys[sourceKey]] = {
key: sourceKey,
schema: target[keys[sourceKey]].schema.concat(source[j].schema)
};
}
else {
target.push(source[j]);
}
}
}
else {
obj._inner[key] = obj._inner[key].concat(source);
}
}
else {
obj._inner[key] = source.slice();
}
}
}
return obj;
}
_test(name, arg, func, options) {
const obj = this.clone();
obj._tests.push({ func, name, arg, options });
return obj;
}
options(options) {
Hoek.assert(!options.context, 'Cannot override context');
this.checkOptions(options);
const obj = this.clone();
obj._settings = Settings.concat(obj._settings, options);
return obj;
}
strict(isStrict) {
const obj = this.clone();
const convert = isStrict === undefined ? false : !isStrict;
obj._settings = Settings.concat(obj._settings, { convert });
return obj;
}
raw(isRaw) {
const value = isRaw === undefined ? true : isRaw;
if (this._flags.raw === value) {
return this;
}
const obj = this.clone();
obj._flags.raw = value;
return obj;
}
error(err) {
Hoek.assert(err && (err instanceof Error || typeof err === 'function'), 'Must provide a valid Error object or a function');
const obj = this.clone();
obj._flags.error = err;
return obj;
}
allow(...values) {
const obj = this.clone();
values = Hoek.flatten(values);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
Hoek.assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined');
obj._invalids.remove(value);
obj._valids.add(value, obj._refs);
}
return obj;
}
valid(...values) {
const obj = this.allow(...values);
obj._flags.allowOnly = true;
return obj;
}
invalid(...values) {
const obj = this.clone();
values = Hoek.flatten(values);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
Hoek.assert(value !== undefined, 'Cannot call allow/valid/invalid with undefined');
obj._valids.remove(value);
obj._invalids.add(value, obj._refs);
}
return obj;
}
required() {
if (this._flags.presence === 'required') {
return this;
}
const obj = this.clone();
obj._flags.presence = 'required';
return obj;
}
optional() {
if (this._flags.presence === 'optional') {
return this;
}
const obj = this.clone();
obj._flags.presence = 'optional';
return obj;
}
forbidden() {
if (this._flags.presence === 'forbidden') {
return this;
}
const obj = this.clone();
obj._flags.presence = 'forbidden';
return obj;
}
strip() {
if (this._flags.strip) {
return this;
}
const obj = this.clone();
obj._flags.strip = true;
return obj;
}
applyFunctionToChildren(children, fn, args, root) {
children = [].concat(children);
if (children.length !== 1 || children[0] !== '') {
root = root ? (root + '.') : '';
const extraChildren = (children[0] === '' ? children.slice(1) : children).map((child) => {
return root + child;
});
throw new Error('unknown key(s) ' + extraChildren.join(', '));
}
return this[fn].apply(this, args);
}
default(value, description) {
if (typeof value === 'function' &&
!Ref.isRef(value)) {
if (!value.description &&
description) {
value.description = description;
}
if (!this._flags.func) {
Hoek.assert(typeof value.description === 'string' && value.description.length > 0, 'description must be provided when default value is a function');
}
}
const obj = this.clone();
obj._flags.default = value;
Ref.push(obj._refs, value);
return obj;
}
empty(schema) {
const obj = this.clone();
if (schema === undefined) {
delete obj._flags.empty;
}
else {
obj._flags.empty = Cast.schema(this._currentJoi, schema);
}
return obj;
}
when(condition, options) {
Hoek.assert(options && typeof options === 'object', 'Invalid options');
Hoek.assert(options.then !== undefined || options.otherwise !== undefined, 'options must have at least one of "then" or "otherwise"');
const then = options.hasOwnProperty('then') ? this.concat(Cast.schema(this._currentJoi, options.then)) : undefined;
const otherwise = options.hasOwnProperty('otherwise') ? this.concat(Cast.schema(this._currentJoi, options.otherwise)) : undefined;
Alternatives = Alternatives || require('../alternatives');
const alternativeOptions = { then, otherwise };
if (Object.prototype.hasOwnProperty.call(options, 'is')) {
alternativeOptions.is = options.is;
}
const obj = Alternatives.when(condition, alternativeOptions);
obj._flags.presence = 'ignore';
obj._baseType = this;
return obj;
}
description(desc) {
Hoek.assert(desc && typeof desc === 'string', 'Description must be a non-empty string');
const obj = this.clone();
obj._description = desc;
return obj;
}
notes(notes) {
Hoek.assert(notes && (typeof notes === 'string' || Array.isArray(notes)), 'Notes must be a non-empty string or array');
const obj = this.clone();
obj._notes = obj._notes.concat(notes);
return obj;
}
tags(tags) {
Hoek.assert(tags && (typeof tags === 'string' || Array.isArray(tags)), 'Tags must be a non-empty string or array');
const obj = this.clone();
obj._tags = obj._tags.concat(tags);
return obj;
}
meta(meta) {
Hoek.assert(meta !== undefined, 'Meta cannot be undefined');
const obj = this.clone();
obj._meta = obj._meta.concat(meta);
return obj;
}
example(...args) {
Hoek.assert(args.length === 1, 'Missing example');
const value = args[0];
const obj = this.clone();
obj._examples.push(value);
return obj;
}
unit(name) {
Hoek.assert(name && typeof name === 'string', 'Unit name must be a non-empty string');
const obj = this.clone();
obj._unit = name;
return obj;
}
_prepareEmptyValue(value) {
if (typeof value === 'string' && this._flags.trim) {
return value.trim();
}
return value;
}
_validate(value, state, options, reference) {
const originalValue = value;
// Setup state and settings
state = state || { key: '', path: [], parent: null, reference };
if (this._settings) {
options = Settings.concat(options, this._settings);
}
let errors = [];
const finish = () => {
let finalValue;
if (value !== undefined) {
finalValue = this._flags.raw ? originalValue : value;
}
else if (options.noDefaults) {
finalValue = value;
}
else if (Ref.isRef(this._flags.default)) {
finalValue = this._flags.default(state.parent, options);
}
else if (typeof this._flags.default === 'function' &&
!(this._flags.func && !this._flags.default.description)) {
let args;
if (state.parent !== null &&
this._flags.default.length > 0) {
args = [Hoek.clone(state.parent), options];
}
const defaultValue = internals._try(this._flags.default, args);
finalValue = defaultValue.value;
if (defaultValue.error) {
errors.push(this.createError('any.default', { error: defaultValue.error }, state, options));
}
}
else {
finalValue = Hoek.clone(this._flags.default);
}
if (errors.length && typeof this._flags.error === 'function') {
const change = this._flags.error.call(this, errors);
if (typeof change === 'string') {
errors = [this.createOverrideError('override', { reason: errors }, state, options, change)];
}
else {
errors = [].concat(change)
.map((err) => {
return err instanceof Error ?
err :
this.createOverrideError(err.type || 'override', err.context, state, options, err.message, err.template);
});
}
}
return {
value: this._flags.strip ? undefined : finalValue,
finalValue,
errors: errors.length ? errors : null
};
};
if (this._coerce) {
const coerced = this._coerce.call(this, value, state, options);
if (coerced.errors) {
value = coerced.value;
errors = errors.concat(coerced.errors);
return finish(); // Coerced error always aborts early
}
value = coerced.value;
}
if (this._flags.empty && !this._flags.empty._validate(this._prepareEmptyValue(value), null, internals.defaults).errors) {
value = undefined;
}
// Check presence requirements
const presence = this._flags.presence || options.presence;
if (presence === 'optional') {
if (value === undefined) {
const isDeepDefault = this._flags.hasOwnProperty('default') && this._flags.default === undefined;
if (isDeepDefault && this._type === 'object') {
value = {};
}
else {
return finish();
}
}
}
else if (presence === 'required' &&
value === undefined) {
errors.push(this.createError('any.required', null, state, options));
return finish();
}
else if (presence === 'forbidden') {
if (value === undefined) {
return finish();
}
errors.push(this.createError('any.unknown', null, state, options));
return finish();
}
// Check allowed and denied values using the original value
if (this._valids.has(value, state, options, this._flags.insensitive)) {
return finish();
}
if (this._invalids.has(value, state, options, this._flags.insensitive)) {
errors.push(this.createError(value === '' ? 'any.empty' : 'any.invalid', { value, invalids: this._invalids.values({ stripUndefined: true }) }, state, options));
if (options.abortEarly ||
value === undefined) { // No reason to keep validating missing value
return finish();
}
}
// Convert value and validate type
if (this._base) {
const base = this._base.call(this, value, state, options);
if (base.errors) {
value = base.value;
errors = errors.concat(base.errors);
return finish(); // Base error always aborts early
}
if (base.value !== value) {
value = base.value;
// Check allowed and denied values using the converted value
if (this._valids.has(value, state, options, this._flags.insensitive)) {
return finish();
}
if (this._invalids.has(value, state, options, this._flags.insensitive)) {
errors.push(this.createError(value === '' ? 'any.empty' : 'any.invalid', { value, invalids: this._invalids.values({ stripUndefined: true }) }, state, options));
if (options.abortEarly) {
return finish();
}
}
}
}
// Required values did not match
if (this._flags.allowOnly) {
errors.push(this.createError('any.allowOnly', { value, valids: this._valids.values({ stripUndefined: true }) }, state, options));
if (options.abortEarly) {
return finish();
}
}
// Validate tests
for (let i = 0; i < this._tests.length; ++i) {
const test = this._tests[i];
const ret = test.func.call(this, value, state, options);
if (ret instanceof Errors.Err) {
errors.push(ret);
if (options.abortEarly) {
return finish();
}
}
else {
value = ret;
}
}
return finish();
}
_validateWithOptions(value, options, callback) {
if (options) {
this.checkOptions(options);
}
const settings = Settings.concat(internals.defaults, options);
const result = this._validate(value, null, settings);
const errors = Errors.process(result.errors, value);
if (callback) {
return callback(errors, result.value);
}
return {
error: errors,
value: result.value,
then(resolve, reject) {
if (errors) {
return Promise.reject(errors).catch(reject);
}
return Promise.resolve(result.value).then(resolve);
},
catch(reject) {
if (errors) {
return Promise.reject(errors).catch(reject);
}
return Promise.resolve(result.value);
}
};
}
validate(value, options, callback) {
if (typeof options === 'function') {
return this._validateWithOptions(value, null, options);
}
return this._validateWithOptions(value, options, callback);
}
describe() {
const description = {
type: this._type
};
const flags = Object.keys(this._flags);
if (flags.length) {
if (['empty', 'default', 'lazy', 'label'].some((flag) => this._flags.hasOwnProperty(flag))) {
description.flags = {};
for (let i = 0; i < flags.length; ++i) {
const flag = flags[i];
if (flag === 'empty') {
description.flags[flag] = this._flags[flag].describe();
}
else if (flag === 'default') {
if (Ref.isRef(this._flags[flag])) {
description.flags[flag] = this._flags[flag].toString();
}
else if (typeof this._flags[flag] === 'function') {
description.flags[flag] = {
description: this._flags[flag].description,
function : this._flags[flag]
};
}
else {
description.flags[flag] = this._flags[flag];
}
}
else if (flag === 'lazy' || flag === 'label') {
// We don't want it in the description
}
else {
description.flags[flag] = this._flags[flag];
}
}
}
else {
description.flags = this._flags;
}
}
if (this._settings) {
description.options = Hoek.clone(this._settings);
}
if (this._baseType) {
description.base = this._baseType.describe();
}
if (this._description) {
description.description = this._description;
}
if (this._notes.length) {
description.notes = this._notes;
}
if (this._tags.length) {
description.tags = this._tags;
}
if (this._meta.length) {
description.meta = this._meta;
}
if (this._examples.length) {
description.examples = this._examples;
}
if (this._unit) {
description.unit = this._unit;
}
const valids = this._valids.values();
if (valids.length) {
description.valids = valids.map((v) => {
return Ref.isRef(v) ? v.toString() : v;
});
}
const invalids = this._invalids.values();
if (invalids.length) {
description.invalids = invalids.map((v) => {
return Ref.isRef(v) ? v.toString() : v;
});
}
description.rules = [];
for (let i = 0; i < this._tests.length; ++i) {
const validator = this._tests[i];
const item = { name: validator.name };
if (validator.arg !== void 0) {
item.arg = Ref.isRef(validator.arg) ? validator.arg.toString() : validator.arg;
}
const options = validator.options;
if (options) {
if (options.hasRef) {
item.arg = {};
const keys = Object.keys(validator.arg);
for (let j = 0; j < keys.length; ++j) {
const key = keys[j];
const value = validator.arg[key];
item.arg[key] = Ref.isRef(value) ? value.toString() : value;
}
}
if (typeof options.description === 'string') {
item.description = options.description;
}
else if (typeof options.description === 'function') {
item.description = options.description(item.arg);
}
}
description.rules.push(item);
}
if (!description.rules.length) {
delete description.rules;
}
const label = this._getLabel();
if (label) {
description.label = label;
}
return description;
}
label(name) {
Hoek.assert(name && typeof name === 'string', 'Label name must be a non-empty string');
const obj = this.clone();
obj._flags.label = name;
return obj;
}
_getLabel(def) {
return this._flags.label || def;
}
};
internals.Any.prototype.isImmutable = true; // Prevents Hoek from deep cloning schema objects
// Aliases
internals.Any.prototype.only = internals.Any.prototype.equal = internals.Any.prototype.valid;
internals.Any.prototype.disallow = internals.Any.prototype.not = internals.Any.prototype.invalid;
internals.Any.prototype.exist = internals.Any.prototype.required;
internals._try = function (fn, args) {
let err;
let result;
try {
result = fn.apply(null, args);
}
catch (e) {
err = e;
}
return {
value: result,
error: err
};
};

35
node_modules/joi/lib/types/any/settings.js generated vendored Normal file
View File

@ -0,0 +1,35 @@
'use strict';
// Load modules
const Hoek = require('hoek');
// Declare internals
const internals = {};
exports.concat = function (target, source) {
if (!source) {
return target;
}
const obj = Object.assign({}, target);
const sKeys = Object.keys(source);
for (let i = 0; i < sKeys.length; ++i) {
const key = sKeys[i];
if (key !== 'language' ||
!obj.hasOwnProperty(key)) {
obj[key] = source[key];
}
else {
obj[key] = Hoek.applyToDefaults(obj[key], source[key]);
}
}
return obj;
};

669
node_modules/joi/lib/types/array/index.js generated vendored Normal file
View File

@ -0,0 +1,669 @@
'use strict';
// Load modules
const Any = require('../any');
const Cast = require('../../cast');
const Ref = require('../../ref');
const Hoek = require('hoek');
// Declare internals
const internals = {};
internals.fastSplice = function (arr, i) {
let pos = i;
while (pos < arr.length) {
arr[pos++] = arr[pos];
}
--arr.length;
};
internals.Array = class extends Any {
constructor() {
super();
this._type = 'array';
this._inner.items = [];
this._inner.ordereds = [];
this._inner.inclusions = [];
this._inner.exclusions = [];
this._inner.requireds = [];
this._flags.sparse = false;
}
_base(value, state, options) {
const result = {
value
};
if (typeof value === 'string' &&
options.convert) {
internals.safeParse(value, result);
}
let isArray = Array.isArray(result.value);
const wasArray = isArray;
if (options.convert && this._flags.single && !isArray) {
result.value = [result.value];
isArray = true;
}
if (!isArray) {
result.errors = this.createError('array.base', null, state, options);
return result;
}
if (this._inner.inclusions.length ||
this._inner.exclusions.length ||
this._inner.requireds.length ||
this._inner.ordereds.length ||
!this._flags.sparse) {
// Clone the array so that we don't modify the original
if (wasArray) {
result.value = result.value.slice(0);
}
result.errors = this._checkItems.call(this, result.value, wasArray, state, options);
if (result.errors && wasArray && options.convert && this._flags.single) {
// Attempt a 2nd pass by putting the array inside one.
const previousErrors = result.errors;
result.value = [result.value];
result.errors = this._checkItems.call(this, result.value, wasArray, state, options);
if (result.errors) {
// Restore previous errors and value since this didn't validate either.
result.errors = previousErrors;
result.value = result.value[0];
}
}
}
return result;
}
_checkItems(items, wasArray, state, options) {
const errors = [];
let errored;
const requireds = this._inner.requireds.slice();
const ordereds = this._inner.ordereds.slice();
const inclusions = this._inner.inclusions.concat(requireds);
let il = items.length;
for (let i = 0; i < il; ++i) {
errored = false;
const item = items[i];
let isValid = false;
const key = wasArray ? i : state.key;
const path = wasArray ? state.path.concat(i) : state.path;
const localState = { key, path, parent: state.parent, reference: state.reference };
let res;
// Sparse
if (!this._flags.sparse && item === undefined) {
errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
if (options.abortEarly) {
return errors;
}
ordereds.shift();
continue;
}
// Exclusions
for (let j = 0; j < this._inner.exclusions.length; ++j) {
res = this._inner.exclusions[j]._validate(item, localState, {}); // Not passing options to use defaults
if (!res.errors) {
errors.push(this.createError(wasArray ? 'array.excludes' : 'array.excludesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options));
errored = true;
if (options.abortEarly) {
return errors;
}
ordereds.shift();
break;
}
}
if (errored) {
continue;
}
// Ordered
if (this._inner.ordereds.length) {
if (ordereds.length > 0) {
const ordered = ordereds.shift();
res = ordered._validate(item, localState, options);
if (!res.errors) {
if (ordered._flags.strip) {
internals.fastSplice(items, i);
--i;
--il;
}
else if (!this._flags.sparse && res.value === undefined) {
errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
if (options.abortEarly) {
return errors;
}
continue;
}
else {
items[i] = res.value;
}
}
else {
errors.push(this.createError('array.ordered', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options));
if (options.abortEarly) {
return errors;
}
}
continue;
}
else if (!this._inner.items.length) {
errors.push(this.createError('array.orderedLength', { pos: i, limit: this._inner.ordereds.length }, { key: state.key, path: localState.path }, options));
if (options.abortEarly) {
return errors;
}
continue;
}
}
// Requireds
const requiredChecks = [];
let jl = requireds.length;
for (let j = 0; j < jl; ++j) {
res = requiredChecks[j] = requireds[j]._validate(item, localState, options);
if (!res.errors) {
items[i] = res.value;
isValid = true;
internals.fastSplice(requireds, j);
--j;
--jl;
if (!this._flags.sparse && res.value === undefined) {
errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
if (options.abortEarly) {
return errors;
}
}
break;
}
}
if (isValid) {
continue;
}
// Inclusions
const stripUnknown = options.stripUnknown
? (options.stripUnknown === true ? true : !!options.stripUnknown.arrays)
: false;
jl = inclusions.length;
for (let j = 0; j < jl; ++j) {
const inclusion = inclusions[j];
// Avoid re-running requireds that already didn't match in the previous loop
const previousCheck = requireds.indexOf(inclusion);
if (previousCheck !== -1) {
res = requiredChecks[previousCheck];
}
else {
res = inclusion._validate(item, localState, options);
if (!res.errors) {
if (inclusion._flags.strip) {
internals.fastSplice(items, i);
--i;
--il;
}
else if (!this._flags.sparse && res.value === undefined) {
errors.push(this.createError('array.sparse', null, { key: state.key, path: localState.path, pos: i }, options));
errored = true;
}
else {
items[i] = res.value;
}
isValid = true;
break;
}
}
// Return the actual error if only one inclusion defined
if (jl === 1) {
if (stripUnknown) {
internals.fastSplice(items, i);
--i;
--il;
isValid = true;
break;
}
errors.push(this.createError(wasArray ? 'array.includesOne' : 'array.includesOneSingle', { pos: i, reason: res.errors, value: item }, { key: state.key, path: localState.path }, options));
errored = true;
if (options.abortEarly) {
return errors;
}
break;
}
}
if (errored) {
continue;
}
if (this._inner.inclusions.length && !isValid) {
if (stripUnknown) {
internals.fastSplice(items, i);
--i;
--il;
continue;
}
errors.push(this.createError(wasArray ? 'array.includes' : 'array.includesSingle', { pos: i, value: item }, { key: state.key, path: localState.path }, options));
if (options.abortEarly) {
return errors;
}
}
}
if (requireds.length) {
this._fillMissedErrors.call(this, errors, requireds, state, options);
}
if (ordereds.length) {
this._fillOrderedErrors.call(this, errors, ordereds, state, options);
}
return errors.length ? errors : null;
}
describe() {
const description = super.describe();
if (this._inner.ordereds.length) {
description.orderedItems = [];
for (let i = 0; i < this._inner.ordereds.length; ++i) {
description.orderedItems.push(this._inner.ordereds[i].describe());
}
}
if (this._inner.items.length) {
description.items = [];
for (let i = 0; i < this._inner.items.length; ++i) {
description.items.push(this._inner.items[i].describe());
}
}
return description;
}
items(...schemas) {
const obj = this.clone();
Hoek.flatten(schemas).forEach((type, index) => {
try {
type = Cast.schema(this._currentJoi, type);
}
catch (castErr) {
if (castErr.hasOwnProperty('path')) {
castErr.path = index + '.' + castErr.path;
}
else {
castErr.path = index;
}
castErr.message = castErr.message + '(' + castErr.path + ')';
throw castErr;
}
obj._inner.items.push(type);
if (type._flags.presence === 'required') {
obj._inner.requireds.push(type);
}
else if (type._flags.presence === 'forbidden') {
obj._inner.exclusions.push(type.optional());
}
else {
obj._inner.inclusions.push(type);
}
});
return obj;
}
ordered(...schemas) {
const obj = this.clone();
Hoek.flatten(schemas).forEach((type, index) => {
try {
type = Cast.schema(this._currentJoi, type);
}
catch (castErr) {
if (castErr.hasOwnProperty('path')) {
castErr.path = index + '.' + castErr.path;
}
else {
castErr.path = index;
}
castErr.message = castErr.message + '(' + castErr.path + ')';
throw castErr;
}
obj._inner.ordereds.push(type);
});
return obj;
}
min(limit) {
const isRef = Ref.isRef(limit);
Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference');
return this._test('min', limit, function (value, state, options) {
let compareTo;
if (isRef) {
compareTo = limit(state.reference || state.parent, options);
if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) {
return this.createError('array.ref', { ref: limit.key }, state, options);
}
}
else {
compareTo = limit;
}
if (value.length >= compareTo) {
return value;
}
return this.createError('array.min', { limit, value }, state, options);
});
}
max(limit) {
const isRef = Ref.isRef(limit);
Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference');
return this._test('max', limit, function (value, state, options) {
let compareTo;
if (isRef) {
compareTo = limit(state.reference || state.parent, options);
if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) {
return this.createError('array.ref', { ref: limit.key }, state, options);
}
}
else {
compareTo = limit;
}
if (value.length <= compareTo) {
return value;
}
return this.createError('array.max', { limit, value }, state, options);
});
}
length(limit) {
const isRef = Ref.isRef(limit);
Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference');
return this._test('length', limit, function (value, state, options) {
let compareTo;
if (isRef) {
compareTo = limit(state.reference || state.parent, options);
if (!(Number.isSafeInteger(compareTo) && compareTo >= 0)) {
return this.createError('array.ref', { ref: limit.key }, state, options);
}
}
else {
compareTo = limit;
}
if (value.length === compareTo) {
return value;
}
return this.createError('array.length', { limit, value }, state, options);
});
}
unique(comparator, configs) {
Hoek.assert(comparator === undefined ||
typeof comparator === 'function' ||
typeof comparator === 'string', 'comparator must be a function or a string');
Hoek.assert(configs === undefined ||
typeof configs === 'object', 'configs must be an object');
const settings = {
ignoreUndefined: (configs && configs.ignoreUndefined) || false
};
if (typeof comparator === 'string') {
settings.path = comparator;
}
else if (typeof comparator === 'function') {
settings.comparator = comparator;
}
return this._test('unique', settings, function (value, state, options) {
const found = {
string: Object.create(null),
number: Object.create(null),
undefined: Object.create(null),
boolean: Object.create(null),
object: new Map(),
function: new Map(),
custom: new Map()
};
const compare = settings.comparator || Hoek.deepEqual;
const ignoreUndefined = settings.ignoreUndefined;
for (let i = 0; i < value.length; ++i) {
const item = settings.path ? Hoek.reach(value[i], settings.path) : value[i];
const records = settings.comparator ? found.custom : found[typeof item];
// All available types are supported, so it's not possible to reach 100% coverage without ignoring this line.
// I still want to keep the test for future js versions with new types (eg. Symbol).
if (/* $lab:coverage:off$ */ records /* $lab:coverage:on$ */) {
if (records instanceof Map) {
const entries = records.entries();
let current;
while (!(current = entries.next()).done) {
if (compare(current.value[0], item)) {
const localState = {
key: state.key,
path: state.path.concat(i),
parent: state.parent,
reference: state.reference
};
const context = {
pos: i,
value: value[i],
dupePos: current.value[1],
dupeValue: value[current.value[1]]
};
if (settings.path) {
context.path = settings.path;
}
return this.createError('array.unique', context, localState, options);
}
}
records.set(item, i);
}
else {
if ((!ignoreUndefined || item !== undefined) && records[item] !== undefined) {
const localState = {
key: state.key,
path: state.path.concat(i),
parent: state.parent,
reference: state.reference
};
const context = {
pos: i,
value: value[i],
dupePos: records[item],
dupeValue: value[records[item]]
};
if (settings.path) {
context.path = settings.path;
}
return this.createError('array.unique', context, localState, options);
}
records[item] = i;
}
}
}
return value;
});
}
sparse(enabled) {
const value = enabled === undefined ? true : !!enabled;
if (this._flags.sparse === value) {
return this;
}
const obj = this.clone();
obj._flags.sparse = value;
return obj;
}
single(enabled) {
const value = enabled === undefined ? true : !!enabled;
if (this._flags.single === value) {
return this;
}
const obj = this.clone();
obj._flags.single = value;
return obj;
}
_fillMissedErrors(errors, requireds, state, options) {
const knownMisses = [];
let unknownMisses = 0;
for (let i = 0; i < requireds.length; ++i) {
const label = requireds[i]._getLabel();
if (label) {
knownMisses.push(label);
}
else {
++unknownMisses;
}
}
if (knownMisses.length) {
if (unknownMisses) {
errors.push(this.createError('array.includesRequiredBoth', { knownMisses, unknownMisses }, { key: state.key, path: state.path }, options));
}
else {
errors.push(this.createError('array.includesRequiredKnowns', { knownMisses }, { key: state.key, path: state.path }, options));
}
}
else {
errors.push(this.createError('array.includesRequiredUnknowns', { unknownMisses }, { key: state.key, path: state.path }, options));
}
}
_fillOrderedErrors(errors, ordereds, state, options) {
const requiredOrdereds = [];
for (let i = 0; i < ordereds.length; ++i) {
const presence = Hoek.reach(ordereds[i], '_flags.presence');
if (presence === 'required') {
requiredOrdereds.push(ordereds[i]);
}
}
if (requiredOrdereds.length) {
this._fillMissedErrors.call(this, errors, requiredOrdereds, state, options);
}
}
};
internals.safeParse = function (value, result) {
try {
const converted = JSON.parse(value);
if (Array.isArray(converted)) {
result.value = converted;
}
}
catch (e) { }
};
module.exports = new internals.Array();

100
node_modules/joi/lib/types/binary/index.js generated vendored Normal file
View File

@ -0,0 +1,100 @@
'use strict';
// Load modules
const Any = require('../any');
const Hoek = require('hoek');
// Declare internals
const internals = {};
internals.Binary = class extends Any {
constructor() {
super();
this._type = 'binary';
}
_base(value, state, options) {
const result = {
value
};
if (typeof value === 'string' &&
options.convert) {
try {
result.value = Buffer.from(value, this._flags.encoding);
}
catch (e) {
}
}
result.errors = Buffer.isBuffer(result.value) ? null : this.createError('binary.base', null, state, options);
return result;
}
encoding(encoding) {
Hoek.assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding);
if (this._flags.encoding === encoding) {
return this;
}
const obj = this.clone();
obj._flags.encoding = encoding;
return obj;
}
min(limit) {
Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('min', limit, function (value, state, options) {
if (value.length >= limit) {
return value;
}
return this.createError('binary.min', { limit, value }, state, options);
});
}
max(limit) {
Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('max', limit, function (value, state, options) {
if (value.length <= limit) {
return value;
}
return this.createError('binary.max', { limit, value }, state, options);
});
}
length(limit) {
Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('length', limit, function (value, state, options) {
if (value.length === limit) {
return value;
}
return this.createError('binary.length', { limit, value }, state, options);
});
}
};
module.exports = new internals.Binary();

98
node_modules/joi/lib/types/boolean/index.js generated vendored Normal file
View File

@ -0,0 +1,98 @@
'use strict';
// Load modules
const Any = require('../any');
const Hoek = require('hoek');
// Declare internals
const internals = {
Set: require('../../set')
};
internals.Boolean = class extends Any {
constructor() {
super();
this._type = 'boolean';
this._flags.insensitive = true;
this._inner.truthySet = new internals.Set();
this._inner.falsySet = new internals.Set();
}
_base(value, state, options) {
const result = {
value
};
if (typeof value === 'string' &&
options.convert) {
const normalized = this._flags.insensitive ? value.toLowerCase() : value;
result.value = (normalized === 'true' ? true
: (normalized === 'false' ? false : value));
}
if (typeof result.value !== 'boolean') {
result.value = (this._inner.truthySet.has(value, null, null, this._flags.insensitive) ? true
: (this._inner.falsySet.has(value, null, null, this._flags.insensitive) ? false : value));
}
result.errors = (typeof result.value === 'boolean') ? null : this.createError('boolean.base', null, state, options);
return result;
}
truthy(...values) {
const obj = this.clone();
values = Hoek.flatten(values);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
Hoek.assert(value !== undefined, 'Cannot call truthy with undefined');
obj._inner.truthySet.add(value);
}
return obj;
}
falsy(...values) {
const obj = this.clone();
values = Hoek.flatten(values);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
Hoek.assert(value !== undefined, 'Cannot call falsy with undefined');
obj._inner.falsySet.add(value);
}
return obj;
}
insensitive(enabled) {
const insensitive = enabled === undefined ? true : !!enabled;
if (this._flags.insensitive === insensitive) {
return this;
}
const obj = this.clone();
obj._flags.insensitive = insensitive;
return obj;
}
describe() {
const description = super.describe();
description.truthy = [true].concat(this._inner.truthySet.values());
description.falsy = [false].concat(this._inner.falsySet.values());
return description;
}
};
module.exports = new internals.Boolean();

179
node_modules/joi/lib/types/date/index.js generated vendored Normal file
View File

@ -0,0 +1,179 @@
'use strict';
// Load modules
const Any = require('../any');
const Ref = require('../../ref');
const Hoek = require('hoek');
// Declare internals
const internals = {};
internals.isoDate = /^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/;
internals.invalidDate = new Date('');
internals.isIsoDate = (() => {
const isoString = internals.isoDate.toString();
return (date) => {
return date && (date.toString() === isoString);
};
})();
internals.Date = class extends Any {
constructor() {
super();
this._type = 'date';
}
_base(value, state, options) {
const result = {
value: (options.convert && internals.Date.toDate(value, this._flags.format, this._flags.timestamp, this._flags.multiplier)) || value
};
if (result.value instanceof Date && !isNaN(result.value.getTime())) {
result.errors = null;
}
else if (!options.convert) {
result.errors = this.createError('date.strict', null, state, options);
}
else {
let type;
if (internals.isIsoDate(this._flags.format)) {
type = 'isoDate';
}
else if (this._flags.timestamp) {
type = `timestamp.${this._flags.timestamp}`;
}
else {
type = 'base';
}
result.errors = this.createError(`date.${type}`, null, state, options);
}
return result;
}
static toDate(value, format, timestamp, multiplier) {
if (value instanceof Date) {
return value;
}
if (typeof value === 'string' ||
(typeof value === 'number' && !isNaN(value) && isFinite(value))) {
if (typeof value === 'string' &&
/^[+-]?\d+(\.\d+)?$/.test(value)) {
value = parseFloat(value);
}
let date;
if (format && internals.isIsoDate(format)) {
date = format.test(value) ? new Date(value) : internals.invalidDate;
}
else if (timestamp && multiplier) {
date = /^\s*$/.test(value) ? internals.invalidDate : new Date(value * multiplier);
}
else {
date = new Date(value);
}
if (!isNaN(date.getTime())) {
return date;
}
}
return null;
}
iso() {
if (this._flags.format === internals.isoDate) {
return this;
}
const obj = this.clone();
obj._flags.format = internals.isoDate;
return obj;
}
timestamp(type = 'javascript') {
const allowed = ['javascript', 'unix'];
Hoek.assert(allowed.includes(type), '"type" must be one of "' + allowed.join('", "') + '"');
if (this._flags.timestamp === type) {
return this;
}
const obj = this.clone();
obj._flags.timestamp = type;
obj._flags.multiplier = type === 'unix' ? 1000 : 1;
return obj;
}
_isIsoDate(value) {
return internals.isoDate.test(value);
}
};
internals.compare = function (type, compare) {
return function (date) {
const isNow = date === 'now';
const isRef = Ref.isRef(date);
if (!isNow && !isRef) {
date = internals.Date.toDate(date);
}
Hoek.assert(date, 'Invalid date format');
return this._test(type, date, function (value, state, options) {
let compareTo;
if (isNow) {
compareTo = Date.now();
}
else if (isRef) {
compareTo = internals.Date.toDate(date(state.reference || state.parent, options));
if (!compareTo) {
return this.createError('date.ref', { ref: date.key }, state, options);
}
compareTo = compareTo.getTime();
}
else {
compareTo = date.getTime();
}
if (compare(value.getTime(), compareTo)) {
return value;
}
return this.createError('date.' + type, { limit: new Date(compareTo) }, state, options);
});
};
};
internals.Date.prototype.min = internals.compare('min', (value, date) => value >= date);
internals.Date.prototype.max = internals.compare('max', (value, date) => value <= date);
internals.Date.prototype.greater = internals.compare('greater', (value, date) => value > date);
internals.Date.prototype.less = internals.compare('less', (value, date) => value < date);
module.exports = new internals.Date();

90
node_modules/joi/lib/types/func/index.js generated vendored Normal file
View File

@ -0,0 +1,90 @@
'use strict';
// Load modules
const Hoek = require('hoek');
const ObjectType = require('../object');
const Ref = require('../../ref');
// Declare internals
const internals = {};
internals.Func = class extends ObjectType.constructor {
constructor() {
super();
this._flags.func = true;
}
arity(n) {
Hoek.assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer');
return this._test('arity', n, function (value, state, options) {
if (value.length === n) {
return value;
}
return this.createError('function.arity', { n }, state, options);
});
}
minArity(n) {
Hoek.assert(Number.isSafeInteger(n) && n > 0, 'n must be a strict positive integer');
return this._test('minArity', n, function (value, state, options) {
if (value.length >= n) {
return value;
}
return this.createError('function.minArity', { n }, state, options);
});
}
maxArity(n) {
Hoek.assert(Number.isSafeInteger(n) && n >= 0, 'n must be a positive integer');
return this._test('maxArity', n, function (value, state, options) {
if (value.length <= n) {
return value;
}
return this.createError('function.maxArity', { n }, state, options);
});
}
ref() {
return this._test('ref', null, function (value, state, options) {
if (Ref.isRef(value)) {
return value;
}
return this.createError('function.ref', null, state, options);
});
}
class() {
return this._test('class', null, function (value, state, options) {
if ((/^\s*class\s/).test(value.toString())) {
return value;
}
return this.createError('function.class', null, state, options);
});
}
};
module.exports = new internals.Func();

53
node_modules/joi/lib/types/lazy/index.js generated vendored Normal file
View File

@ -0,0 +1,53 @@
'use strict';
// Load modules
const Any = require('../any');
const Hoek = require('hoek');
// Declare internals
const internals = {};
internals.Lazy = class extends Any {
constructor() {
super();
this._type = 'lazy';
}
_base(value, state, options) {
const result = { value };
const lazy = this._flags.lazy;
if (!lazy) {
result.errors = this.createError('lazy.base', null, state, options);
return result;
}
const schema = lazy();
if (!(schema instanceof Any)) {
result.errors = this.createError('lazy.schema', null, state, options);
return result;
}
return schema._validate(value, state, options);
}
set(fn) {
Hoek.assert(typeof fn === 'function', 'You must provide a function as first argument');
const obj = this.clone();
obj._flags.lazy = fn;
return obj;
}
};
module.exports = new internals.Lazy();

185
node_modules/joi/lib/types/number/index.js generated vendored Normal file
View File

@ -0,0 +1,185 @@
'use strict';
// Load modules
const Any = require('../any');
const Ref = require('../../ref');
const Hoek = require('hoek');
// Declare internals
const internals = {
precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/
};
internals.Number = class extends Any {
constructor() {
super();
this._type = 'number';
this._invalids.add(Infinity);
this._invalids.add(-Infinity);
}
_base(value, state, options) {
const result = {
errors: null,
value
};
if (typeof value === 'string' &&
options.convert) {
const number = parseFloat(value);
result.value = (isNaN(number) || !isFinite(value)) ? NaN : number;
}
const isNumber = typeof result.value === 'number' && !isNaN(result.value);
if (options.convert && 'precision' in this._flags && isNumber) {
// This is conceptually equivalent to using toFixed but it should be much faster
const precision = Math.pow(10, this._flags.precision);
result.value = Math.round(result.value * precision) / precision;
}
result.errors = isNumber ? null : this.createError('number.base', { value }, state, options);
return result;
}
multiple(base) {
const isRef = Ref.isRef(base);
if (!isRef) {
Hoek.assert(typeof base === 'number' && isFinite(base), 'multiple must be a number');
Hoek.assert(base > 0, 'multiple must be greater than 0');
}
return this._test('multiple', base, function (value, state, options) {
const divisor = isRef ? base(state.reference || state.parent, options) : base;
if (isRef && (typeof divisor !== 'number' || !isFinite(divisor))) {
return this.createError('number.ref', { ref: base.key }, state, options);
}
if (value % divisor === 0) {
return value;
}
return this.createError('number.multiple', { multiple: base, value }, state, options);
});
}
integer() {
return this._test('integer', undefined, function (value, state, options) {
return Number.isSafeInteger(value) ? value : this.createError('number.integer', { value }, state, options);
});
}
negative() {
return this._test('negative', undefined, function (value, state, options) {
if (value < 0) {
return value;
}
return this.createError('number.negative', { value }, state, options);
});
}
positive() {
return this._test('positive', undefined, function (value, state, options) {
if (value > 0) {
return value;
}
return this.createError('number.positive', { value }, state, options);
});
}
precision(limit) {
Hoek.assert(Number.isSafeInteger(limit), 'limit must be an integer');
Hoek.assert(!('precision' in this._flags), 'precision already set');
const obj = this._test('precision', limit, function (value, state, options) {
const places = value.toString().match(internals.precisionRx);
const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0);
if (decimals <= limit) {
return value;
}
return this.createError('number.precision', { limit, value }, state, options);
});
obj._flags.precision = limit;
return obj;
}
port() {
return this._test('port', undefined, function (value, state, options) {
if (!Number.isSafeInteger(value) || value < 0 || value > 65535) {
return this.createError('number.port', { value }, state, options);
}
return value;
});
}
};
internals.compare = function (type, compare) {
return function (limit) {
const isRef = Ref.isRef(limit);
const isNumber = typeof limit === 'number' && !isNaN(limit);
Hoek.assert(isNumber || isRef, 'limit must be a number or reference');
return this._test(type, limit, function (value, state, options) {
let compareTo;
if (isRef) {
compareTo = limit(state.reference || state.parent, options);
if (!(typeof compareTo === 'number' && !isNaN(compareTo))) {
return this.createError('number.ref', { ref: limit.key }, state, options);
}
}
else {
compareTo = limit;
}
if (compare(value, compareTo)) {
return value;
}
return this.createError('number.' + type, { limit: compareTo, value }, state, options);
});
};
};
internals.Number.prototype.min = internals.compare('min', (value, limit) => value >= limit);
internals.Number.prototype.max = internals.compare('max', (value, limit) => value <= limit);
internals.Number.prototype.greater = internals.compare('greater', (value, limit) => value > limit);
internals.Number.prototype.less = internals.compare('less', (value, limit) => value < limit);
module.exports = new internals.Number();

928
node_modules/joi/lib/types/object/index.js generated vendored Normal file
View File

@ -0,0 +1,928 @@
'use strict';
// Load modules
const Hoek = require('hoek');
const Topo = require('topo');
const Any = require('../any');
const Errors = require('../../errors');
const Cast = require('../../cast');
// Declare internals
const internals = {};
internals.Object = class extends Any {
constructor() {
super();
this._type = 'object';
this._inner.children = null;
this._inner.renames = [];
this._inner.dependencies = [];
this._inner.patterns = [];
}
_init(...args) {
return args.length ? this.keys(...args) : this;
}
_base(value, state, options) {
let target = value;
const errors = [];
const finish = () => {
return {
value: target,
errors: errors.length ? errors : null
};
};
if (typeof value === 'string' &&
options.convert) {
value = internals.safeParse(value);
}
const type = this._flags.func ? 'function' : 'object';
if (!value ||
typeof value !== type ||
Array.isArray(value)) {
errors.push(this.createError(type + '.base', null, state, options));
return finish();
}
// Skip if there are no other rules to test
if (!this._inner.renames.length &&
!this._inner.dependencies.length &&
!this._inner.children && // null allows any keys
!this._inner.patterns.length) {
target = value;
return finish();
}
// Ensure target is a local copy (parsed) or shallow copy
if (target === value) {
if (type === 'object') {
target = Object.create(Object.getPrototypeOf(value));
}
else {
target = function (...args) {
return value.apply(this, args);
};
target.prototype = Hoek.clone(value.prototype);
}
const valueKeys = Object.keys(value);
for (let i = 0; i < valueKeys.length; ++i) {
target[valueKeys[i]] = value[valueKeys[i]];
}
}
else {
target = value;
}
// Rename keys
const renamed = {};
for (let i = 0; i < this._inner.renames.length; ++i) {
const rename = this._inner.renames[i];
if (rename.isRegExp) {
const targetKeys = Object.keys(target);
const matchedTargetKeys = [];
for (let j = 0; j < targetKeys.length; ++j) {
if (rename.from.test(targetKeys[j])) {
matchedTargetKeys.push(targetKeys[j]);
}
}
const allUndefined = matchedTargetKeys.every((key) => target[key] === undefined);
if (rename.options.ignoreUndefined && allUndefined) {
continue;
}
if (!rename.options.multiple &&
renamed[rename.to]) {
errors.push(this.createError('object.rename.regex.multiple', { from: matchedTargetKeys, to: rename.to }, state, options));
if (options.abortEarly) {
return finish();
}
}
if (Object.prototype.hasOwnProperty.call(target, rename.to) &&
!rename.options.override &&
!renamed[rename.to]) {
errors.push(this.createError('object.rename.regex.override', { from: matchedTargetKeys, to: rename.to }, state, options));
if (options.abortEarly) {
return finish();
}
}
if (allUndefined) {
delete target[rename.to];
}
else {
target[rename.to] = target[matchedTargetKeys[matchedTargetKeys.length - 1]];
}
renamed[rename.to] = true;
if (!rename.options.alias) {
for (let j = 0; j < matchedTargetKeys.length; ++j) {
delete target[matchedTargetKeys[j]];
}
}
}
else {
if (rename.options.ignoreUndefined && target[rename.from] === undefined) {
continue;
}
if (!rename.options.multiple &&
renamed[rename.to]) {
errors.push(this.createError('object.rename.multiple', { from: rename.from, to: rename.to }, state, options));
if (options.abortEarly) {
return finish();
}
}
if (Object.prototype.hasOwnProperty.call(target, rename.to) &&
!rename.options.override &&
!renamed[rename.to]) {
errors.push(this.createError('object.rename.override', { from: rename.from, to: rename.to }, state, options));
if (options.abortEarly) {
return finish();
}
}
if (target[rename.from] === undefined) {
delete target[rename.to];
}
else {
target[rename.to] = target[rename.from];
}
renamed[rename.to] = true;
if (!rename.options.alias) {
delete target[rename.from];
}
}
}
// Validate schema
if (!this._inner.children && // null allows any keys
!this._inner.patterns.length &&
!this._inner.dependencies.length) {
return finish();
}
const unprocessed = new Set(Object.keys(target));
if (this._inner.children) {
const stripProps = [];
for (let i = 0; i < this._inner.children.length; ++i) {
const child = this._inner.children[i];
const key = child.key;
const item = target[key];
unprocessed.delete(key);
const localState = { key, path: state.path.concat(key), parent: target, reference: state.reference };
const result = child.schema._validate(item, localState, options);
if (result.errors) {
errors.push(this.createError('object.child', { key, child: child.schema._getLabel(key), reason: result.errors }, localState, options));
if (options.abortEarly) {
return finish();
}
}
else {
if (child.schema._flags.strip || (result.value === undefined && result.value !== item)) {
stripProps.push(key);
target[key] = result.finalValue;
}
else if (result.value !== undefined) {
target[key] = result.value;
}
}
}
for (let i = 0; i < stripProps.length; ++i) {
delete target[stripProps[i]];
}
}
// Unknown keys
if (unprocessed.size && this._inner.patterns.length) {
for (const key of unprocessed) {
const localState = {
key,
path: state.path.concat(key),
parent: target,
reference: state.reference
};
const item = target[key];
for (let i = 0; i < this._inner.patterns.length; ++i) {
const pattern = this._inner.patterns[i];
if (pattern.regex ?
pattern.regex.test(key) :
!pattern.schema.validate(key).error) {
unprocessed.delete(key);
const result = pattern.rule._validate(item, localState, options);
if (result.errors) {
errors.push(this.createError('object.child', {
key,
child: pattern.rule._getLabel(key),
reason: result.errors
}, localState, options));
if (options.abortEarly) {
return finish();
}
}
target[key] = result.value;
}
}
}
}
if (unprocessed.size && (this._inner.children || this._inner.patterns.length)) {
if ((options.stripUnknown && this._flags.allowUnknown !== true) ||
options.skipFunctions) {
const stripUnknown = options.stripUnknown
? (options.stripUnknown === true ? true : !!options.stripUnknown.objects)
: false;
for (const key of unprocessed) {
if (stripUnknown) {
delete target[key];
unprocessed.delete(key);
}
else if (typeof target[key] === 'function') {
unprocessed.delete(key);
}
}
}
if ((this._flags.allowUnknown !== undefined ? !this._flags.allowUnknown : !options.allowUnknown)) {
for (const unprocessedKey of unprocessed) {
errors.push(this.createError('object.allowUnknown', { child: unprocessedKey }, {
key: unprocessedKey,
path: state.path.concat(unprocessedKey)
}, options, {}));
}
}
}
// Validate dependencies
for (let i = 0; i < this._inner.dependencies.length; ++i) {
const dep = this._inner.dependencies[i];
const err = internals[dep.type].call(this, dep.key !== null && target[dep.key], dep.peers, target, { key: dep.key, path: dep.key === null ? state.path : state.path.concat(dep.key) }, options);
if (err instanceof Errors.Err) {
errors.push(err);
if (options.abortEarly) {
return finish();
}
}
}
return finish();
}
keys(schema) {
Hoek.assert(schema === null || schema === undefined || typeof schema === 'object', 'Object schema must be a valid object');
Hoek.assert(!schema || !(schema instanceof Any), 'Object schema cannot be a joi schema');
const obj = this.clone();
if (!schema) {
obj._inner.children = null;
return obj;
}
const children = Object.keys(schema);
if (!children.length) {
obj._inner.children = [];
return obj;
}
const topo = new Topo();
if (obj._inner.children) {
for (let i = 0; i < obj._inner.children.length; ++i) {
const child = obj._inner.children[i];
// Only add the key if we are not going to replace it later
if (!children.includes(child.key)) {
topo.add(child, { after: child._refs, group: child.key });
}
}
}
for (let i = 0; i < children.length; ++i) {
const key = children[i];
const child = schema[key];
try {
const cast = Cast.schema(this._currentJoi, child);
topo.add({ key, schema: cast }, { after: cast._refs, group: key });
}
catch (castErr) {
if (castErr.hasOwnProperty('path')) {
castErr.path = key + '.' + castErr.path;
}
else {
castErr.path = key;
}
throw castErr;
}
}
obj._inner.children = topo.nodes;
return obj;
}
append(schema) {
// Skip any changes
if (schema === null || schema === undefined || Object.keys(schema).length === 0) {
return this;
}
return this.keys(schema);
}
unknown(allow) {
const value = allow !== false;
if (this._flags.allowUnknown === value) {
return this;
}
const obj = this.clone();
obj._flags.allowUnknown = value;
return obj;
}
length(limit) {
Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('length', limit, function (value, state, options) {
if (Object.keys(value).length === limit) {
return value;
}
return this.createError('object.length', { limit }, state, options);
});
}
min(limit) {
Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('min', limit, function (value, state, options) {
if (Object.keys(value).length >= limit) {
return value;
}
return this.createError('object.min', { limit }, state, options);
});
}
max(limit) {
Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
return this._test('max', limit, function (value, state, options) {
if (Object.keys(value).length <= limit) {
return value;
}
return this.createError('object.max', { limit }, state, options);
});
}
pattern(pattern, schema) {
const isRegExp = pattern instanceof RegExp;
Hoek.assert(isRegExp || pattern instanceof Any, 'pattern must be a regex or schema');
Hoek.assert(schema !== undefined, 'Invalid rule');
if (isRegExp) {
pattern = new RegExp(pattern.source, pattern.ignoreCase ? 'i' : undefined); // Future version should break this and forbid unsupported regex flags
}
try {
schema = Cast.schema(this._currentJoi, schema);
}
catch (castErr) {
if (castErr.hasOwnProperty('path')) {
castErr.message = castErr.message + '(' + castErr.path + ')';
}
throw castErr;
}
const obj = this.clone();
if (isRegExp) {
obj._inner.patterns.push({ regex: pattern, rule: schema });
}
else {
obj._inner.patterns.push({ schema: pattern, rule: schema });
}
return obj;
}
schema() {
return this._test('schema', null, function (value, state, options) {
if (value instanceof Any) {
return value;
}
return this.createError('object.schema', null, state, options);
});
}
with(key, peers) {
Hoek.assert(arguments.length === 2, 'Invalid number of arguments, expected 2.');
return this._dependency('with', key, peers);
}
without(key, peers) {
Hoek.assert(arguments.length === 2, 'Invalid number of arguments, expected 2.');
return this._dependency('without', key, peers);
}
xor(...peers) {
peers = Hoek.flatten(peers);
return this._dependency('xor', null, peers);
}
or(...peers) {
peers = Hoek.flatten(peers);
return this._dependency('or', null, peers);
}
and(...peers) {
peers = Hoek.flatten(peers);
return this._dependency('and', null, peers);
}
nand(...peers) {
peers = Hoek.flatten(peers);
return this._dependency('nand', null, peers);
}
requiredKeys(...children) {
children = Hoek.flatten(children);
return this.applyFunctionToChildren(children, 'required');
}
optionalKeys(...children) {
children = Hoek.flatten(children);
return this.applyFunctionToChildren(children, 'optional');
}
forbiddenKeys(...children) {
children = Hoek.flatten(children);
return this.applyFunctionToChildren(children, 'forbidden');
}
rename(from, to, options) {
Hoek.assert(typeof from === 'string' || from instanceof RegExp, 'Rename missing the from argument');
Hoek.assert(typeof to === 'string', 'Rename missing the to argument');
Hoek.assert(to !== from, 'Cannot rename key to same name:', from);
for (let i = 0; i < this._inner.renames.length; ++i) {
Hoek.assert(this._inner.renames[i].from !== from, 'Cannot rename the same key multiple times');
}
const obj = this.clone();
obj._inner.renames.push({
from,
to,
options: Hoek.applyToDefaults(internals.renameDefaults, options || {}),
isRegExp: from instanceof RegExp
});
return obj;
}
applyFunctionToChildren(children, fn, args, root) {
children = [].concat(children);
Hoek.assert(children.length > 0, 'expected at least one children');
const groupedChildren = internals.groupChildren(children);
let obj;
if ('' in groupedChildren) {
obj = this[fn].apply(this, args);
delete groupedChildren[''];
}
else {
obj = this.clone();
}
if (obj._inner.children) {
root = root ? (root + '.') : '';
for (let i = 0; i < obj._inner.children.length; ++i) {
const child = obj._inner.children[i];
const group = groupedChildren[child.key];
if (group) {
obj._inner.children[i] = {
key: child.key,
_refs: child._refs,
schema: child.schema.applyFunctionToChildren(group, fn, args, root + child.key)
};
delete groupedChildren[child.key];
}
}
}
const remaining = Object.keys(groupedChildren);
Hoek.assert(remaining.length === 0, 'unknown key(s)', remaining.join(', '));
return obj;
}
_dependency(type, key, peers) {
peers = [].concat(peers);
for (let i = 0; i < peers.length; ++i) {
Hoek.assert(typeof peers[i] === 'string', type, 'peers must be a string or array of strings');
}
const obj = this.clone();
obj._inner.dependencies.push({ type, key, peers });
return obj;
}
describe(shallow) {
const description = super.describe();
if (description.rules) {
for (let i = 0; i < description.rules.length; ++i) {
const rule = description.rules[i];
// Coverage off for future-proof descriptions, only object().assert() is use right now
if (/* $lab:coverage:off$ */rule.arg &&
typeof rule.arg === 'object' &&
rule.arg.schema &&
rule.arg.ref /* $lab:coverage:on$ */) {
rule.arg = {
schema: rule.arg.schema.describe(),
ref: rule.arg.ref.toString()
};
}
}
}
if (this._inner.children &&
!shallow) {
description.children = {};
for (let i = 0; i < this._inner.children.length; ++i) {
const child = this._inner.children[i];
description.children[child.key] = child.schema.describe();
}
}
if (this._inner.dependencies.length) {
description.dependencies = Hoek.clone(this._inner.dependencies);
}
if (this._inner.patterns.length) {
description.patterns = [];
for (let i = 0; i < this._inner.patterns.length; ++i) {
const pattern = this._inner.patterns[i];
if (pattern.regex) {
description.patterns.push({ regex: pattern.regex.toString(), rule: pattern.rule.describe() });
}
else {
description.patterns.push({ schema: pattern.schema.describe(), rule: pattern.rule.describe() });
}
}
}
if (this._inner.renames.length > 0) {
description.renames = Hoek.clone(this._inner.renames);
}
return description;
}
assert(ref, schema, message) {
ref = Cast.ref(ref);
Hoek.assert(ref.isContext || ref.depth > 1, 'Cannot use assertions for root level references - use direct key rules instead');
message = message || 'pass the assertion test';
try {
schema = Cast.schema(this._currentJoi, schema);
}
catch (castErr) {
if (castErr.hasOwnProperty('path')) {
castErr.message = castErr.message + '(' + castErr.path + ')';
}
throw castErr;
}
const key = ref.path[ref.path.length - 1];
const path = ref.path.join('.');
return this._test('assert', { schema, ref }, function (value, state, options) {
const result = schema._validate(ref(value), null, options, value);
if (!result.errors) {
return value;
}
const localState = Hoek.merge({}, state);
localState.key = key;
localState.path = ref.path;
return this.createError('object.assert', { ref: path, message }, localState, options);
});
}
type(constructor, name = constructor.name) {
Hoek.assert(typeof constructor === 'function', 'type must be a constructor function');
const typeData = {
name,
ctor: constructor
};
return this._test('type', typeData, function (value, state, options) {
if (value instanceof constructor) {
return value;
}
return this.createError('object.type', { type: typeData.name }, state, options);
});
}
};
internals.safeParse = function (value) {
try {
return JSON.parse(value);
}
catch (parseErr) {}
return value;
};
internals.renameDefaults = {
alias: false, // Keep old value in place
multiple: false, // Allow renaming multiple keys into the same target
override: false // Overrides an existing key
};
internals.groupChildren = function (children) {
children.sort();
const grouped = {};
for (let i = 0; i < children.length; ++i) {
const child = children[i];
Hoek.assert(typeof child === 'string', 'children must be strings');
const group = child.split('.')[0];
const childGroup = grouped[group] = (grouped[group] || []);
childGroup.push(child.substring(group.length + 1));
}
return grouped;
};
internals.keysToLabels = function (schema, keys) {
const children = schema._inner.children;
if (!children) {
return keys;
}
const findLabel = function (key) {
const matchingChild = children.find((child) => child.key === key);
return matchingChild ? matchingChild.schema._getLabel(key) : key;
};
if (Array.isArray(keys)) {
return keys.map(findLabel);
}
return findLabel(keys);
};
internals.with = function (value, peers, parent, state, options) {
if (value === undefined) {
return value;
}
for (let i = 0; i < peers.length; ++i) {
const peer = peers[i];
if (!Object.prototype.hasOwnProperty.call(parent, peer) ||
parent[peer] === undefined) {
return this.createError('object.with', {
main: state.key,
mainWithLabel: internals.keysToLabels(this, state.key),
peer,
peerWithLabel: internals.keysToLabels(this, peer)
}, state, options);
}
}
return value;
};
internals.without = function (value, peers, parent, state, options) {
if (value === undefined) {
return value;
}
for (let i = 0; i < peers.length; ++i) {
const peer = peers[i];
if (Object.prototype.hasOwnProperty.call(parent, peer) &&
parent[peer] !== undefined) {
return this.createError('object.without', {
main: state.key,
mainWithLabel: internals.keysToLabels(this, state.key),
peer,
peerWithLabel: internals.keysToLabels(this, peer)
}, state, options);
}
}
return value;
};
internals.xor = function (value, peers, parent, state, options) {
const present = [];
for (let i = 0; i < peers.length; ++i) {
const peer = peers[i];
if (Object.prototype.hasOwnProperty.call(parent, peer) &&
parent[peer] !== undefined) {
present.push(peer);
}
}
if (present.length === 1) {
return value;
}
const context = { peers, peersWithLabels: internals.keysToLabels(this, peers) };
if (present.length === 0) {
return this.createError('object.missing', context, state, options);
}
return this.createError('object.xor', context, state, options);
};
internals.or = function (value, peers, parent, state, options) {
for (let i = 0; i < peers.length; ++i) {
const peer = peers[i];
if (Object.prototype.hasOwnProperty.call(parent, peer) &&
parent[peer] !== undefined) {
return value;
}
}
return this.createError('object.missing', {
peers,
peersWithLabels: internals.keysToLabels(this, peers)
}, state, options);
};
internals.and = function (value, peers, parent, state, options) {
const missing = [];
const present = [];
const count = peers.length;
for (let i = 0; i < count; ++i) {
const peer = peers[i];
if (!Object.prototype.hasOwnProperty.call(parent, peer) ||
parent[peer] === undefined) {
missing.push(peer);
}
else {
present.push(peer);
}
}
const aon = (missing.length === count || present.length === count);
if (!aon) {
return this.createError('object.and', {
present,
presentWithLabels: internals.keysToLabels(this, present),
missing,
missingWithLabels: internals.keysToLabels(this, missing)
}, state, options);
}
};
internals.nand = function (value, peers, parent, state, options) {
const present = [];
for (let i = 0; i < peers.length; ++i) {
const peer = peers[i];
if (Object.prototype.hasOwnProperty.call(parent, peer) &&
parent[peer] !== undefined) {
present.push(peer);
}
}
const values = Hoek.clone(peers);
const main = values.splice(0, 1)[0];
const allPresent = (present.length === peers.length);
return allPresent ? this.createError('object.nand', {
main,
mainWithLabel: internals.keysToLabels(this, main),
peers: values,
peersWithLabels: internals.keysToLabels(this, values)
}, state, options) : null;
};
module.exports = new internals.Object();

702
node_modules/joi/lib/types/string/index.js generated vendored Executable file
View File

@ -0,0 +1,702 @@
'use strict';
// Load modules
const Net = require('net');
const Hoek = require('hoek');
let Isemail; // Loaded on demand
const Any = require('../any');
const Ref = require('../../ref');
const JoiDate = require('../date');
const Uri = require('./uri');
const Ip = require('./ip');
// Declare internals
const internals = {
uriRegex: Uri.createUriRegex(),
ipRegex: Ip.createIpRegex(['ipv4', 'ipv6', 'ipvfuture'], 'optional'),
guidBrackets: {
'{': '}', '[': ']', '(': ')', '': ''
},
guidVersions: {
uuidv1: '1',
uuidv2: '2',
uuidv3: '3',
uuidv4: '4',
uuidv5: '5'
},
cidrPresences: ['required', 'optional', 'forbidden'],
normalizationForms: ['NFC', 'NFD', 'NFKC', 'NFKD']
};
internals.String = class extends Any {
constructor() {
super();
this._type = 'string';
this._invalids.add('');
}
_base(value, state, options) {
if (typeof value === 'string' &&
options.convert) {
if (this._flags.normalize) {
value = value.normalize(this._flags.normalize);
}
if (this._flags.case) {
value = (this._flags.case === 'upper' ? value.toLocaleUpperCase() : value.toLocaleLowerCase());
}
if (this._flags.trim) {
value = value.trim();
}
if (this._inner.replacements) {
for (let i = 0; i < this._inner.replacements.length; ++i) {
const replacement = this._inner.replacements[i];
value = value.replace(replacement.pattern, replacement.replacement);
}
}
if (this._flags.truncate) {
for (let i = 0; i < this._tests.length; ++i) {
const test = this._tests[i];
if (test.name === 'max') {
value = value.slice(0, test.arg);
break;
}
}
}
if (this._flags.byteAligned && value.length % 2 !== 0) {
value = `0${value}`;
}
}
return {
value,
errors: (typeof value === 'string') ? null : this.createError('string.base', { value }, state, options)
};
}
insensitive() {
if (this._flags.insensitive) {
return this;
}
const obj = this.clone();
obj._flags.insensitive = true;
return obj;
}
creditCard() {
return this._test('creditCard', undefined, function (value, state, options) {
let i = value.length;
let sum = 0;
let mul = 1;
while (i--) {
const char = value.charAt(i) * mul;
sum = sum + (char - (char > 9) * 9);
mul = mul ^ 3;
}
const check = (sum % 10 === 0) && (sum > 0);
return check ? value : this.createError('string.creditCard', { value }, state, options);
});
}
regex(pattern, patternOptions) {
Hoek.assert(pattern instanceof RegExp, 'pattern must be a RegExp');
const patternObject = {
pattern: new RegExp(pattern.source, pattern.ignoreCase ? 'i' : undefined) // Future version should break this and forbid unsupported regex flags
};
if (typeof patternOptions === 'string') {
patternObject.name = patternOptions;
}
else if (typeof patternOptions === 'object') {
patternObject.invert = !!patternOptions.invert;
if (patternOptions.name) {
patternObject.name = patternOptions.name;
}
}
const errorCode = ['string.regex', patternObject.invert ? '.invert' : '', patternObject.name ? '.name' : '.base'].join('');
return this._test('regex', patternObject, function (value, state, options) {
const patternMatch = patternObject.pattern.test(value);
if (patternMatch ^ patternObject.invert) {
return value;
}
return this.createError(errorCode, { name: patternObject.name, pattern: patternObject.pattern, value }, state, options);
});
}
alphanum() {
return this._test('alphanum', undefined, function (value, state, options) {
if (/^[a-zA-Z0-9]+$/.test(value)) {
return value;
}
return this.createError('string.alphanum', { value }, state, options);
});
}
token() {
return this._test('token', undefined, function (value, state, options) {
if (/^\w+$/.test(value)) {
return value;
}
return this.createError('string.token', { value }, state, options);
});
}
email(isEmailOptions) {
if (isEmailOptions) {
Hoek.assert(typeof isEmailOptions === 'object', 'email options must be an object');
Hoek.assert(typeof isEmailOptions.checkDNS === 'undefined', 'checkDNS option is not supported');
Hoek.assert(typeof isEmailOptions.tldWhitelist === 'undefined' ||
typeof isEmailOptions.tldWhitelist === 'object', 'tldWhitelist must be an array or object');
Hoek.assert(
typeof isEmailOptions.minDomainAtoms === 'undefined' ||
Number.isSafeInteger(isEmailOptions.minDomainAtoms) &&
isEmailOptions.minDomainAtoms > 0,
'minDomainAtoms must be a positive integer'
);
Hoek.assert(
typeof isEmailOptions.errorLevel === 'undefined' ||
typeof isEmailOptions.errorLevel === 'boolean' ||
(
Number.isSafeInteger(isEmailOptions.errorLevel) &&
isEmailOptions.errorLevel >= 0
),
'errorLevel must be a non-negative integer or boolean'
);
}
return this._test('email', isEmailOptions, function (value, state, options) {
Isemail = Isemail || require('isemail');
try {
const result = Isemail.validate(value, isEmailOptions);
if (result === true || result === 0) {
return value;
}
}
catch (e) { }
return this.createError('string.email', { value }, state, options);
});
}
ip(ipOptions = {}) {
let regex = internals.ipRegex;
Hoek.assert(typeof ipOptions === 'object', 'options must be an object');
if (ipOptions.cidr) {
Hoek.assert(typeof ipOptions.cidr === 'string', 'cidr must be a string');
ipOptions.cidr = ipOptions.cidr.toLowerCase();
Hoek.assert(Hoek.contain(internals.cidrPresences, ipOptions.cidr), 'cidr must be one of ' + internals.cidrPresences.join(', '));
// If we only received a `cidr` setting, create a regex for it. But we don't need to create one if `cidr` is "optional" since that is the default
if (!ipOptions.version && ipOptions.cidr !== 'optional') {
regex = Ip.createIpRegex(['ipv4', 'ipv6', 'ipvfuture'], ipOptions.cidr);
}
}
else {
// Set our default cidr strategy
ipOptions.cidr = 'optional';
}
let versions;
if (ipOptions.version) {
if (!Array.isArray(ipOptions.version)) {
ipOptions.version = [ipOptions.version];
}
Hoek.assert(ipOptions.version.length >= 1, 'version must have at least 1 version specified');
versions = [];
for (let i = 0; i < ipOptions.version.length; ++i) {
let version = ipOptions.version[i];
Hoek.assert(typeof version === 'string', 'version at position ' + i + ' must be a string');
version = version.toLowerCase();
Hoek.assert(Ip.versions[version], 'version at position ' + i + ' must be one of ' + Object.keys(Ip.versions).join(', '));
versions.push(version);
}
// Make sure we have a set of versions
versions = Hoek.unique(versions);
regex = Ip.createIpRegex(versions, ipOptions.cidr);
}
return this._test('ip', ipOptions, function (value, state, options) {
if (regex.test(value)) {
return value;
}
if (versions) {
return this.createError('string.ipVersion', { value, cidr: ipOptions.cidr, version: versions }, state, options);
}
return this.createError('string.ip', { value, cidr: ipOptions.cidr }, state, options);
});
}
uri(uriOptions) {
let customScheme = '';
let allowRelative = false;
let relativeOnly = false;
let allowQuerySquareBrackets = false;
let regex = internals.uriRegex;
if (uriOptions) {
Hoek.assert(typeof uriOptions === 'object', 'options must be an object');
const unknownOptions = Object.keys(uriOptions).filter((key) => !['scheme', 'allowRelative', 'relativeOnly', 'allowQuerySquareBrackets'].includes(key));
Hoek.assert(unknownOptions.length === 0, `options contain unknown keys: ${unknownOptions}`);
if (uriOptions.scheme) {
Hoek.assert(uriOptions.scheme instanceof RegExp || typeof uriOptions.scheme === 'string' || Array.isArray(uriOptions.scheme), 'scheme must be a RegExp, String, or Array');
if (!Array.isArray(uriOptions.scheme)) {
uriOptions.scheme = [uriOptions.scheme];
}
Hoek.assert(uriOptions.scheme.length >= 1, 'scheme must have at least 1 scheme specified');
// Flatten the array into a string to be used to match the schemes.
for (let i = 0; i < uriOptions.scheme.length; ++i) {
const scheme = uriOptions.scheme[i];
Hoek.assert(scheme instanceof RegExp || typeof scheme === 'string', 'scheme at position ' + i + ' must be a RegExp or String');
// Add OR separators if a value already exists
customScheme = customScheme + (customScheme ? '|' : '');
// If someone wants to match HTTP or HTTPS for example then we need to support both RegExp and String so we don't escape their pattern unknowingly.
if (scheme instanceof RegExp) {
customScheme = customScheme + scheme.source;
}
else {
Hoek.assert(/[a-zA-Z][a-zA-Z0-9+-\.]*/.test(scheme), 'scheme at position ' + i + ' must be a valid scheme');
customScheme = customScheme + Hoek.escapeRegex(scheme);
}
}
}
if (uriOptions.allowRelative) {
allowRelative = true;
}
if (uriOptions.relativeOnly) {
relativeOnly = true;
}
if (uriOptions.allowQuerySquareBrackets) {
allowQuerySquareBrackets = true;
}
}
if (customScheme || allowRelative || relativeOnly || allowQuerySquareBrackets) {
regex = Uri.createUriRegex(customScheme, allowRelative, relativeOnly, allowQuerySquareBrackets);
}
return this._test('uri', uriOptions, function (value, state, options) {
if (regex.test(value)) {
return value;
}
if (relativeOnly) {
return this.createError('string.uriRelativeOnly', { value }, state, options);
}
if (customScheme) {
return this.createError('string.uriCustomScheme', { scheme: customScheme, value }, state, options);
}
return this.createError('string.uri', { value }, state, options);
});
}
isoDate() {
return this._test('isoDate', undefined, function (value, state, options) {
if (JoiDate._isIsoDate(value)) {
if (!options.convert) {
return value;
}
const d = new Date(value);
if (!isNaN(d.getTime())) {
return d.toISOString();
}
}
return this.createError('string.isoDate', { value }, state, options);
});
}
guid(guidOptions) {
let versionNumbers = '';
if (guidOptions && guidOptions.version) {
if (!Array.isArray(guidOptions.version)) {
guidOptions.version = [guidOptions.version];
}
Hoek.assert(guidOptions.version.length >= 1, 'version must have at least 1 valid version specified');
const versions = new Set();
for (let i = 0; i < guidOptions.version.length; ++i) {
let version = guidOptions.version[i];
Hoek.assert(typeof version === 'string', 'version at position ' + i + ' must be a string');
version = version.toLowerCase();
const versionNumber = internals.guidVersions[version];
Hoek.assert(versionNumber, 'version at position ' + i + ' must be one of ' + Object.keys(internals.guidVersions).join(', '));
Hoek.assert(!(versions.has(versionNumber)), 'version at position ' + i + ' must not be a duplicate.');
versionNumbers += versionNumber;
versions.add(versionNumber);
}
}
const guidRegex = new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}([:-]?)[0-9A-F]{4}\\2?[${versionNumbers || '0-9A-F'}][0-9A-F]{3}\\2?[${versionNumbers ? '89AB' : '0-9A-F'}][0-9A-F]{3}\\2?[0-9A-F]{12}([\\]}\\)]?)$`, 'i');
return this._test('guid', guidOptions, function (value, state, options) {
const results = guidRegex.exec(value);
if (!results) {
return this.createError('string.guid', { value }, state, options);
}
// Matching braces
if (internals.guidBrackets[results[1]] !== results[results.length - 1]) {
return this.createError('string.guid', { value }, state, options);
}
return value;
});
}
hex(hexOptions = {}) {
Hoek.assert(typeof hexOptions === 'object', 'hex options must be an object');
Hoek.assert(typeof hexOptions.byteAligned === 'undefined' || typeof hexOptions.byteAligned === 'boolean',
'byteAligned must be boolean');
const byteAligned = hexOptions.byteAligned === true;
const regex = /^[a-f0-9]+$/i;
const obj = this._test('hex', regex, function (value, state, options) {
if (regex.test(value)) {
if (byteAligned && value.length % 2 !== 0) {
return this.createError('string.hexAlign', { value }, state, options);
}
return value;
}
return this.createError('string.hex', { value }, state, options);
});
if (byteAligned) {
obj._flags.byteAligned = true;
}
return obj;
}
base64(base64Options = {}) {
// Validation.
Hoek.assert(typeof base64Options === 'object', 'base64 options must be an object');
Hoek.assert(typeof base64Options.paddingRequired === 'undefined' || typeof base64Options.paddingRequired === 'boolean',
'paddingRequired must be boolean');
// Determine if padding is required.
const paddingRequired = base64Options.paddingRequired === false ?
base64Options.paddingRequired
: base64Options.paddingRequired || true;
// Set validation based on preference.
const regex = paddingRequired ?
// Padding is required.
/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/
// Padding is optional.
: /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/;
return this._test('base64', regex, function (value, state, options) {
if (regex.test(value)) {
return value;
}
return this.createError('string.base64', { value }, state, options);
});
}
dataUri(dataUriOptions = {}) {
const regex = /^data:[\w\/\+]+;((charset=[\w-]+|base64),)?(.*)$/;
// Determine if padding is required.
const paddingRequired = dataUriOptions.paddingRequired === false ?
dataUriOptions.paddingRequired
: dataUriOptions.paddingRequired || true;
const base64regex = paddingRequired ?
/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/
: /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/;
return this._test('dataUri', regex, function (value, state, options) {
const matches = value.match(regex);
if (matches) {
if (!matches[2]) {
return value;
}
if (matches[2] !== 'base64') {
return value;
}
if (base64regex.test(matches[3])) {
return value;
}
}
return this.createError('string.dataUri', { value }, state, options);
});
}
hostname() {
const regex = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;
return this._test('hostname', undefined, function (value, state, options) {
if ((value.length <= 255 && regex.test(value)) ||
Net.isIPv6(value)) {
return value;
}
return this.createError('string.hostname', { value }, state, options);
});
}
normalize(form = 'NFC') {
Hoek.assert(Hoek.contain(internals.normalizationForms, form), 'normalization form must be one of ' + internals.normalizationForms.join(', '));
const obj = this._test('normalize', form, function (value, state, options) {
if (options.convert ||
value === value.normalize(form)) {
return value;
}
return this.createError('string.normalize', { value, form }, state, options);
});
obj._flags.normalize = form;
return obj;
}
lowercase() {
const obj = this._test('lowercase', undefined, function (value, state, options) {
if (options.convert ||
value === value.toLocaleLowerCase()) {
return value;
}
return this.createError('string.lowercase', { value }, state, options);
});
obj._flags.case = 'lower';
return obj;
}
uppercase() {
const obj = this._test('uppercase', undefined, function (value, state, options) {
if (options.convert ||
value === value.toLocaleUpperCase()) {
return value;
}
return this.createError('string.uppercase', { value }, state, options);
});
obj._flags.case = 'upper';
return obj;
}
trim(enabled = true) {
Hoek.assert(typeof enabled === 'boolean', 'option must be a boolean');
if ((this._flags.trim && enabled) || (!this._flags.trim && !enabled)) {
return this;
}
let obj;
if (enabled) {
obj = this._test('trim', undefined, function (value, state, options) {
if (options.convert ||
value === value.trim()) {
return value;
}
return this.createError('string.trim', { value }, state, options);
});
}
else {
obj = this.clone();
obj._tests = obj._tests.filter((test) => test.name !== 'trim');
}
obj._flags.trim = enabled;
return obj;
}
replace(pattern, replacement) {
if (typeof pattern === 'string') {
pattern = new RegExp(Hoek.escapeRegex(pattern), 'g');
}
Hoek.assert(pattern instanceof RegExp, 'pattern must be a RegExp');
Hoek.assert(typeof replacement === 'string', 'replacement must be a String');
// This can not be considere a test like trim, we can't "reject"
// anything from this rule, so just clone the current object
const obj = this.clone();
if (!obj._inner.replacements) {
obj._inner.replacements = [];
}
obj._inner.replacements.push({
pattern,
replacement
});
return obj;
}
truncate(enabled) {
const value = enabled === undefined ? true : !!enabled;
if (this._flags.truncate === value) {
return this;
}
const obj = this.clone();
obj._flags.truncate = value;
return obj;
}
};
internals.compare = function (type, compare) {
return function (limit, encoding) {
const isRef = Ref.isRef(limit);
Hoek.assert((Number.isSafeInteger(limit) && limit >= 0) || isRef, 'limit must be a positive integer or reference');
Hoek.assert(!encoding || Buffer.isEncoding(encoding), 'Invalid encoding:', encoding);
return this._test(type, limit, function (value, state, options) {
let compareTo;
if (isRef) {
compareTo = limit(state.reference || state.parent, options);
if (!Number.isSafeInteger(compareTo)) {
return this.createError('string.ref', { ref: limit.key }, state, options);
}
}
else {
compareTo = limit;
}
if (compare(value, compareTo, encoding)) {
return value;
}
return this.createError('string.' + type, { limit: compareTo, value, encoding }, state, options);
});
};
};
internals.String.prototype.min = internals.compare('min', (value, limit, encoding) => {
const length = encoding ? Buffer.byteLength(value, encoding) : value.length;
return length >= limit;
});
internals.String.prototype.max = internals.compare('max', (value, limit, encoding) => {
const length = encoding ? Buffer.byteLength(value, encoding) : value.length;
return length <= limit;
});
internals.String.prototype.length = internals.compare('length', (value, limit, encoding) => {
const length = encoding ? Buffer.byteLength(value, encoding) : value.length;
return length === limit;
});
// Aliases
internals.String.prototype.uuid = internals.String.prototype.guid;
module.exports = new internals.String();

54
node_modules/joi/lib/types/string/ip.js generated vendored Normal file
View File

@ -0,0 +1,54 @@
'use strict';
// Load modules
const RFC3986 = require('./rfc3986');
// Declare internals
const internals = {
Ip: {
cidrs: {
ipv4: {
required: '\\/(?:' + RFC3986.ipv4Cidr + ')',
optional: '(?:\\/(?:' + RFC3986.ipv4Cidr + '))?',
forbidden: ''
},
ipv6: {
required: '\\/' + RFC3986.ipv6Cidr,
optional: '(?:\\/' + RFC3986.ipv6Cidr + ')?',
forbidden: ''
},
ipvfuture: {
required: '\\/' + RFC3986.ipv6Cidr,
optional: '(?:\\/' + RFC3986.ipv6Cidr + ')?',
forbidden: ''
}
},
versions: {
ipv4: RFC3986.IPv4address,
ipv6: RFC3986.IPv6address,
ipvfuture: RFC3986.IPvFuture
}
}
};
internals.Ip.createIpRegex = function (versions, cidr) {
let regex;
for (let i = 0; i < versions.length; ++i) {
const version = versions[i];
if (!regex) {
regex = '^(?:' + internals.Ip.versions[version] + internals.Ip.cidrs[version][cidr];
}
else {
regex += '|' + internals.Ip.versions[version] + internals.Ip.cidrs[version][cidr];
}
}
return new RegExp(regex + ')$');
};
module.exports = internals.Ip;

219
node_modules/joi/lib/types/string/rfc3986.js generated vendored Normal file
View File

@ -0,0 +1,219 @@
'use strict';
// Load modules
// Delcare internals
const internals = {
rfc3986: {}
};
internals.generate = function () {
/**
* elements separated by forward slash ("/") are alternatives.
*/
const or = '|';
/**
* Rule to support zero-padded addresses.
*/
const zeroPad = '0?';
/**
* DIGIT = %x30-39 ; 0-9
*/
const digit = '0-9';
const digitOnly = '[' + digit + ']';
/**
* ALPHA = %x41-5A / %x61-7A ; A-Z / a-z
*/
const alpha = 'a-zA-Z';
const alphaOnly = '[' + alpha + ']';
/**
* IPv4
* cidr = DIGIT ; 0-9
* / %x31-32 DIGIT ; 10-29
* / "3" %x30-32 ; 30-32
*/
internals.rfc3986.ipv4Cidr = digitOnly + or + '[1-2]' + digitOnly + or + '3' + '[0-2]';
/**
* IPv6
* cidr = DIGIT ; 0-9
* / %x31-39 DIGIT ; 10-99
* / "1" %x0-1 DIGIT ; 100-119
* / "12" %x0-8 ; 120-128
*/
internals.rfc3986.ipv6Cidr = '(?:' + zeroPad + zeroPad + digitOnly + or + zeroPad + '[1-9]' + digitOnly + or + '1' + '[01]' + digitOnly + or + '12[0-8])';
/**
* HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"
*/
const hexDigit = digit + 'A-Fa-f';
const hexDigitOnly = '[' + hexDigit + ']';
/**
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
*/
const unreserved = alpha + digit + '-\\._~';
/**
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
*/
const subDelims = '!\\$&\'\\(\\)\\*\\+,;=';
/**
* pct-encoded = "%" HEXDIG HEXDIG
*/
const pctEncoded = '%' + hexDigit;
/**
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
*/
const pchar = unreserved + pctEncoded + subDelims + ':@';
const pcharOnly = '[' + pchar + ']';
/**
* squareBrackets example: []
*/
const squareBrackets = '\\[\\]';
/**
* dec-octet = DIGIT ; 0-9
* / %x31-39 DIGIT ; 10-99
* / "1" 2DIGIT ; 100-199
* / "2" %x30-34 DIGIT ; 200-249
* / "25" %x30-35 ; 250-255
*/
const decOctect = '(?:' + zeroPad + zeroPad + digitOnly + or + zeroPad + '[1-9]' + digitOnly + or + '1' + digitOnly + digitOnly + or + '2' + '[0-4]' + digitOnly + or + '25' + '[0-5])';
/**
* IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
*/
internals.rfc3986.IPv4address = '(?:' + decOctect + '\\.){3}' + decOctect;
/**
* h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal
* ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address
* IPv6address = 6( h16 ":" ) ls32
* / "::" 5( h16 ":" ) ls32
* / [ h16 ] "::" 4( h16 ":" ) ls32
* / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
* / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
* / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
* / [ *4( h16 ":" ) h16 ] "::" ls32
* / [ *5( h16 ":" ) h16 ] "::" h16
* / [ *6( h16 ":" ) h16 ] "::"
*/
const h16 = hexDigitOnly + '{1,4}';
const ls32 = '(?:' + h16 + ':' + h16 + '|' + internals.rfc3986.IPv4address + ')';
const IPv6SixHex = '(?:' + h16 + ':){6}' + ls32;
const IPv6FiveHex = '::(?:' + h16 + ':){5}' + ls32;
const IPv6FourHex = '(?:' + h16 + ')?::(?:' + h16 + ':){4}' + ls32;
const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32;
const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32;
const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32;
const IPv6NoneHex = '(?:(?:' + h16 + ':){0,4}' + h16 + ')?::' + ls32;
const IPv6NoneHex2 = '(?:(?:' + h16 + ':){0,5}' + h16 + ')?::' + h16;
const IPv6NoneHex3 = '(?:(?:' + h16 + ':){0,6}' + h16 + ')?::';
internals.rfc3986.IPv6address = '(?:' + IPv6SixHex + or + IPv6FiveHex + or + IPv6FourHex + or + IPv6ThreeHex + or + IPv6TwoHex + or + IPv6OneHex + or + IPv6NoneHex + or + IPv6NoneHex2 + or + IPv6NoneHex3 + ')';
/**
* IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
*/
internals.rfc3986.IPvFuture = 'v' + hexDigitOnly + '+\\.[' + unreserved + subDelims + ':]+';
/**
* scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
*/
internals.rfc3986.scheme = alphaOnly + '[' + alpha + digit + '+-\\.]*';
/**
* userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
*/
const userinfo = '[' + unreserved + pctEncoded + subDelims + ':]*';
/**
* IP-literal = "[" ( IPv6address / IPvFuture ) "]"
*/
const IPLiteral = '\\[(?:' + internals.rfc3986.IPv6address + or + internals.rfc3986.IPvFuture + ')\\]';
/**
* reg-name = *( unreserved / pct-encoded / sub-delims )
*/
const regName = '[' + unreserved + pctEncoded + subDelims + ']{0,255}';
/**
* host = IP-literal / IPv4address / reg-name
*/
const host = '(?:' + IPLiteral + or + internals.rfc3986.IPv4address + or + regName + ')';
/**
* port = *DIGIT
*/
const port = digitOnly + '*';
/**
* authority = [ userinfo "@" ] host [ ":" port ]
*/
const authority = '(?:' + userinfo + '@)?' + host + '(?::' + port + ')?';
/**
* segment = *pchar
* segment-nz = 1*pchar
* path = path-abempty ; begins with "/" or is empty
* / path-absolute ; begins with "/" but not "//"
* / path-noscheme ; begins with a non-colon segment
* / path-rootless ; begins with a segment
* / path-empty ; zero characters
* path-abempty = *( "/" segment )
* path-absolute = "/" [ segment-nz *( "/" segment ) ]
* path-rootless = segment-nz *( "/" segment )
*/
const segment = pcharOnly + '*';
const segmentNz = pcharOnly + '+';
const segmentNzNc = '[' + unreserved + pctEncoded + subDelims + '@' + ']+';
const pathEmpty = '';
const pathAbEmpty = '(?:\\/' + segment + ')*';
const pathAbsolute = '\\/(?:' + segmentNz + pathAbEmpty + ')?';
const pathRootless = segmentNz + pathAbEmpty;
const pathNoScheme = segmentNzNc + pathAbEmpty;
/**
* hier-part = "//" authority path
*/
internals.rfc3986.hierPart = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathRootless + ')';
/**
* relative-part = "//" authority path-abempty
* / path-absolute
* / path-noscheme
* / path-empty
*/
internals.rfc3986.relativeRef = '(?:' + '(?:\\/\\/' + authority + pathAbEmpty + ')' + or + pathAbsolute + or + pathNoScheme + or + pathEmpty + ')';
/**
* query = *( pchar / "/" / "?" )
*/
internals.rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part or end of the line.
/**
* query = *( pchar / "[" / "]" / "/" / "?" )
*/
internals.rfc3986.queryWithSquareBrackets = '[' + pchar + squareBrackets + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment part or end of the line.
/**
* fragment = *( pchar / "/" / "?" )
*/
internals.rfc3986.fragment = '[' + pchar + '\\/\\?]*';
};
internals.generate();
module.exports = internals.rfc3986;

46
node_modules/joi/lib/types/string/uri.js generated vendored Normal file
View File

@ -0,0 +1,46 @@
'use strict';
// Load Modules
const RFC3986 = require('./rfc3986');
// Declare internals
const internals = {
Uri: {
createUriRegex: function (optionalScheme, allowRelative, relativeOnly, allowQuerySquareBrackets) {
let scheme = RFC3986.scheme;
let prefix;
if (relativeOnly) {
prefix = '(?:' + RFC3986.relativeRef + ')';
}
else {
// If we were passed a scheme, use it instead of the generic one
if (optionalScheme) {
// Have to put this in a non-capturing group to handle the OR statements
scheme = '(?:' + optionalScheme + ')';
}
const withScheme = '(?:' + scheme + ':' + RFC3986.hierPart + ')';
prefix = allowRelative ? '(?:' + withScheme + '|' + RFC3986.relativeRef + ')' : withScheme;
}
/**
* URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
*
* OR
*
* relative-ref = relative-part [ "?" query ] [ "#" fragment ]
*/
return new RegExp('^' + prefix + '(?:\\?' + (allowQuerySquareBrackets ? RFC3986.queryWithSquareBrackets : RFC3986.query) + ')?' + '(?:#' + RFC3986.fragment + ')?$');
}
}
};
module.exports = internals.Uri;

93
node_modules/joi/lib/types/symbol/index.js generated vendored Normal file
View File

@ -0,0 +1,93 @@
'use strict';
// Load modules
const Util = require('util');
const Any = require('../any');
const Hoek = require('hoek');
// Declare internals
const internals = {};
internals.Map = class extends Map {
slice() {
return new internals.Map(this);
}
toString() {
return Util.inspect(this);
}
};
internals.Symbol = class extends Any {
constructor() {
super();
this._type = 'symbol';
this._inner.map = new internals.Map();
}
_base(value, state, options) {
if (options.convert) {
const lookup = this._inner.map.get(value);
if (lookup) {
value = lookup;
}
if (this._flags.allowOnly) {
return {
value,
errors: (typeof value === 'symbol') ? null : this.createError('symbol.map', { map: this._inner.map }, state, options)
};
}
}
return {
value,
errors: (typeof value === 'symbol') ? null : this.createError('symbol.base', null, state, options)
};
}
map(iterable) {
if (iterable && !iterable[Symbol.iterator] && typeof iterable === 'object') {
iterable = Object.entries(iterable);
}
Hoek.assert(iterable && iterable[Symbol.iterator], 'Iterable must be an iterable or object');
const obj = this.clone();
const symbols = [];
for (const entry of iterable) {
Hoek.assert(entry && entry[Symbol.iterator], 'Entry must be an iterable');
const [key, value] = entry;
Hoek.assert(typeof key !== 'object' && typeof key !== 'function' && typeof key !== 'symbol', 'Key must not be an object, function, or Symbol');
Hoek.assert(typeof value === 'symbol', 'Value must be a Symbol');
obj._inner.map.set(key, value);
symbols.push(value);
}
return obj.valid(...symbols);
}
describe() {
const description = super.describe();
description.map = new Map(this._inner.map);
return description;
}
};
module.exports = new internals.Symbol();

3
node_modules/joi/node_modules/hoek/.npmignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
*
!lib/**
!.npmignore

32
node_modules/joi/node_modules/hoek/LICENSE generated vendored Normal file
View File

@ -0,0 +1,32 @@
Copyright (c) 2011-2017, Project contributors
Copyright (c) 2011-2014, Walmart
Copyright (c) 2011, Yahoo Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of any contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* * *
The complete list of contributors can be found at: https://github.com/hapijs/hapi/graphs/contributors
Portions of this project were initially based on the Yahoo! Inc. Postmile project,
published at https://github.com/yahoo/postmile.

30
node_modules/joi/node_modules/hoek/README.md generated vendored Normal file
View File

@ -0,0 +1,30 @@
![hoek Logo](https://raw.github.com/hapijs/hoek/master/images/hoek.png)
Utility methods for the hapi ecosystem. This module is not intended to solve every problem for everyone, but rather as a central place to store hapi-specific methods. If you're looking for a general purpose utility module, check out [lodash](https://github.com/lodash/lodash) or [underscore](https://github.com/jashkenas/underscore).
[![Build Status](https://secure.travis-ci.org/hapijs/hoek.svg)](http://travis-ci.org/hapijs/hoek)
<a href="https://andyet.com"><img src="https://s3.amazonaws.com/static.andyet.com/images/%26yet-logo.svg" align="right" /></a>
Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf)
**hoek** is sponsored by [&yet](https://andyet.com)
## Usage
The *Hoek* library contains some common functions used within the hapi ecosystem. It comes with useful methods for Arrays (clone, merge, applyToDefaults), Objects (removeKeys, copy), Asserting and more.
For example, to use Hoek to set configuration with default options:
```javascript
const Hoek = require('hoek');
const default = {url : "www.github.com", port : "8000", debug : true};
const config = Hoek.applyToDefaults(default, {port : "3000", admin : true});
// In this case, config would be { url: 'www.github.com', port: '3000', debug: true, admin: true }
```
## Documentation
[**API Reference**](API.md)

168
node_modules/joi/node_modules/hoek/lib/escape.js generated vendored Executable file
View File

@ -0,0 +1,168 @@
'use strict';
// Declare internals
const internals = {};
exports.escapeJavaScript = function (input) {
if (!input) {
return '';
}
let escaped = '';
for (let i = 0; i < input.length; ++i) {
const charCode = input.charCodeAt(i);
if (internals.isSafe(charCode)) {
escaped += input[i];
}
else {
escaped += internals.escapeJavaScriptChar(charCode);
}
}
return escaped;
};
exports.escapeHtml = function (input) {
if (!input) {
return '';
}
let escaped = '';
for (let i = 0; i < input.length; ++i) {
const charCode = input.charCodeAt(i);
if (internals.isSafe(charCode)) {
escaped += input[i];
}
else {
escaped += internals.escapeHtmlChar(charCode);
}
}
return escaped;
};
exports.escapeJson = function (input) {
if (!input) {
return '';
}
const lessThan = 0x3C;
const greaterThan = 0x3E;
const andSymbol = 0x26;
const lineSeperator = 0x2028;
// replace method
let charCode;
return input.replace(/[<>&\u2028\u2029]/g, (match) => {
charCode = match.charCodeAt(0);
if (charCode === lessThan) {
return '\\u003c';
}
else if (charCode === greaterThan) {
return '\\u003e';
}
else if (charCode === andSymbol) {
return '\\u0026';
}
else if (charCode === lineSeperator) {
return '\\u2028';
}
return '\\u2029';
});
};
internals.escapeJavaScriptChar = function (charCode) {
if (charCode >= 256) {
return '\\u' + internals.padLeft('' + charCode, 4);
}
const hexValue = Buffer.from(String.fromCharCode(charCode), 'ascii').toString('hex');
return '\\x' + internals.padLeft(hexValue, 2);
};
internals.escapeHtmlChar = function (charCode) {
const namedEscape = internals.namedHtml[charCode];
if (typeof namedEscape !== 'undefined') {
return namedEscape;
}
if (charCode >= 256) {
return '&#' + charCode + ';';
}
const hexValue = Buffer.from(String.fromCharCode(charCode), 'ascii').toString('hex');
return '&#x' + internals.padLeft(hexValue, 2) + ';';
};
internals.padLeft = function (str, len) {
while (str.length < len) {
str = '0' + str;
}
return str;
};
internals.isSafe = function (charCode) {
return (typeof internals.safeCharCodes[charCode] !== 'undefined');
};
internals.namedHtml = {
'38': '&amp;',
'60': '&lt;',
'62': '&gt;',
'34': '&quot;',
'160': '&nbsp;',
'162': '&cent;',
'163': '&pound;',
'164': '&curren;',
'169': '&copy;',
'174': '&reg;'
};
internals.safeCharCodes = (function () {
const safe = {};
for (let i = 32; i < 123; ++i) {
if ((i >= 97) || // a-z
(i >= 65 && i <= 90) || // A-Z
(i >= 48 && i <= 57) || // 0-9
i === 32 || // space
i === 46 || // .
i === 44 || // ,
i === 45 || // -
i === 58 || // :
i === 95) { // _
safe[i] = null;
}
}
return safe;
}());

954
node_modules/joi/node_modules/hoek/lib/index.js generated vendored Executable file
View File

@ -0,0 +1,954 @@
'use strict';
// Load modules
const Assert = require('assert');
const Crypto = require('crypto');
const Path = require('path');
const Util = require('util');
const Escape = require('./escape');
// Declare internals
const internals = {};
// Clone object or array
exports.clone = function (obj, seen) {
if (typeof obj !== 'object' ||
obj === null) {
return obj;
}
seen = seen || new Map();
const lookup = seen.get(obj);
if (lookup) {
return lookup;
}
let newObj;
let cloneDeep = false;
if (!Array.isArray(obj)) {
if (Buffer.isBuffer(obj)) {
newObj = Buffer.from(obj);
}
else if (obj instanceof Date) {
newObj = new Date(obj.getTime());
}
else if (obj instanceof RegExp) {
newObj = new RegExp(obj);
}
else {
const proto = Object.getPrototypeOf(obj);
if (proto &&
proto.isImmutable) {
newObj = obj;
}
else {
newObj = Object.create(proto);
cloneDeep = true;
}
}
}
else {
newObj = [];
cloneDeep = true;
}
seen.set(obj, newObj);
if (cloneDeep) {
const keys = Object.getOwnPropertyNames(obj);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor &&
(descriptor.get ||
descriptor.set)) {
Object.defineProperty(newObj, key, descriptor);
}
else {
newObj[key] = exports.clone(obj[key], seen);
}
}
}
return newObj;
};
// Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied
/*eslint-disable */
exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) {
/*eslint-enable */
exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object');
exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
if (!source) {
return target;
}
if (Array.isArray(source)) {
exports.assert(Array.isArray(target), 'Cannot merge array onto an object');
if (isMergeArrays === false) { // isMergeArrays defaults to true
target.length = 0; // Must not change target assignment
}
for (let i = 0; i < source.length; ++i) {
target.push(exports.clone(source[i]));
}
return target;
}
const keys = Object.keys(source);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
if (key === '__proto__') {
continue;
}
const value = source[key];
if (value &&
typeof value === 'object') {
if (!target[key] ||
typeof target[key] !== 'object' ||
(Array.isArray(target[key]) !== Array.isArray(value)) ||
value instanceof Date ||
Buffer.isBuffer(value) ||
value instanceof RegExp) {
target[key] = exports.clone(value);
}
else {
exports.merge(target[key], value, isNullOverride, isMergeArrays);
}
}
else {
if (value !== null &&
value !== undefined) { // Explicit to preserve empty strings
target[key] = value;
}
else if (isNullOverride !== false) { // Defaults to true
target[key] = value;
}
}
}
return target;
};
// Apply options to a copy of the defaults
exports.applyToDefaults = function (defaults, options, isNullOverride) {
exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
if (!options) { // If no options, return null
return null;
}
const copy = exports.clone(defaults);
if (options === true) { // If options is set to true, use defaults
return copy;
}
return exports.merge(copy, options, isNullOverride === true, false);
};
// Clone an object except for the listed keys which are shallow copied
exports.cloneWithShallow = function (source, keys) {
if (!source ||
typeof source !== 'object') {
return source;
}
const storage = internals.store(source, keys); // Move shallow copy items to storage
const copy = exports.clone(source); // Deep copy the rest
internals.restore(copy, source, storage); // Shallow copy the stored items and restore
return copy;
};
internals.store = function (source, keys) {
const storage = {};
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const value = exports.reach(source, key);
if (value !== undefined) {
storage[key] = value;
internals.reachSet(source, key, undefined);
}
}
return storage;
};
internals.restore = function (copy, source, storage) {
const keys = Object.keys(storage);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
internals.reachSet(copy, key, storage[key]);
internals.reachSet(source, key, storage[key]);
}
};
internals.reachSet = function (obj, key, value) {
const path = key.split('.');
let ref = obj;
for (let i = 0; i < path.length; ++i) {
const segment = path[i];
if (i + 1 === path.length) {
ref[segment] = value;
}
ref = ref[segment];
}
};
// Apply options to defaults except for the listed keys which are shallow copied from option without merging
exports.applyToDefaultsWithShallow = function (defaults, options, keys) {
exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
exports.assert(keys && Array.isArray(keys), 'Invalid keys');
if (!options) { // If no options, return null
return null;
}
const copy = exports.cloneWithShallow(defaults, keys);
if (options === true) { // If options is set to true, use defaults
return copy;
}
const storage = internals.store(options, keys); // Move shallow copy items to storage
exports.merge(copy, options, false, false); // Deep copy the rest
internals.restore(copy, options, storage); // Shallow copy the stored items and restore
return copy;
};
// Deep object or array comparison
exports.deepEqual = function (obj, ref, options, seen) {
if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql
return obj !== 0 || 1 / obj === 1 / ref; // -0 / +0
}
options = options || { prototype: true };
const type = typeof obj;
if (type !== typeof ref) {
return false;
}
if (type !== 'object' ||
obj === null ||
ref === null) {
return obj !== obj && ref !== ref; // NaN
}
seen = seen || [];
if (seen.indexOf(obj) !== -1) {
return true; // If previous comparison failed, it would have stopped execution
}
seen.push(obj);
if (Array.isArray(obj)) {
if (!Array.isArray(ref)) {
return false;
}
if (!options.part && obj.length !== ref.length) {
return false;
}
for (let i = 0; i < obj.length; ++i) {
if (options.part) {
let found = false;
for (let j = 0; j < ref.length; ++j) {
if (exports.deepEqual(obj[i], ref[j], options)) {
found = true;
break;
}
}
return found;
}
if (!exports.deepEqual(obj[i], ref[i], options)) {
return false;
}
}
return true;
}
if (Buffer.isBuffer(obj)) {
if (!Buffer.isBuffer(ref)) {
return false;
}
if (obj.length !== ref.length) {
return false;
}
for (let i = 0; i < obj.length; ++i) {
if (obj[i] !== ref[i]) {
return false;
}
}
return true;
}
if (obj instanceof Date) {
return (ref instanceof Date && obj.getTime() === ref.getTime());
}
if (obj instanceof RegExp) {
return (ref instanceof RegExp && obj.toString() === ref.toString());
}
if (options.prototype) {
if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) {
return false;
}
}
const keys = Object.getOwnPropertyNames(obj);
if (!options.part && keys.length !== Object.getOwnPropertyNames(ref).length) {
return false;
}
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor.get) {
if (!exports.deepEqual(descriptor, Object.getOwnPropertyDescriptor(ref, key), options, seen)) {
return false;
}
}
else if (!exports.deepEqual(obj[key], ref[key], options, seen)) {
return false;
}
}
return true;
};
// Remove duplicate items from array
exports.unique = (array, key) => {
let result;
if (key) {
result = [];
const index = new Set();
array.forEach((item) => {
const identifier = item[key];
if (!index.has(identifier)) {
index.add(identifier);
result.push(item);
}
});
}
else {
result = Array.from(new Set(array));
}
return result;
};
// Convert array into object
exports.mapToObject = function (array, key) {
if (!array) {
return null;
}
const obj = {};
for (let i = 0; i < array.length; ++i) {
if (key) {
if (array[i][key]) {
obj[array[i][key]] = true;
}
}
else {
obj[array[i]] = true;
}
}
return obj;
};
// Find the common unique items in two arrays
exports.intersect = function (array1, array2, justFirst) {
if (!array1 || !array2) {
return [];
}
const common = [];
const hash = (Array.isArray(array1) ? exports.mapToObject(array1) : array1);
const found = {};
for (let i = 0; i < array2.length; ++i) {
if (hash[array2[i]] && !found[array2[i]]) {
if (justFirst) {
return array2[i];
}
common.push(array2[i]);
found[array2[i]] = true;
}
}
return (justFirst ? null : common);
};
// Test if the reference contains the values
exports.contain = function (ref, values, options) {
/*
string -> string(s)
array -> item(s)
object -> key(s)
object -> object (key:value)
*/
let valuePairs = null;
if (typeof ref === 'object' &&
typeof values === 'object' &&
!Array.isArray(ref) &&
!Array.isArray(values)) {
valuePairs = values;
values = Object.keys(values);
}
else {
values = [].concat(values);
}
options = options || {}; // deep, once, only, part
exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object');
exports.assert(values.length, 'Values array cannot be empty');
let compare;
let compareFlags;
if (options.deep) {
compare = exports.deepEqual;
const hasOnly = options.hasOwnProperty('only');
const hasPart = options.hasOwnProperty('part');
compareFlags = {
prototype: hasOnly ? options.only : hasPart ? !options.part : false,
part: hasOnly ? !options.only : hasPart ? options.part : true
};
}
else {
compare = (a, b) => a === b;
}
let misses = false;
const matches = new Array(values.length);
for (let i = 0; i < matches.length; ++i) {
matches[i] = 0;
}
if (typeof ref === 'string') {
let pattern = '(';
for (let i = 0; i < values.length; ++i) {
const value = values[i];
exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value');
pattern += (i ? '|' : '') + exports.escapeRegex(value);
}
const regex = new RegExp(pattern + ')', 'g');
const leftovers = ref.replace(regex, ($0, $1) => {
const index = values.indexOf($1);
++matches[index];
return ''; // Remove from string
});
misses = !!leftovers;
}
else if (Array.isArray(ref)) {
for (let i = 0; i < ref.length; ++i) {
let matched = false;
for (let j = 0; j < values.length && matched === false; ++j) {
matched = compare(values[j], ref[i], compareFlags) && j;
}
if (matched !== false) {
++matches[matched];
}
else {
misses = true;
}
}
}
else {
const keys = Object.getOwnPropertyNames(ref);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const pos = values.indexOf(key);
if (pos !== -1) {
if (valuePairs &&
!compare(valuePairs[key], ref[key], compareFlags)) {
return false;
}
++matches[pos];
}
else {
misses = true;
}
}
}
let result = false;
for (let i = 0; i < matches.length; ++i) {
result = result || !!matches[i];
if ((options.once && matches[i] > 1) ||
(!options.part && !matches[i])) {
return false;
}
}
if (options.only &&
misses) {
return false;
}
return result;
};
// Flatten array
exports.flatten = function (array, target) {
const result = target || [];
for (let i = 0; i < array.length; ++i) {
if (Array.isArray(array[i])) {
exports.flatten(array[i], result);
}
else {
result.push(array[i]);
}
}
return result;
};
// Convert an object key chain string ('a.b.c') to reference (object[a][b][c])
exports.reach = function (obj, chain, options) {
if (chain === false ||
chain === null ||
typeof chain === 'undefined') {
return obj;
}
options = options || {};
if (typeof options === 'string') {
options = { separator: options };
}
const path = chain.split(options.separator || '.');
let ref = obj;
for (let i = 0; i < path.length; ++i) {
let key = path[i];
if (key[0] === '-' && Array.isArray(ref)) {
key = key.slice(1, key.length);
key = ref.length - key;
}
if (!ref ||
!((typeof ref === 'object' || typeof ref === 'function') && key in ref) ||
(typeof ref !== 'object' && options.functions === false)) { // Only object and function can have properties
exports.assert(!options.strict || i + 1 === path.length, 'Missing segment', key, 'in reach path ', chain);
exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
ref = options.default;
break;
}
ref = ref[key];
}
return ref;
};
exports.reachTemplate = function (obj, template, options) {
return template.replace(/{([^}]+)}/g, ($0, chain) => {
const value = exports.reach(obj, chain, options);
return (value === undefined || value === null ? '' : value);
});
};
exports.formatStack = function (stack) {
const trace = [];
for (let i = 0; i < stack.length; ++i) {
const item = stack[i];
trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]);
}
return trace;
};
exports.formatTrace = function (trace) {
const display = [];
for (let i = 0; i < trace.length; ++i) {
const row = trace[i];
display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')');
}
return display;
};
exports.callStack = function (slice) {
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
const v8 = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) {
return stack;
};
const capture = {};
Error.captureStackTrace(capture, this);
const stack = capture.stack;
Error.prepareStackTrace = v8;
const trace = exports.formatStack(stack);
return trace.slice(1 + slice);
};
exports.displayStack = function (slice) {
const trace = exports.callStack(slice === undefined ? 1 : slice + 1);
return exports.formatTrace(trace);
};
exports.abortThrow = false;
exports.abort = function (message, hideStack) {
if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) {
throw new Error(message || 'Unknown error');
}
let stack = '';
if (!hideStack) {
stack = exports.displayStack(1).join('\n\t');
}
console.log('ABORT: ' + message + '\n\t' + stack);
process.exit(1);
};
exports.assert = function (condition, ...args) {
if (condition) {
return;
}
if (args.length === 1 && args[0] instanceof Error) {
throw args[0];
}
const msgs = args
.filter((arg) => arg !== '')
.map((arg) => {
return typeof arg === 'string' ? arg : arg instanceof Error ? arg.message : exports.stringify(arg);
});
throw new Assert.AssertionError({
message: msgs.join(' ') || 'Unknown error',
actual: false,
expected: true,
operator: '==',
stackStartFunction: exports.assert
});
};
exports.Bench = function () {
this.ts = 0;
this.reset();
};
exports.Bench.prototype.reset = function () {
this.ts = exports.Bench.now();
};
exports.Bench.prototype.elapsed = function () {
return exports.Bench.now() - this.ts;
};
exports.Bench.now = function () {
const ts = process.hrtime();
return (ts[0] * 1e3) + (ts[1] / 1e6);
};
// Escape string for Regex construction
exports.escapeRegex = function (string) {
// Escape ^$.*+-?=!:|\/()[]{},
return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
};
// Base64url (RFC 4648) encode
exports.base64urlEncode = function (value, encoding) {
exports.assert(typeof value === 'string' || Buffer.isBuffer(value), 'value must be string or buffer');
const buf = (Buffer.isBuffer(value) ? value : Buffer.from(value, encoding || 'binary'));
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
};
// Base64url (RFC 4648) decode
exports.base64urlDecode = function (value, encoding) {
if (typeof value !== 'string') {
throw new Error('Value not a string');
}
if (!/^[\w\-]*$/.test(value)) {
throw new Error('Invalid character');
}
const buf = Buffer.from(value, 'base64');
return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary'));
};
// Escape attribute value for use in HTTP header
exports.escapeHeaderAttribute = function (attribute) {
// Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "
exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')');
return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash
};
exports.escapeHtml = function (string) {
return Escape.escapeHtml(string);
};
exports.escapeJavaScript = function (string) {
return Escape.escapeJavaScript(string);
};
exports.escapeJson = function (string) {
return Escape.escapeJson(string);
};
exports.once = function (method) {
if (method._hoekOnce) {
return method;
}
let once = false;
const wrapped = function (...args) {
if (!once) {
once = true;
method.apply(null, args);
}
};
wrapped._hoekOnce = true;
return wrapped;
};
exports.isInteger = Number.isSafeInteger;
exports.ignore = function () { };
exports.inherits = Util.inherits;
exports.format = Util.format;
exports.transform = function (source, transform, options) {
exports.assert(source === null || source === undefined || typeof source === 'object' || Array.isArray(source), 'Invalid source object: must be null, undefined, an object, or an array');
const separator = (typeof options === 'object' && options !== null) ? (options.separator || '.') : '.';
if (Array.isArray(source)) {
const results = [];
for (let i = 0; i < source.length; ++i) {
results.push(exports.transform(source[i], transform, options));
}
return results;
}
const result = {};
const keys = Object.keys(transform);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const path = key.split(separator);
const sourcePath = transform[key];
exports.assert(typeof sourcePath === 'string', 'All mappings must be "." delineated strings');
let segment;
let res = result;
while (path.length > 1) {
segment = path.shift();
if (!res[segment]) {
res[segment] = {};
}
res = res[segment];
}
segment = path.shift();
res[segment] = exports.reach(source, sourcePath, options);
}
return result;
};
exports.uniqueFilename = function (path, extension) {
if (extension) {
extension = extension[0] !== '.' ? '.' + extension : extension;
}
else {
extension = '';
}
path = Path.resolve(path);
const name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension;
return Path.join(path, name);
};
exports.stringify = function (...args) {
try {
return JSON.stringify.apply(null, args);
}
catch (err) {
return '[Cannot display object: ' + err.message + ']';
}
};
exports.shallow = function (source) {
return Object.assign({}, source);
};
exports.wait = function (timeout) {
return new Promise((resolve) => setTimeout(resolve, timeout));
};
exports.block = function () {
return new Promise(exports.ignore);
};

55
node_modules/joi/node_modules/hoek/package.json generated vendored Normal file
View File

@ -0,0 +1,55 @@
{
"_from": "hoek@5.x.x",
"_id": "hoek@5.0.4",
"_inBundle": false,
"_integrity": "sha512-Alr4ZQgoMlnere5FZJsIyfIjORBqZll5POhDsF4q64dPuJR6rNxXdDxtHSQq8OXRurhmx+PWYEE8bXRROY8h0w==",
"_location": "/joi/hoek",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "hoek@5.x.x",
"name": "hoek",
"escapedName": "hoek",
"rawSpec": "5.x.x",
"saveSpec": null,
"fetchSpec": "5.x.x"
},
"_requiredBy": [
"/joi"
],
"_resolved": "https://registry.npmjs.org/hoek/-/hoek-5.0.4.tgz",
"_shasum": "0f7fa270a1cafeb364a4b2ddfaa33f864e4157da",
"_spec": "hoek@5.x.x",
"_where": "/var/www/html/gtg2nodejs/node_modules/joi",
"bugs": {
"url": "https://github.com/hapijs/hoek/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": "This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).",
"description": "General purpose node utilities",
"devDependencies": {
"code": "5.x.x",
"lab": "15.x.x"
},
"engines": {
"node": ">=8.9.0"
},
"homepage": "https://github.com/hapijs/hoek#readme",
"keywords": [
"utilities"
],
"license": "BSD-3-Clause",
"main": "lib/index.js",
"name": "hoek",
"repository": {
"type": "git",
"url": "git://github.com/hapijs/hoek.git"
},
"scripts": {
"test": "lab -a code -t 100 -L",
"test-cov-html": "lab -a code -t 100 -L -r html -o coverage.html"
},
"version": "5.0.4"
}

65
node_modules/joi/package.json generated vendored Normal file
View File

@ -0,0 +1,65 @@
{
"_from": "joi@^13.1.2",
"_id": "joi@13.7.0",
"_inBundle": false,
"_integrity": "sha512-xuY5VkHfeOYK3Hdi91ulocfuFopwgbSORmIwzcwHKESQhC7w1kD5jaVSPnqDxS2I8t3RZ9omCKAxNwXN5zG1/Q==",
"_location": "/joi",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "joi@^13.1.2",
"name": "joi",
"escapedName": "joi",
"rawSpec": "^13.1.2",
"saveSpec": null,
"fetchSpec": "^13.1.2"
},
"_requiredBy": [
"/xml2json"
],
"_resolved": "https://registry.npmjs.org/joi/-/joi-13.7.0.tgz",
"_shasum": "cfd85ebfe67e8a1900432400b4d03bbd93fb879f",
"_spec": "joi@^13.1.2",
"_where": "/var/www/html/gtg2nodejs/node_modules/xml2json",
"bugs": {
"url": "https://github.com/hapijs/joi/issues"
},
"bundleDependencies": false,
"dependencies": {
"hoek": "5.x.x",
"isemail": "3.x.x",
"topo": "3.x.x"
},
"deprecated": "This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).",
"description": "Object schema validation",
"devDependencies": {
"code": "5.x.x",
"hapitoc": "1.x.x",
"lab": "15.x.x"
},
"engines": {
"node": ">=8.9.0"
},
"homepage": "https://github.com/hapijs/joi",
"keywords": [
"hapi",
"schema",
"validation"
],
"license": "BSD-3-Clause",
"main": "lib/index.js",
"name": "joi",
"repository": {
"type": "git",
"url": "git://github.com/hapijs/joi.git"
},
"scripts": {
"test": "lab -t 100 -a code -L",
"test-cov-html": "lab -r html -o coverage.html -a code",
"test-debug": "lab -a code",
"toc": "hapitoc",
"version": "npm run toc && git add API.md README.md"
},
"version": "13.7.0"
}

537
node_modules/nan/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,537 @@
# NAN ChangeLog
**Version 2.14.2: current Node 14.13.1, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1**
### 2.14.2 Oct 13 2020
- Bugfix: fix gcc 8 function cast warning (#899) 35f0fab205574b2cbda04e6347c8b2db755e124f
### 2.14.1 Apr 21 2020
- Bugfix: use GetBackingStore() instead of GetContents() (#888) 2c023bd447661a61071da318b0ff4003c3858d39
### 2.14.0 May 16 2019
- Feature: Add missing methods to Nan::Maybe<T> (#852) 4e962489fb84a184035b9fa74f245f650249aca6
### 2.13.2 Mar 24 2019
- Bugfix: remove usage of deprecated `IsNearDeath` (#842) fbaf42252af279c3d867c6b193571f9711c39847
### 2.13.1 Mar 14 2019
- Bugfix: check V8 version directly instead of inferring from NMV (#840) 12f9df9f393285de8fb4a8cd01478dc4fe3b089d
### 2.13.0 Mar 13 2019
- Feature: add support for node master (#831) 113c0282072e7ff4f9dfc98b432fd894b798c2c
### 2.12.1 Dec 18 2018
- Bugfix: Fix build breakage with Node.js 10.0.0-10.9.0. (#833) 625e90e8fef8d39ffa7247250a76a100b2487474
### 2.12.0 Dec 16 2018
- Bugfix: Add scope.Escape() to Call() (#817) 2e5ed4fc3a8ac80a6ef1f2a55099ab3ac8800dc6
- Bugfix: Fix Node.js v10.12.0 deprecation warnings. 509859cc23b1770376b56550a027840a2ce0f73d
- Feature: Allow SetWeak() for non-object persistent handles. (#824) e6ef6a48e7e671fe3e4b7dddaa8912a3f8262ecd
### 2.11.1 Sep 29 2018
- Fix: adapt to V8 7.0 24a22c3b25eeeec2016c6ec239bdd6169e985447
### 2.11.0 Aug 25 2018
- Removal: remove `FunctionCallbackInfo::Callee` for nodejs `>= 10` 1a56c0a6efd4fac944cb46c30912a8e023bda7d4
- Bugfix: Fix `AsyncProgressWorkerBase::WorkProgress` sends invalid data b0c764d1dab11e9f8b37ffb81e2560a4498aad5e
- Feature: Introduce `GetCurrentEventLoop` b4911b0bb1f6d47d860e10ec014d941c51efac5e
- Feature: Add `NAN_MODULE_WORKER_ENABLED` macro as a replacement for `NAN_MODULE` b058fb047d18a58250e66ae831444441c1f2ac7a
### 2.10.0 Mar 16 2018
- Deprecation: Deprecate `MakeCallback` 5e92b19a59e194241d6a658bd6ff7bfbda372950
- Feature: add `Nan::Call` overload 4482e1242fe124d166fc1a5b2be3c1cc849fe452
- Feature: add more `Nan::Call` overloads 8584e63e6d04c7d2eb8c4a664e4ef57d70bf672b
- Feature: Fix deprecation warnings for Node 10 1caf258243b0602ed56922bde74f1c91b0cbcb6a
### 2.9.2 Feb 22 2018
- Bugfix: Bandaid for async hooks 212bd2f849be14ef1b02fc85010b053daa24252b
### 2.9.1 Feb 22 2018
- Bugfix: Avoid deprecation warnings in deprecated `Nan::Callback::operator()` 372b14d91289df4604b0f81780709708c45a9aa4
- Bugfix: Avoid deprecation warnings in `Nan::JSON` 3bc294bce0b7d0a3ee4559926303e5ed4866fda2
### 2.9.0 Feb 22 2018
- Deprecation: Deprecate legacy `Callback::Call` 6dd5fa690af61ca3523004b433304c581b3ea309
- Feature: introduce `AsyncResource` class 90c0a179c0d8cb5fd26f1a7d2b1d6231eb402d48o
- Feature: Add context aware `Nan::Callback::Call` functions 7169e09fb088418b6e388222e88b4c13f07ebaee
- Feature: Make `AsyncWorker` context aware 066ba21a6fb9e2b5230c9ed3a6fc51f1211736a4
- Feature: add `Callback` overload to `Nan::Call` 5328daf66e202658c1dc0d916c3aaba99b3cc606
- Bugfix: fix warning: suggest parentheses around `&&` within `||` b2bb63d68b8ae623a526b542764e1ac82319cb2c
- Bugfix: Fix compilation on io.js 3 d06114dba0a522fb436f0c5f47b994210968cd7b
### 2.8.0 Nov 15 2017
- Deprecation: Deprecate `Nan::ForceSet` in favor of `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
- Feature: Add `Nan::AsyncProgressQueueWorker` a976636ecc2ef617d1b061ce4a6edf39923691cb
- Feature: Add `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
- Bugfix: Fix compiling on io.js 1 & 2 82705a64503ce60c62e98df5bd02972bba090900
- Bugfix: Use DefineOwnProperty instead of ForceSet 95cbb976d6fbbba88ba0f86dd188223a8591b4e7
### 2.7.0 Aug 30 2017
- Feature: Add `Nan::To<v8::Function>()` overload. b93280670c9f6da42ed4cf6cbf085ffdd87bd65b
- Bugfix: Fix ternary in `Nan::MaybeLocal<T>::FromMaybe<S>()`. 79a26f7d362e756a9524e672a82c3d603b542867
### 2.6.2 Apr 12 2017
- Bugfix: Fix v8::JSON::Parse() deprecation warning. 87f6a3c65815fa062296a994cc863e2fa124867d
### 2.6.1 Apr 6 2017
- Bugfix: nan_json.h: fix build breakage in Node 6 ac8d47dc3c10bfbf3f15a6b951633120c0ee6d51
### 2.6.0 Apr 6 2017
- Feature: nan: add support for JSON::Parse & Stringify b533226c629cce70e1932a873bb6f849044a56c5
### 2.5.1 Jan 23 2017
- Bugfix: Fix disappearing handle for private value 6a80995694f162ef63dbc9948fbefd45d4485aa0
- Bugfix: Add missing scopes a93b8bae6bc7d32a170db6e89228b7f60ee57112
- Bugfix: Use string::data instead of string::front in NewOneByteString d5f920371e67e1f3b268295daee6e83af86b6e50
### 2.5.0 Dec 21 2016
- Feature: Support Private accessors a86255cb357e8ad8ccbf1f6a4a901c921e39a178
- Bugfix: Abort in delete operators that shouldn't be called 0fe38215ff8581703967dfd26c12793feb960018
### 2.4.0 Jul 10 2016
- Feature: Rewrite Callback to add Callback::Reset c4cf44d61f8275cd5f7b0c911d7a806d4004f649
- Feature: AsyncProgressWorker: add template types for .send 1242c9a11a7ed481c8f08ec06316385cacc513d0
- Bugfix: Add constness to old Persistent comparison operators bd43cb9982c7639605d60fd073efe8cae165d9b2
### 2.3.5 May 31 2016
- Bugfix: Replace NAN_INLINE with 'inline' keyword. 71819d8725f822990f439479c9aba3b240804909
### 2.3.4 May 31 2016
- Bugfix: Remove V8 deprecation warnings 0592fb0a47f3a1c7763087ebea8e1138829f24f9
- Bugfix: Fix new versions not to use WeakCallbackInfo::IsFirstPass 615c19d9e03d4be2049c10db0151edbc3b229246
- Bugfix: Make ObjectWrap::handle() const d19af99595587fe7a26bd850af6595c2a7145afc
- Bugfix: Fix compilation errors related to 0592fb0a47f3a1c7763087ebea8e1138829f24f9 e9191c525b94f652718325e28610a1adcf90fed8
### 2.3.3 May 4 2016
- Bugfix: Refactor SetMethod() to deal with v8::Templates (#566) b9083cf6d5de6ebe6bcb49c7502fbb7c0d9ddda8
### 2.3.2 Apr 27 2016
- Bugfix: Fix compilation on outdated versions due to Handle removal f8b7c875d04d425a41dfd4f3f8345bc3a11e6c52
### 2.3.1 Apr 27 2016
- Bugfix: Don't use deprecated v8::Template::Set() in SetMethod a90951e9ea70fa1b3836af4b925322919159100e
### 2.3.0 Apr 27 2016
- Feature: added Signal() for invoking async callbacks without sending data from AsyncProgressWorker d8adba45f20e077d00561b20199133620c990b38
- Bugfix: Don't use deprecated v8::Template::Set() 00dacf0a4b86027415867fa7f1059acc499dcece
### 2.2.1 Mar 29 2016
- Bugfix: Use NewFromUnsigned in ReturnValue<T>::Set(uint32_t i) for pre_12 3a18f9bdce29826e0e4c217854bc476918241a58
- Performance: Remove unneeeded nullptr checks b715ef44887931c94f0d1605b3b1a4156eebece9
### 2.2.0 Jan 9 2016
- Feature: Add Function::Call wrapper 4c157474dacf284d125c324177b45aa5dabc08c6
- Feature: Rename GC*logueCallback to GCCallback for > 4.0 3603435109f981606d300eb88004ca101283acec
- Bugfix: Fix Global::Pass for old versions 367e82a60fbaa52716232cc89db1cc3f685d77d9
- Bugfix: Remove weird MaybeLocal wrapping of what already is a MaybeLocal 23b4590db10c2ba66aee2338aebe9751c4cb190b
### 2.1.0 Oct 8 2015
- Deprecation: Deprecate NanErrnoException in favor of ErrnoException 0af1ca4cf8b3f0f65ed31bc63a663ab3319da55c
- Feature: added helper class for accessing contents of typedarrays 17b51294c801e534479d5463697a73462d0ca555
- Feature: [Maybe types] Add MakeMaybe(...) 48d7b53d9702b0c7a060e69ea10fea8fb48d814d
- Feature: new: allow utf16 string with length 66ac6e65c8ab9394ef588adfc59131b3b9d8347b
- Feature: Introduce SetCallHandler and SetCallAsFunctionHandler 7764a9a115d60ba10dc24d86feb0fbc9b4f75537
- Bugfix: Enable creating Locals from Globals under Node 0.10. 9bf9b8b190821af889790fdc18ace57257e4f9ff
- Bugfix: Fix issue #462 where PropertyCallbackInfo data is not stored safely. 55f50adedd543098526c7b9f4fffd607d3f9861f
### 2.0.9 Sep 8 2015
- Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7
### 2.0.8 Aug 28 2015
- Work around duplicate linking bug in clang 11902da
### 2.0.7 Aug 26 2015
- Build: Repackage
### 2.0.6 Aug 26 2015
- Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1
- Bugfix: Remove unused static std::map instances 525bddc
- Bugfix: Make better use of maybe versions of APIs bfba85b
- Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d
### 2.0.5 Aug 10 2015
- Bugfix: Reimplement weak callback in ObjectWrap 98d38c1
- Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d
### 2.0.4 Aug 6 2015
- Build: Repackage
### 2.0.3 Aug 6 2015
- Bugfix: Don't use clang++ / g++ syntax extension. 231450e
### 2.0.2 Aug 6 2015
- Build: Repackage
### 2.0.1 Aug 6 2015
- Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687
- Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601
- Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f
- Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed
### 2.0.0 Jul 31 2015
- Change: Renamed identifiers with leading underscores b5932b4
- Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1
- Change: Replace NanScope and NanEscpableScope macros with classes 47751c4
- Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99
- Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5
- Change: Rename NanNewBuffer to NanCopyBuffer d6af78d
- Change: Remove Nan prefix from all names 72d1f67
- Change: Update Buffer API for new upstream changes d5d3291
- Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a
- Change: Get rid of Handles e6c0daf
- Feature: Support io.js 3 with V8 4.4
- Feature: Introduce NanPersistent 7fed696
- Feature: Introduce NanGlobal 4408da1
- Feature: Added NanTryCatch 10f1ca4
- Feature: Update for V8 v4.3 4b6404a
- Feature: Introduce NanNewOneByteString c543d32
- Feature: Introduce namespace Nan 67ed1b1
- Removal: Remove NanLocker and NanUnlocker dd6e401
- Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9
- Removal: Remove NanReturn* macros d90a25c
- Removal: Remove HasInstance e8f84fe
### 1.9.0 Jul 31 2015
- Feature: Added `NanFatalException` 81d4a2c
- Feature: Added more error types 4265f06
- Feature: Added dereference and function call operators to NanCallback c4b2ed0
- Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c
- Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6
- Feature: Added NanErrnoException dd87d9e
- Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130
- Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c
- Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b
### 1.8.4 Apr 26 2015
- Build: Repackage
### 1.8.3 Apr 26 2015
- Bugfix: Include missing header 1af8648
### 1.8.2 Apr 23 2015
- Build: Repackage
### 1.8.1 Apr 23 2015
- Bugfix: NanObjectWrapHandle should take a pointer 155f1d3
### 1.8.0 Apr 23 2015
- Feature: Allow primitives with NanReturnValue 2e4475e
- Feature: Added comparison operators to NanCallback 55b075e
- Feature: Backport thread local storage 15bb7fa
- Removal: Remove support for signatures with arguments 8a2069d
- Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59
### 1.7.0 Feb 28 2015
- Feature: Made NanCallback::Call accept optional target 8d54da7
- Feature: Support atom-shell 0.21 0b7f1bb
### 1.6.2 Feb 6 2015
- Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639
### 1.6.1 Jan 23 2015
- Build: version bump
### 1.5.3 Jan 23 2015
- Build: repackage
### 1.6.0 Jan 23 2015
- Deprecated `NanNewContextHandle` in favor of `NanNew<Context>` 49259af
- Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179
- Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9
### 1.5.2 Jan 23 2015
- Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4
- Bugfix: Readded missing String constructors 18d828f
- Bugfix: Add overload handling NanNew<FunctionTemplate>(..) 5ef813b
- Bugfix: Fix uv_work_cb versioning 997e4ae
- Bugfix: Add function factory and test 4eca89c
- Bugfix: Add object template factory and test cdcb951
- Correctness: Lifted an io.js related typedef c9490be
- Correctness: Make explicit downcasts of String lengths 00074e6
- Windows: Limit the scope of disabled warning C4530 83d7deb
### 1.5.1 Jan 15 2015
- Build: version bump
### 1.4.3 Jan 15 2015
- Build: version bump
### 1.4.2 Jan 15 2015
- Feature: Support io.js 0dbc5e8
### 1.5.0 Jan 14 2015
- Feature: Support io.js b003843
- Correctness: Improved NanNew internals 9cd4f6a
- Feature: Implement progress to NanAsyncWorker 8d6a160
### 1.4.1 Nov 8 2014
- Bugfix: Handle DEBUG definition correctly
- Bugfix: Accept int as Boolean
### 1.4.0 Nov 1 2014
- Feature: Added NAN_GC_CALLBACK 6a5c245
- Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8
- Correctness: Added constness to references in NanHasInstance 02c61cd
- Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6
- Windoze: Shut Visual Studio up when compiling 8d558c1
- License: Switch to plain MIT from custom hacked MIT license 11de983
- Build: Added test target to Makefile e232e46
- Performance: Removed superfluous scope in NanAsyncWorker f4b7821
- Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208
- Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450
### 1.3.0 Aug 2 2014
- Added NanNew<v8::String, std::string>(std::string)
- Added NanNew<v8::String, std::string&>(std::string&)
- Added NanAsciiString helper class
- Added NanUtf8String helper class
- Added NanUcs2String helper class
- Deprecated NanRawString()
- Deprecated NanCString()
- Added NanGetIsolateData(v8::Isolate *isolate)
- Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::Function> func, int argc, v8::Handle<v8::Value>* argv)
- Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::String> symbol, int argc, v8::Handle<v8::Value>* argv)
- Added NanMakeCallback(v8::Handle<v8::Object> target, const char* method, int argc, v8::Handle<v8::Value>* argv)
- Added NanSetTemplate(v8::Handle<v8::Template> templ, v8::Handle<v8::String> name , v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
- Added NanSetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
- Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, const char *name, v8::Handle<v8::Data> value)
- Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes)
### 1.2.0 Jun 5 2014
- Add NanSetPrototypeTemplate
- Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class,
introduced _NanWeakCallbackDispatcher
- Removed -Wno-unused-local-typedefs from test builds
- Made test builds Windows compatible ('Sleep()')
### 1.1.2 May 28 2014
- Release to fix more stuff-ups in 1.1.1
### 1.1.1 May 28 2014
- Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0
### 1.1.0 May 25 2014
- Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead
- Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]),
(uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*,
v8::String::ExternalAsciiStringResource*
- Deprecate NanSymbol()
- Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker
### 1.0.0 May 4 2014
- Heavy API changes for V8 3.25 / Node 0.11.13
- Use cpplint.py
- Removed NanInitPersistent
- Removed NanPersistentToLocal
- Removed NanFromV8String
- Removed NanMakeWeak
- Removed NanNewLocal
- Removed NAN_WEAK_CALLBACK_OBJECT
- Removed NAN_WEAK_CALLBACK_DATA
- Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions
- Introduce NanUndefined, NanNull, NanTrue and NanFalse
- Introduce NanEscapableScope and NanEscapeScope
- Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node)
- Introduce NanMakeCallback for node::MakeCallback
- Introduce NanSetTemplate
- Introduce NanGetCurrentContext
- Introduce NanCompileScript and NanRunScript
- Introduce NanAdjustExternalMemory
- Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback
- Introduce NanGetHeapStatistics
- Rename NanAsyncWorker#SavePersistent() to SaveToPersistent()
### 0.8.0 Jan 9 2014
- NanDispose -> NanDisposePersistent, deprecate NanDispose
- Extract _NAN_*_RETURN_TYPE, pull up NAN_*()
### 0.7.1 Jan 9 2014
- Fixes to work against debug builds of Node
- Safer NanPersistentToLocal (avoid reinterpret_cast)
- Speed up common NanRawString case by only extracting flattened string when necessary
### 0.7.0 Dec 17 2013
- New no-arg form of NanCallback() constructor.
- NanCallback#Call takes Handle rather than Local
- Removed deprecated NanCallback#Run method, use NanCallback#Call instead
- Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS
- Restore (unofficial) Node 0.6 compatibility at NanCallback#Call()
- Introduce NanRawString() for char* (or appropriate void*) from v8::String
(replacement for NanFromV8String)
- Introduce NanCString() for null-terminated char* from v8::String
### 0.6.0 Nov 21 2013
- Introduce NanNewLocal<T>(v8::Handle<T> value) for use in place of
v8::Local<T>::New(...) since v8 started requiring isolate in Node 0.11.9
### 0.5.2 Nov 16 2013
- Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public
### 0.5.1 Nov 12 2013
- Use node::MakeCallback() instead of direct v8::Function::Call()
### 0.5.0 Nov 11 2013
- Added @TooTallNate as collaborator
- New, much simpler, "include_dirs" for binding.gyp
- Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros
### 0.4.4 Nov 2 2013
- Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+
### 0.4.3 Nov 2 2013
- Include node_object_wrap.h, removed from node.h for Node 0.11.8.
### 0.4.2 Nov 2 2013
- Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for
Node 0.11.8 release.
### 0.4.1 Sep 16 2013
- Added explicit `#include <uv.h>` as it was removed from node.h for v0.11.8
### 0.4.0 Sep 2 2013
- Added NAN_INLINE and NAN_DEPRECATED and made use of them
- Added NanError, NanTypeError and NanRangeError
- Cleaned up code
### 0.3.2 Aug 30 2013
- Fix missing scope declaration in GetFromPersistent() and SaveToPersistent
in NanAsyncWorker
### 0.3.1 Aug 20 2013
- fix "not all control paths return a value" compile warning on some platforms
### 0.3.0 Aug 19 2013
- Made NAN work with NPM
- Lots of fixes to NanFromV8String, pulling in features from new Node core
- Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API
- Added optional error number argument for NanThrowError()
- Added NanInitPersistent()
- Added NanReturnNull() and NanReturnEmptyString()
- Added NanLocker and NanUnlocker
- Added missing scopes
- Made sure to clear disposed Persistent handles
- Changed NanAsyncWorker to allocate error messages on the heap
- Changed NanThrowError(Local<Value>) to NanThrowError(Handle<Value>)
- Fixed leak in NanAsyncWorker when errmsg is used
### 0.2.2 Aug 5 2013
- Fixed usage of undefined variable with node::BASE64 in NanFromV8String()
### 0.2.1 Aug 5 2013
- Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for
NanFromV8String()
### 0.2.0 Aug 5 2013
- Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR,
NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY
- Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS,
_NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS,
_NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS,
_NAN_PROPERTY_QUERY_ARGS
- Added NanGetInternalFieldPointer, NanSetInternalFieldPointer
- Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT,
NAN_WEAK_CALLBACK_DATA, NanMakeWeak
- Renamed THROW_ERROR to _NAN_THROW_ERROR
- Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*)
- Added NanBufferUse(char*, uint32_t)
- Added NanNewContextHandle(v8::ExtensionConfiguration*,
v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Value>)
- Fixed broken NanCallback#GetFunction()
- Added optional encoding and size arguments to NanFromV8String()
- Added NanGetPointerSafe() and NanSetPointerSafe()
- Added initial test suite (to be expanded)
- Allow NanUInt32OptionValue to convert any Number object
### 0.1.0 Jul 21 2013
- Added `NAN_GETTER`, `NAN_SETTER`
- Added `NanThrowError` with single Local<Value> argument
- Added `NanNewBufferHandle` with single uint32_t argument
- Added `NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>)`
- Added `Local<Function> NanCallback#GetFunction()`
- Added `NanCallback#Call(int, Local<Value>[])`
- Deprecated `NanCallback#Run(int, Local<Value>[])` in favour of Call

13
node_modules/nan/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,13 @@
The MIT License (MIT)
=====================
Copyright (c) 2018 NAN contributors
-----------------------------------
*NAN contributors listed at <https://github.com/nodejs/nan#contributors>*
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.

455
node_modules/nan/README.md generated vendored Normal file
View File

@ -0,0 +1,455 @@
Native Abstractions for Node.js
===============================
**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 and 14.**
***Current version: 2.14.2***
*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)*
[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/)
[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](https://travis-ci.org/nodejs/nan)
[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan)
Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle.
This project also contains some helper utilities that make addon development a bit more pleasant.
* **[News & Updates](#news)**
* **[Usage](#usage)**
* **[Example](#example)**
* **[API](#api)**
* **[Tests](#tests)**
* **[Known issues](#issues)**
* **[Governance & Contributing](#governance)**
<a name="news"></a>
## News & Updates
<a name="usage"></a>
## Usage
Simply add **NAN** as a dependency in the *package.json* of your Node addon:
``` bash
$ npm install --save nan
```
Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files:
``` python
"include_dirs" : [
"<!(node -e \"require('nan')\")"
]
```
This works like a `-I<path-to-NAN>` when compiling your addon.
<a name="example"></a>
## Example
Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**.
Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality.
For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**.
Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon.
Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure.
<a name="api"></a>
## API
Additional to the NAN documentation below, please consult:
* [The V8 Getting Started * Guide](https://v8.dev/docs/embed)
* [V8 API Documentation](https://v8docs.nodesource.com/)
* [Node Add-on Documentation](https://nodejs.org/api/addons.html)
<!-- START API -->
### JavaScript-accessible methods
A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information.
In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
* **Method argument types**
- <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
- <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
- <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
* **Method declarations**
- <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a>
- <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a>
- <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
- <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a>
- <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a>
- <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
- <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a>
- <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a>
* Method and template helpers
- <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
- <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
- <a href="doc/methods.md#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a>
- <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
- <a href="doc/methods.md#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a>
- <a href="doc/methods.md#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a>
### Scopes
A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
- <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
- <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection).
### Persistent references
An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
- <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
- <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
- <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
- <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
- <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a>
- <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
- <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
### New
NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
- <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a>
- <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
- <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a>
- <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a>
- <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a>
- <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
### Converters
NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
- <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a>
### Maybe Types
The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
* **Maybe Types**
- <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
- <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
- <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
- <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a>
* **Maybe Helpers**
- <a href="doc/maybe_types.md#api_nan_call"><b><code>Nan::Call()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a>
- <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a>
- <a href="doc/maybe_types.md#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a>
### Script
NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
- <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
- <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
### JSON
The _JSON_ object provides the C++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object.
- <a href="doc/json.md#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a>
- <a href="doc/json.md#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a>
Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments.
### Errors
NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
Note that an Error object is simply a specialized form of `v8::Value`.
Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
- <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a>
- <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
- <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
- <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
- <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
- <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
- <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
- <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
- <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
### Buffers
NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
- <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
- <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
- <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
### Nan::Callback
`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
- <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a>
### Asynchronous work helpers
`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier.
- <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a>
- <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
### Strings & Bytes
Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
- <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
- <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
- <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
### Object Wrappers
The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects.
- <a href="doc/object_wrappers.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
### V8 internals
The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
- <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
- <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
### Miscellaneous V8 Helpers
- <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
- <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
- <a href="doc/v8_misc.md#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a>
### Miscellaneous Node Helpers
- <a href="doc/node_misc.md#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a>
- <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
- <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
- <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a>
<!-- END API -->
<a name="tests"></a>
### Tests
To run the NAN tests do:
``` sh
npm install
npm run-script rebuild-tests
npm test
```
Or just:
``` sh
npm install
make test
```
<a name="issues"></a>
## Known issues
### Compiling against Node.js 0.12 on OSX
With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12
do not compile anymore. The error looks something like:
```
CXX(target) Release/obj.target/accessors/cpp/accessors.o
In file included from ../cpp/accessors.cpp:9:
In file included from ../../nan.h:51:
In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61:
/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope'
return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
~~~~~~~~~~~~~^~~~~~~~~~~~
```
This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make
`v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore
this patch cannot be released by either project in an official release.
For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support
that configuration, you will need to either get an older compiler, or apply a source patch to the version
of V8 headers as a workaround.
<a name="governance"></a>
## Governance & Contributing
NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api)
### Addon API Working Group (WG)
The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project.
Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects.
The WG has final authority over this project including:
* Technical direction
* Project governance and process (including this policy)
* Contribution policy
* GitHub repository hosting
* Maintaining the list of additional Collaborators
For the current list of WG members, see the project [README.md](./README.md#collaborators).
Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote.
_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly.
For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators).
### Consensus Seeking Process
The WG follows a [Consensus Seeking](https://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model.
Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification.
If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins.
<a id="developers-certificate-of-origin"></a>
## Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
* (a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
* (b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
* (c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
* (d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
<a name="collaborators"></a>
### WG Members / Collaborators
<table><tbody>
<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr>
<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr>
<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr>
<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr>
<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr>
<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr>
<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td><a href="http://twitter.com/agnat">Twitter/@agnat</a></td></tr>
<tr><th align="left">Michael Ira Krufky</th><td><a href="https://github.com/mkrufky">GitHub/mkrufky</a></td><td><a href="http://twitter.com/mkrufky">Twitter/@mkrufky</a></td></tr>
</tbody></table>
## Licence &amp; copyright
Copyright (c) 2018 NAN WG Members / Collaborators (listed above).
Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.

146
node_modules/nan/doc/asyncworker.md generated vendored Normal file
View File

@ -0,0 +1,146 @@
## Asynchronous work helpers
`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier.
- <a href="#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a>
- <a href="#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker</code></b></a>
- <a href="#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a>
- <a href="#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a>
<a name="api_nan_async_worker"></a>
### Nan::AsyncWorker
`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress.
This class internally handles the details of creating an [`AsyncResource`][AsyncResource], and running the callback in the
correct async context. To be able to identify the async resources created by this class in async-hooks, provide a
`resource_name` to the constructor. It is recommended that the module name be used as a prefix to the `resource_name` to avoid
collisions in the names. For more details see [`AsyncResource`][AsyncResource] documentation. The `resource_name` needs to stay valid for the lifetime of the worker instance.
Definition:
```c++
class AsyncWorker {
public:
explicit AsyncWorker(Callback *callback_, const char* resource_name = "nan:AsyncWorker");
virtual ~AsyncWorker();
virtual void WorkComplete();
void SaveToPersistent(const char *key, const v8::Local<v8::Value> &value);
void SaveToPersistent(const v8::Local<v8::String> &key,
const v8::Local<v8::Value> &value);
void SaveToPersistent(uint32_t index,
const v8::Local<v8::Value> &value);
v8::Local<v8::Value> GetFromPersistent(const char *key) const;
v8::Local<v8::Value> GetFromPersistent(const v8::Local<v8::String> &key) const;
v8::Local<v8::Value> GetFromPersistent(uint32_t index) const;
virtual void Execute() = 0;
uv_work_t request;
virtual void Destroy();
protected:
Persistent<v8::Object> persistentHandle;
Callback *callback;
virtual void HandleOKCallback();
virtual void HandleErrorCallback();
void SetErrorMessage(const char *msg);
const char* ErrorMessage();
};
```
<a name="api_nan_async_progress_worker"></a>
### Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker
`Nan::AsyncProgressWorkerBase` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript.
Previously the definition of `Nan::AsyncProgressWorker` only allowed sending `const char` data. Now extending `Nan::AsyncProgressWorker` will yield an instance of the implicit `Nan::AsyncProgressWorkerBase` template with type `<char>` for compatibility.
`Nan::AsyncProgressWorkerBase` &amp; `Nan::AsyncProgressWorker` is intended for best-effort delivery of nonessential progress messages, e.g. a progress bar. The last event sent before the main thread is woken will be delivered.
Definition:
```c++
template<class T>
class AsyncProgressWorkerBase<T> : public AsyncWorker {
public:
explicit AsyncProgressWorkerBase(Callback *callback_, const char* resource_name = ...);
virtual ~AsyncProgressWorkerBase();
void WorkProgress();
class ExecutionProgress {
public:
void Signal() const;
void Send(const T* data, size_t count) const;
};
virtual void Execute(const ExecutionProgress& progress) = 0;
virtual void HandleProgressCallback(const T *data, size_t count) = 0;
virtual void Destroy();
};
typedef AsyncProgressWorkerBase<T> AsyncProgressWorker;
```
<a name="api_nan_async_progress_queue_worker"></a>
### Nan::AsyncProgressQueueWorker
`Nan::AsyncProgressQueueWorker` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript.
`Nan::AsyncProgressQueueWorker` behaves exactly the same as `Nan::AsyncProgressWorker`, except all events are queued and delivered to the main thread.
Definition:
```c++
template<class T>
class AsyncProgressQueueWorker<T> : public AsyncWorker {
public:
explicit AsyncProgressQueueWorker(Callback *callback_, const char* resource_name = "nan:AsyncProgressQueueWorker");
virtual ~AsyncProgressQueueWorker();
void WorkProgress();
class ExecutionProgress {
public:
void Send(const T* data, size_t count) const;
};
virtual void Execute(const ExecutionProgress& progress) = 0;
virtual void HandleProgressCallback(const T *data, size_t count) = 0;
virtual void Destroy();
};
```
<a name="api_nan_async_queue_worker"></a>
### Nan::AsyncQueueWorker
`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`.
Definition:
```c++
void AsyncQueueWorker(AsyncWorker *);
```
[AsyncResource]: node_misc.md#api_nan_asyncresource

54
node_modules/nan/doc/buffers.md generated vendored Normal file
View File

@ -0,0 +1,54 @@
## Buffers
NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
- <a href="#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a>
- <a href="#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a>
- <a href="#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a>
<a name="api_nan_new_buffer"></a>
### Nan::NewBuffer()
Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`.
Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management.
When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`.
You _must not_ free the memory space manually once you have created a `Buffer` in this way.
Signature:
```c++
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(uint32_t size)
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size)
Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char *data,
size_t length,
Nan::FreeCallback callback,
void *hint)
```
<a name="api_nan_copy_buffer"></a>
### Nan::CopyBuffer()
Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`.
Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy.
Signature:
```c++
Nan::MaybeLocal<v8::Object> Nan::CopyBuffer(const char *data, uint32_t size)
```
<a name="api_nan_free_callback"></a>
### Nan::FreeCallback()
A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer).
The supplied callback will be invoked when the `Buffer` undergoes garbage collection.
Signature:
```c++
typedef void (*FreeCallback)(char *data, void *hint);
```

76
node_modules/nan/doc/callback.md generated vendored Normal file
View File

@ -0,0 +1,76 @@
## Nan::Callback
`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
- <a href="#api_nan_callback"><b><code>Nan::Callback</code></b></a>
<a name="api_nan_callback"></a>
### Nan::Callback
```c++
class Callback {
public:
Callback();
explicit Callback(const v8::Local<v8::Function> &fn);
~Callback();
bool operator==(const Callback &other) const;
bool operator!=(const Callback &other) const;
v8::Local<v8::Function> operator*() const;
MaybeLocal<v8::Value> operator()(AsyncResource* async_resource,
v8::Local<v8::Object> target,
int argc = 0,
v8::Local<v8::Value> argv[] = 0) const;
MaybeLocal<v8::Value> operator()(AsyncResource* async_resource,
int argc = 0,
v8::Local<v8::Value> argv[] = 0) const;
void SetFunction(const v8::Local<v8::Function> &fn);
v8::Local<v8::Function> GetFunction() const;
bool IsEmpty() const;
void Reset(const v8::Local<v8::Function> &fn);
void Reset();
MaybeLocal<v8::Value> Call(v8::Local<v8::Object> target,
int argc,
v8::Local<v8::Value> argv[],
AsyncResource* async_resource) const;
MaybeLocal<v8::Value> Call(int argc,
v8::Local<v8::Value> argv[],
AsyncResource* async_resource) const;
// Deprecated versions. Use the versions that accept an async_resource instead
// as they run the callback in the correct async context as specified by the
// resource. If you want to call a synchronous JS function (i.e. on a
// non-empty JS stack), you can use Nan::Call instead.
v8::Local<v8::Value> operator()(v8::Local<v8::Object> target,
int argc = 0,
v8::Local<v8::Value> argv[] = 0) const;
v8::Local<v8::Value> operator()(int argc = 0,
v8::Local<v8::Value> argv[] = 0) const;
v8::Local<v8::Value> Call(v8::Local<v8::Object> target,
int argc,
v8::Local<v8::Value> argv[]) const;
v8::Local<v8::Value> Call(int argc, v8::Local<v8::Value> argv[]) const;
};
```
Example usage:
```c++
v8::Local<v8::Function> function;
Nan::Callback callback(function);
callback.Call(0, 0);
```

41
node_modules/nan/doc/converters.md generated vendored Normal file
View File

@ -0,0 +1,41 @@
## Converters
NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN.
- <a href="#api_nan_to"><b><code>Nan::To()</code></b></a>
<a name="api_nan_to"></a>
### Nan::To()
Converts a `v8::Local<v8::Value>` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly.
See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types.
Signatures:
```c++
// V8 types
Nan::MaybeLocal<v8::Boolean> Nan::To<v8::Boolean>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Int32> Nan::To<v8::Int32>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Integer> Nan::To<v8::Integer>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Object> Nan::To<v8::Object>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Number> Nan::To<v8::Number>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::String> Nan::To<v8::String>(v8::Local<v8::Value> val);
Nan::MaybeLocal<v8::Uint32> Nan::To<v8::Uint32>(v8::Local<v8::Value> val);
// Native types
Nan::Maybe<bool> Nan::To<bool>(v8::Local<v8::Value> val);
Nan::Maybe<double> Nan::To<double>(v8::Local<v8::Value> val);
Nan::Maybe<int32_t> Nan::To<int32_t>(v8::Local<v8::Value> val);
Nan::Maybe<int64_t> Nan::To<int64_t>(v8::Local<v8::Value> val);
Nan::Maybe<uint32_t> Nan::To<uint32_t>(v8::Local<v8::Value> val);
```
### Example
```c++
v8::Local<v8::Value> val;
Nan::MaybeLocal<v8::String> str = Nan::To<v8::String>(val);
Nan::Maybe<double> d = Nan::To<double>(val);
```

226
node_modules/nan/doc/errors.md generated vendored Normal file
View File

@ -0,0 +1,226 @@
## Errors
NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted.
Note that an Error object is simply a specialized form of `v8::Value`.
Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information.
- <a href="#api_nan_error"><b><code>Nan::Error()</code></b></a>
- <a href="#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a>
- <a href="#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a>
- <a href="#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a>
- <a href="#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a>
- <a href="#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a>
- <a href="#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a>
- <a href="#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a>
- <a href="#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a>
- <a href="#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a>
- <a href="#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a>
- <a href="#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a>
- <a href="#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a>
<a name="api_nan_error"></a>
### Nan::Error()
Create a new Error object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an Error object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::Error(const char *msg);
v8::Local<v8::Value> Nan::Error(v8::Local<v8::String> msg);
```
<a name="api_nan_range_error"></a>
### Nan::RangeError()
Create a new RangeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an RangeError object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::RangeError(const char *msg);
v8::Local<v8::Value> Nan::RangeError(v8::Local<v8::String> msg);
```
<a name="api_nan_reference_error"></a>
### Nan::ReferenceError()
Create a new ReferenceError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an ReferenceError object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::ReferenceError(const char *msg);
v8::Local<v8::Value> Nan::ReferenceError(v8::Local<v8::String> msg);
```
<a name="api_nan_syntax_error"></a>
### Nan::SyntaxError()
Create a new SyntaxError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an SyntaxError object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::SyntaxError(const char *msg);
v8::Local<v8::Value> Nan::SyntaxError(v8::Local<v8::String> msg);
```
<a name="api_nan_type_error"></a>
### Nan::TypeError()
Create a new TypeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8.
Note that an TypeError object is simply a specialized form of `v8::Value`.
Signature:
```c++
v8::Local<v8::Value> Nan::TypeError(const char *msg);
v8::Local<v8::Value> Nan::TypeError(v8::Local<v8::String> msg);
```
<a name="api_nan_throw_error"></a>
### Nan::ThrowError()
Throw an Error object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new Error object will be created.
Signature:
```c++
void Nan::ThrowError(const char *msg);
void Nan::ThrowError(v8::Local<v8::String> msg);
void Nan::ThrowError(v8::Local<v8::Value> error);
```
<a name="api_nan_throw_range_error"></a>
### Nan::ThrowRangeError()
Throw an RangeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new RangeError object will be created.
Signature:
```c++
void Nan::ThrowRangeError(const char *msg);
void Nan::ThrowRangeError(v8::Local<v8::String> msg);
void Nan::ThrowRangeError(v8::Local<v8::Value> error);
```
<a name="api_nan_throw_reference_error"></a>
### Nan::ThrowReferenceError()
Throw an ReferenceError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new ReferenceError object will be created.
Signature:
```c++
void Nan::ThrowReferenceError(const char *msg);
void Nan::ThrowReferenceError(v8::Local<v8::String> msg);
void Nan::ThrowReferenceError(v8::Local<v8::Value> error);
```
<a name="api_nan_throw_syntax_error"></a>
### Nan::ThrowSyntaxError()
Throw an SyntaxError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new SyntaxError object will be created.
Signature:
```c++
void Nan::ThrowSyntaxError(const char *msg);
void Nan::ThrowSyntaxError(v8::Local<v8::String> msg);
void Nan::ThrowSyntaxError(v8::Local<v8::Value> error);
```
<a name="api_nan_throw_type_error"></a>
### Nan::ThrowTypeError()
Throw an TypeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new TypeError object will be created.
Signature:
```c++
void Nan::ThrowTypeError(const char *msg);
void Nan::ThrowTypeError(v8::Local<v8::String> msg);
void Nan::ThrowTypeError(v8::Local<v8::Value> error);
```
<a name="api_nan_fatal_exception"></a>
### Nan::FatalException()
Replaces `node::FatalException()` which has a different API across supported versions of Node. For use with [`Nan::TryCatch`](#api_nan_try_catch).
Signature:
```c++
void Nan::FatalException(const Nan::TryCatch& try_catch);
```
<a name="api_nan_errno_exception"></a>
### Nan::ErrnoException()
Replaces `node::ErrnoException()` which has a different API across supported versions of Node.
Signature:
```c++
v8::Local<v8::Value> Nan::ErrnoException(int errorno,
const char* syscall = NULL,
const char* message = NULL,
const char* path = NULL);
```
<a name="api_nan_try_catch"></a>
### Nan::TryCatch
A simple wrapper around [`v8::TryCatch`](https://v8docs.nodesource.com/node-8.16/d4/dc6/classv8_1_1_try_catch.html) compatible with all supported versions of V8. Can be used as a direct replacement in most cases. See also [`Nan::FatalException()`](#api_nan_fatal_exception) for an internal use compatible with `node::FatalException`.
Signature:
```c++
class Nan::TryCatch {
public:
Nan::TryCatch();
bool HasCaught() const;
bool CanContinue() const;
v8::Local<v8::Value> ReThrow();
v8::Local<v8::Value> Exception() const;
// Nan::MaybeLocal for older versions of V8
v8::MaybeLocal<v8::Value> StackTrace() const;
v8::Local<v8::Message> Message() const;
void Reset();
void SetVerbose(bool value);
void SetCaptureMessage(bool value);
};
```

62
node_modules/nan/doc/json.md generated vendored Normal file
View File

@ -0,0 +1,62 @@
## JSON
The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object.
- <a href="#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a>
- <a href="#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a>
Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments.
<a name="api_nan_json_parse"></a>
### Nan::JSON.Parse
A simple wrapper around [`v8::JSON::Parse`](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html#a936310d2540fb630ed37d3ee3ffe4504).
Definition:
```c++
Nan::MaybeLocal<v8::Value> Nan::JSON::Parse(v8::Local<v8::String> json_string);
```
Use `JSON.Parse(json_string)` to parse a string into a `v8::Value`.
Example:
```c++
v8::Local<v8::String> json_string = Nan::New("{ \"JSON\": \"object\" }").ToLocalChecked();
Nan::JSON NanJSON;
Nan::MaybeLocal<v8::Value> result = NanJSON.Parse(json_string);
if (!result.IsEmpty()) {
v8::Local<v8::Value> val = result.ToLocalChecked();
}
```
<a name="api_nan_json_stringify"></a>
### Nan::JSON.Stringify
A simple wrapper around [`v8::JSON::Stringify`](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html#a44b255c3531489ce43f6110209138860).
Definition:
```c++
Nan::MaybeLocal<v8::String> Nan::JSON::Stringify(v8::Local<v8::Object> json_object, v8::Local<v8::String> gap = v8::Local<v8::String>());
```
Use `JSON.Stringify(value)` to stringify a `v8::Object`.
Example:
```c++
// using `v8::Local<v8::Value> val` from the `JSON::Parse` example
v8::Local<v8::Object> obj = Nan::To<v8::Object>(val).ToLocalChecked();
Nan::JSON NanJSON;
Nan::MaybeLocal<v8::String> result = NanJSON.Stringify(obj);
if (!result.IsEmpty()) {
v8::Local<v8::String> stringified = result.ToLocalChecked();
}
```

583
node_modules/nan/doc/maybe_types.md generated vendored Normal file
View File

@ -0,0 +1,583 @@
## Maybe Types
The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_.
* **Maybe Types**
- <a href="#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a>
- <a href="#api_nan_maybe"><b><code>Nan::Maybe</code></b></a>
- <a href="#api_nan_nothing"><b><code>Nan::Nothing</code></b></a>
- <a href="#api_nan_just"><b><code>Nan::Just</code></b></a>
* **Maybe Helpers**
- <a href="#api_nan_call"><b><code>Nan::Call()</code></b></a>
- <a href="#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a>
- <a href="#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a>
- <a href="#api_nan_equals"><b><code>Nan::Equals()</code></b></a>
- <a href="#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a>
- <a href="#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a>
- <a href="#api_nan_set"><b><code>Nan::Set()</code></b></a>
- <a href="#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a>
- <a href="#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a>
- <a href="#api_nan_get"><b><code>Nan::Get()</code></b></a>
- <a href="#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a>
- <a href="#api_nan_has"><b><code>Nan::Has()</code></b></a>
- <a href="#api_nan_delete"><b><code>Nan::Delete()</code></b></a>
- <a href="#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a>
- <a href="#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a>
- <a href="#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a>
- <a href="#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a>
- <a href="#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a>
- <a href="#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a>
- <a href="#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a>
- <a href="#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a>
- <a href="#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a>
- <a href="#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a>
- <a href="#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a>
- <a href="#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a>
- <a href="#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a>
- <a href="#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a>
- <a href="#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a>
- <a href="#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a>
- <a href="#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a>
- <a href="#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a>
- <a href="#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a>
- <a href="#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a>
- <a href="#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a>
- <a href="#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a>
<a name="api_nan_maybe_local"></a>
### Nan::MaybeLocal
A `Nan::MaybeLocal<T>` is a wrapper around [`v8::Local<T>`](https://v8docs.nodesource.com/node-8.16/de/deb/classv8_1_1_local.html) that enforces a check that determines whether the `v8::Local<T>` is empty before it can be used.
If an API method returns a `Nan::MaybeLocal`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, an empty `Nan::MaybeLocal` is returned.
Definition:
```c++
template<typename T> class Nan::MaybeLocal {
public:
MaybeLocal();
template<typename S> MaybeLocal(v8::Local<S> that);
bool IsEmpty() const;
template<typename S> bool ToLocal(v8::Local<S> *out);
// Will crash if the MaybeLocal<> is empty.
v8::Local<T> ToLocalChecked();
template<typename S> v8::Local<S> FromMaybe(v8::Local<S> default_value) const;
};
```
See the documentation for [`v8::MaybeLocal`](https://v8docs.nodesource.com/node-8.16/d8/d7d/classv8_1_1_maybe_local.html) for further details.
<a name="api_nan_maybe"></a>
### Nan::Maybe
A simple `Nan::Maybe` type, representing an object which may or may not have a value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
If an API method returns a `Nan::Maybe<>`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, a "Nothing" value is returned.
Definition:
```c++
template<typename T> class Nan::Maybe {
public:
bool IsNothing() const;
bool IsJust() const;
// Will crash if the Maybe<> is nothing.
T FromJust();
T FromMaybe(const T& default_value);
bool operator==(const Maybe &other);
bool operator!=(const Maybe &other);
};
```
See the documentation for [`v8::Maybe`](https://v8docs.nodesource.com/node-8.16/d9/d4b/classv8_1_1_maybe.html) for further details.
<a name="api_nan_nothing"></a>
### Nan::Nothing
Construct an empty `Nan::Maybe` type representing _nothing_.
```c++
template<typename T> Nan::Maybe<T> Nan::Nothing();
```
<a name="api_nan_just"></a>
### Nan::Just
Construct a `Nan::Maybe` type representing _just_ a value.
```c++
template<typename T> Nan::Maybe<T> Nan::Just(const T &t);
```
<a name="api_nan_call"></a>
### Nan::Call()
A helper method for calling a synchronous [`v8::Function#Call()`](https://v8docs.nodesource.com/node-8.16/d5/d54/classv8_1_1_function.html#a9c3d0e4e13ddd7721fce238aa5b94a11) in a way compatible across supported versions of V8.
For asynchronous callbacks, use Nan::Callback::Call along with an AsyncResource.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::Call(v8::Local<v8::Function> fun, v8::Local<v8::Object> recv, int argc, v8::Local<v8::Value> argv[]);
Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, v8::Local<v8::Object> recv,
int argc, v8::Local<v8::Value> argv[]);
Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, int argc, v8::Local<v8::Value> argv[]);
```
<a name="api_nan_to_detail_string"></a>
### Nan::ToDetailString()
A helper method for calling [`v8::Value#ToDetailString()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#a2f9770296dc2c8d274bc8cc0dca243e5) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::String> Nan::ToDetailString(v8::Local<v8::Value> val);
```
<a name="api_nan_to_array_index"></a>
### Nan::ToArrayIndex()
A helper method for calling [`v8::Value#ToArrayIndex()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#acc5bbef3c805ec458470c0fcd6f13493) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Uint32> Nan::ToArrayIndex(v8::Local<v8::Value> val);
```
<a name="api_nan_equals"></a>
### Nan::Equals()
A helper method for calling [`v8::Value#Equals()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#a08fba1d776a59bbf6864b25f9152c64b) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b));
```
<a name="api_nan_new_instance"></a>
### Nan::NewInstance()
A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/node-8.16/d5/d54/classv8_1_1_function.html#ae477558b10c14b76ed00e8dbab44ce5b) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h);
Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h, int argc, v8::Local<v8::Value> argv[]);
Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::ObjectTemplate> h);
```
<a name="api_nan_get_function"></a>
### Nan::GetFunction()
A helper method for calling [`v8::FunctionTemplate#GetFunction()`](https://v8docs.nodesource.com/node-8.16/d8/d83/classv8_1_1_function_template.html#a56d904662a86eca78da37d9bb0ed3705) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Function> Nan::GetFunction(v8::Local<v8::FunctionTemplate> t);
```
<a name="api_nan_set"></a>
### Nan::Set()
A helper method for calling [`v8::Object#Set()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a67604ea3734f170c66026064ea808f20) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj,
v8::Local<v8::Value> key,
v8::Local<v8::Value> value)
Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj,
uint32_t index,
v8::Local<v8::Value> value);
```
<a name="api_nan_define_own_property"></a>
### Nan::DefineOwnProperty()
A helper method for calling [`v8::Object#DefineOwnProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a6f76b2ed605cb8f9185b92de0033a820) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::DefineOwnProperty(v8::Local<v8::Object> obj,
v8::Local<v8::String> key,
v8::Local<v8::Value> value,
v8::PropertyAttribute attribs = v8::None);
```
<a name="api_nan_force_set"></a>
### <del>Nan::ForceSet()</del>
Deprecated, use <a href="#api_nan_define_own_property"><code>Nan::DefineOwnProperty()</code></a>.
<del>A helper method for calling [`v8::Object#ForceSet()`](https://v8docs.nodesource.com/node-0.12/db/d85/classv8_1_1_object.html#acfbdfd7427b516ebdb5c47c4df5ed96c) in a way compatible across supported versions of V8.</del>
Signature:
```c++
NAN_DEPRECATED Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object> obj,
v8::Local<v8::Value> key,
v8::Local<v8::Value> value,
v8::PropertyAttribute attribs = v8::None);
```
<a name="api_nan_get"></a>
### Nan::Get()
A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj,
v8::Local<v8::Value> key);
Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj, uint32_t index);
```
<a name="api_nan_get_property_attribute"></a>
### Nan::GetPropertyAttributes()
A helper method for calling [`v8::Object#GetPropertyAttributes()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a9b898894da3d1db2714fd9325a54fe57) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<v8::PropertyAttribute> Nan::GetPropertyAttributes(
v8::Local<v8::Object> obj,
v8::Local<v8::Value> key);
```
<a name="api_nan_has"></a>
### Nan::Has()
A helper method for calling [`v8::Object#Has()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab3c3d89ea7c2f9afd08965bd7299a41d) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, v8::Local<v8::String> key);
Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, uint32_t index);
```
<a name="api_nan_delete"></a>
### Nan::Delete()
A helper method for calling [`v8::Object#Delete()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a48e4a19b2cedff867eecc73ddb7d377f) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj, uint32_t index);
```
<a name="api_nan_get_property_names"></a>
### Nan::GetPropertyNames()
A helper method for calling [`v8::Object#GetPropertyNames()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#aced885270cfd2c956367b5eedc7fbfe8) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Array> Nan::GetPropertyNames(v8::Local<v8::Object> obj);
```
<a name="api_nan_get_own_property_names"></a>
### Nan::GetOwnPropertyNames()
A helper method for calling [`v8::Object#GetOwnPropertyNames()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a79a6e4d66049b9aa648ed4dfdb23e6eb) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Array> Nan::GetOwnPropertyNames(v8::Local<v8::Object> obj);
```
<a name="api_nan_set_prototype"></a>
### Nan::SetPrototype()
A helper method for calling [`v8::Object#SetPrototype()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a442706b22fceda6e6d1f632122a9a9f4) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::SetPrototype(v8::Local<v8::Object> obj,
v8::Local<v8::Value> prototype);
```
<a name="api_nan_object_proto_to_string"></a>
### Nan::ObjectProtoToString()
A helper method for calling [`v8::Object#ObjectProtoToString()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab7a92b4dcf822bef72f6c0ac6fea1f0b) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::String> Nan::ObjectProtoToString(v8::Local<v8::Object> obj);
```
<a name="api_nan_has_own_property"></a>
### Nan::HasOwnProperty()
A helper method for calling [`v8::Object#HasOwnProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab7b7245442ca6de1e1c145ea3fd653ff) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasOwnProperty(v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_has_real_named_property"></a>
### Nan::HasRealNamedProperty()
A helper method for calling [`v8::Object#HasRealNamedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ad8b80a59c9eb3c1e6c3cd6c84571f767) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasRealNamedProperty(v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_has_real_indexed_property"></a>
### Nan::HasRealIndexedProperty()
A helper method for calling [`v8::Object#HasRealIndexedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af94fc1135a5e74a2193fb72c3a1b9855) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasRealIndexedProperty(v8::Local<v8::Object> obj,
uint32_t index);
```
<a name="api_nan_has_real_named_callback_property"></a>
### Nan::HasRealNamedCallbackProperty()
A helper method for calling [`v8::Object#HasRealNamedCallbackProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af743b7ea132b89f84d34d164d0668811) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasRealNamedCallbackProperty(
v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_get_real_named_property_in_prototype_chain"></a>
### Nan::GetRealNamedPropertyInPrototypeChain()
A helper method for calling [`v8::Object#GetRealNamedPropertyInPrototypeChain()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a8700b1862e6b4783716964ba4d5e6172) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::GetRealNamedPropertyInPrototypeChain(
v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_get_real_named_property"></a>
### Nan::GetRealNamedProperty()
A helper method for calling [`v8::Object#GetRealNamedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a84471a824576a5994fdd0ffcbf99ccc0) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::GetRealNamedProperty(v8::Local<v8::Object> obj,
v8::Local<v8::String> key);
```
<a name="api_nan_call_as_function"></a>
### Nan::CallAsFunction()
A helper method for calling [`v8::Object#CallAsFunction()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ad3ffc36f3dfc3592ce2a96bc047ee2cd) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::CallAsFunction(v8::Local<v8::Object> obj,
v8::Local<v8::Object> recv,
int argc,
v8::Local<v8::Value> argv[]);
```
<a name="api_nan_call_as_constructor"></a>
### Nan::CallAsConstructor()
A helper method for calling [`v8::Object#CallAsConstructor()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a50d571de50d0b0dfb28795619d07a01b) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::CallAsConstructor(v8::Local<v8::Object> obj,
int argc,
v8::Local<v8::Value> argv[]);
```
<a name="api_nan_get_source_line"></a>
### Nan::GetSourceLine()
A helper method for calling [`v8::Message#GetSourceLine()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#a849f7a6c41549d83d8159825efccd23a) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::String> Nan::GetSourceLine(v8::Local<v8::Message> msg);
```
<a name="api_nan_get_line_number"></a>
### Nan::GetLineNumber()
A helper method for calling [`v8::Message#GetLineNumber()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#adbe46c10a88a6565f2732a2d2adf99b9) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<int> Nan::GetLineNumber(v8::Local<v8::Message> msg);
```
<a name="api_nan_get_start_column"></a>
### Nan::GetStartColumn()
A helper method for calling [`v8::Message#GetStartColumn()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#a60ede616ba3822d712e44c7a74487ba6) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<int> Nan::GetStartColumn(v8::Local<v8::Message> msg);
```
<a name="api_nan_get_end_column"></a>
### Nan::GetEndColumn()
A helper method for calling [`v8::Message#GetEndColumn()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#aaa004cf19e529da980bc19fcb76d93be) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<int> Nan::GetEndColumn(v8::Local<v8::Message> msg);
```
<a name="api_nan_clone_element_at"></a>
### Nan::CloneElementAt()
A helper method for calling [`v8::Array#CloneElementAt()`](https://v8docs.nodesource.com/node-4.8/d3/d32/classv8_1_1_array.html#a1d3a878d4c1c7cae974dd50a1639245e) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Object> Nan::CloneElementAt(v8::Local<v8::Array> array, uint32_t index);
```
<a name="api_nan_has_private"></a>
### Nan::HasPrivate()
A helper method for calling [`v8::Object#HasPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af68a0b98066cfdeb8f943e98a40ba08d) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
```
<a name="api_nan_get_private"></a>
### Nan::GetPrivate()
A helper method for calling [`v8::Object#GetPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a169f2da506acbec34deadd9149a1925a) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
```
<a name="api_nan_set_private"></a>
### Nan::SetPrivate()
A helper method for calling [`v8::Object#SetPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ace1769b0f3b86bfe9fda1010916360ee) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value);
```
<a name="api_nan_delete_private"></a>
### Nan::DeletePrivate()
A helper method for calling [`v8::Object#DeletePrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a138bb32a304f3982be02ad499693b8fd) in a way compatible across supported versions of V8.
Signature:
```c++
Nan::Maybe<bool> Nan::DeletePrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key);
```
<a name="api_nan_make_maybe"></a>
### Nan::MakeMaybe()
Wraps a `v8::Local<>` in a `Nan::MaybeLocal<>`. When called with a `Nan::MaybeLocal<>` it just returns its argument. This is useful in generic template code that builds on NAN.
Synopsis:
```c++
MaybeLocal<v8::Number> someNumber = MakeMaybe(New<v8::Number>(3.141592654));
MaybeLocal<v8::String> someString = MakeMaybe(New<v8::String>("probably"));
```
Signature:
```c++
template <typename T, template <typename> class MaybeMaybe>
Nan::MaybeLocal<T> Nan::MakeMaybe(MaybeMaybe<T> v);
```

664
node_modules/nan/doc/methods.md generated vendored Normal file
View File

@ -0,0 +1,664 @@
## JavaScript-accessible methods
A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information.
In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type.
* **Method argument types**
- <a href="#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a>
- <a href="#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a>
- <a href="#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a>
* **Method declarations**
- <a href="#api_nan_method"><b>Method declaration</b></a>
- <a href="#api_nan_getter"><b>Getter declaration</b></a>
- <a href="#api_nan_setter"><b>Setter declaration</b></a>
- <a href="#api_nan_property_getter"><b>Property getter declaration</b></a>
- <a href="#api_nan_property_setter"><b>Property setter declaration</b></a>
- <a href="#api_nan_property_enumerator"><b>Property enumerator declaration</b></a>
- <a href="#api_nan_property_deleter"><b>Property deleter declaration</b></a>
- <a href="#api_nan_property_query"><b>Property query declaration</b></a>
- <a href="#api_nan_index_getter"><b>Index getter declaration</b></a>
- <a href="#api_nan_index_setter"><b>Index setter declaration</b></a>
- <a href="#api_nan_index_enumerator"><b>Index enumerator declaration</b></a>
- <a href="#api_nan_index_deleter"><b>Index deleter declaration</b></a>
- <a href="#api_nan_index_query"><b>Index query declaration</b></a>
* Method and template helpers
- <a href="#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a>
- <a href="#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a>
- <a href="#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a>
- <a href="#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a>
- <a href="#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a>
- <a href="#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a>
- <a href="#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a>
- <a href="#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a>
- <a href="#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a>
- <a href="#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a>
<a name="api_nan_function_callback_info"></a>
### Nan::FunctionCallbackInfo
`Nan::FunctionCallbackInfo` should be used in place of [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.16/dd/d0d/classv8_1_1_function_callback_info.html), even with older versions of Node where `v8::FunctionCallbackInfo` does not exist.
Definition:
```c++
template<typename T> class FunctionCallbackInfo {
public:
ReturnValue<T> GetReturnValue() const;
v8::Local<v8::Function> Callee(); // NOTE: Not available in NodeJS >= 10.0.0
v8::Local<v8::Value> Data();
v8::Local<v8::Object> Holder();
bool IsConstructCall();
int Length() const;
v8::Local<v8::Value> operator[](int i) const;
v8::Local<v8::Object> This() const;
v8::Isolate *GetIsolate() const;
};
```
See the [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.16/dd/d0d/classv8_1_1_function_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from methods.
**Note:** `FunctionCallbackInfo::Callee` is removed in Node.js after `10.0.0` because it is was deprecated in V8. Consider using `info.Data()` to pass any information you need.
<a name="api_nan_property_callback_info"></a>
### Nan::PropertyCallbackInfo
`Nan::PropertyCallbackInfo` should be used in place of [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d7/dc5/classv8_1_1_property_callback_info.html), even with older versions of Node where `v8::PropertyCallbackInfo` does not exist.
Definition:
```c++
template<typename T> class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
public:
ReturnValue<T> GetReturnValue() const;
v8::Isolate* GetIsolate() const;
v8::Local<v8::Value> Data() const;
v8::Local<v8::Object> This() const;
v8::Local<v8::Object> Holder() const;
};
```
See the [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d7/dc5/classv8_1_1_property_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from property accessor methods.
<a name="api_nan_return_value"></a>
### Nan::ReturnValue
`Nan::ReturnValue` is used in place of [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.16/da/da7/classv8_1_1_return_value.html) on both [`Nan::FunctionCallbackInfo`](#api_nan_function_callback_info) and [`Nan::PropertyCallbackInfo`](#api_nan_property_callback_info) as the return type of `GetReturnValue()`.
Example usage:
```c++
void EmptyArray(const Nan::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(Nan::New<v8::Array>());
}
```
Definition:
```c++
template<typename T> class ReturnValue {
public:
// Handle setters
template <typename S> void Set(const v8::Local<S> &handle);
template <typename S> void Set(const Nan::Global<S> &handle);
// Fast primitive setters
void Set(bool value);
void Set(double i);
void Set(int32_t i);
void Set(uint32_t i);
// Fast JS primitive setters
void SetNull();
void SetUndefined();
void SetEmptyString();
// Convenience getter for isolate
v8::Isolate *GetIsolate() const;
};
```
See the documentation on [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.16/da/da7/classv8_1_1_return_value.html) for further information on this.
<a name="api_nan_method"></a>
### Method declaration
JavaScript-accessible methods should be declared with the following signature to form a `Nan::FunctionCallback`:
```c++
typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
```
Example:
```c++
void MethodName(const Nan::FunctionCallbackInfo<v8::Value>& info) {
...
}
```
You do not need to declare a new `HandleScope` within a method as one is implicitly created for you.
**Example usage**
```c++
// .h:
class Foo : public Nan::ObjectWrap {
...
static void Bar(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void Baz(const Nan::FunctionCallbackInfo<v8::Value>& info);
}
// .cc:
void Foo::Bar(const Nan::FunctionCallbackInfo<v8::Value>& info) {
...
}
void Foo::Baz(const Nan::FunctionCallbackInfo<v8::Value>& info) {
...
}
```
A helper macro `NAN_METHOD(methodname)` exists, compatible with NAN v1 method declarations.
**Example usage with `NAN_METHOD(methodname)`**
```c++
// .h:
class Foo : public Nan::ObjectWrap {
...
static NAN_METHOD(Bar);
static NAN_METHOD(Baz);
}
// .cc:
NAN_METHOD(Foo::Bar) {
...
}
NAN_METHOD(Foo::Baz) {
...
}
```
Use [`Nan::SetPrototypeMethod`](#api_nan_set_prototype_method) to attach a method to a JavaScript function prototype or [`Nan::SetMethod`](#api_nan_set_method) to attach a method directly on a JavaScript object.
<a name="api_nan_getter"></a>
### Getter declaration
JavaScript-accessible getters should be declared with the following signature to form a `Nan::GetterCallback`:
```c++
typedef void(*GetterCallback)(v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void GetterName(v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info) {
...
}
```
You do not need to declare a new `HandleScope` within a getter as one is implicitly created for you.
A helper macro `NAN_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors).
<a name="api_nan_setter"></a>
### Setter declaration
JavaScript-accessible setters should be declared with the following signature to form a <b><code>Nan::SetterCallback</code></b>:
```c++
typedef void(*SetterCallback)(v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<void>&);
```
Example:
```c++
void SetterName(v8::Local<v8::String> property,
v8::Local<v8::Value> value,
const Nan::PropertyCallbackInfo<void>& info) {
...
}
```
You do not need to declare a new `HandleScope` within a setter as one is implicitly created for you.
A helper macro `NAN_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors).
<a name="api_nan_property_getter"></a>
### Property getter declaration
JavaScript-accessible property getters should be declared with the following signature to form a <b><code>Nan::PropertyGetterCallback</code></b>:
```c++
typedef void(*PropertyGetterCallback)(v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void PropertyGetterName(v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info) {
...
}
```
You do not need to declare a new `HandleScope` within a property getter as one is implicitly created for you.
A helper macro `NAN_PROPERTY_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_property_setter"></a>
### Property setter declaration
JavaScript-accessible property setters should be declared with the following signature to form a <b><code>Nan::PropertySetterCallback</code></b>:
```c++
typedef void(*PropertySetterCallback)(v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void PropertySetterName(v8::Local<v8::String> property,
v8::Local<v8::Value> value,
const Nan::PropertyCallbackInfo<v8::Value>& info);
```
You do not need to declare a new `HandleScope` within a property setter as one is implicitly created for you.
A helper macro `NAN_PROPERTY_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_property_enumerator"></a>
### Property enumerator declaration
JavaScript-accessible property enumerators should be declared with the following signature to form a <b><code>Nan::PropertyEnumeratorCallback</code></b>:
```c++
typedef void(*PropertyEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&);
```
Example:
```c++
void PropertyEnumeratorName(const Nan::PropertyCallbackInfo<v8::Array>& info);
```
You do not need to declare a new `HandleScope` within a property enumerator as one is implicitly created for you.
A helper macro `NAN_PROPERTY_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_property_deleter"></a>
### Property deleter declaration
JavaScript-accessible property deleters should be declared with the following signature to form a <b><code>Nan::PropertyDeleterCallback</code></b>:
```c++
typedef void(*PropertyDeleterCallback)(v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Boolean>&);
```
Example:
```c++
void PropertyDeleterName(v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Boolean>& info);
```
You do not need to declare a new `HandleScope` within a property deleter as one is implicitly created for you.
A helper macro `NAN_PROPERTY_DELETER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_property_query"></a>
### Property query declaration
JavaScript-accessible property query methods should be declared with the following signature to form a <b><code>Nan::PropertyQueryCallback</code></b>:
```c++
typedef void(*PropertyQueryCallback)(v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Integer>&);
```
Example:
```c++
void PropertyQueryName(v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Integer>& info);
```
You do not need to declare a new `HandleScope` within a property query method as one is implicitly created for you.
A helper macro `NAN_PROPERTY_QUERY(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_getter"></a>
### Index getter declaration
JavaScript-accessible index getter methods should be declared with the following signature to form a <b><code>Nan::IndexGetterCallback</code></b>:
```c++
typedef void(*IndexGetterCallback)(uint32_t,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void IndexGetterName(uint32_t index, const PropertyCallbackInfo<v8::Value>& info);
```
You do not need to declare a new `HandleScope` within a index getter as one is implicitly created for you.
A helper macro `NAN_INDEX_GETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_setter"></a>
### Index setter declaration
JavaScript-accessible index setter methods should be declared with the following signature to form a <b><code>Nan::IndexSetterCallback</code></b>:
```c++
typedef void(*IndexSetterCallback)(uint32_t,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
```
Example:
```c++
void IndexSetterName(uint32_t index,
v8::Local<v8::Value> value,
const PropertyCallbackInfo<v8::Value>& info);
```
You do not need to declare a new `HandleScope` within a index setter as one is implicitly created for you.
A helper macro `NAN_INDEX_SETTER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_enumerator"></a>
### Index enumerator declaration
JavaScript-accessible index enumerator methods should be declared with the following signature to form a <b><code>Nan::IndexEnumeratorCallback</code></b>:
```c++
typedef void(*IndexEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&);
```
Example:
```c++
void IndexEnumeratorName(const PropertyCallbackInfo<v8::Array>& info);
```
You do not need to declare a new `HandleScope` within a index enumerator as one is implicitly created for you.
A helper macro `NAN_INDEX_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_deleter"></a>
### Index deleter declaration
JavaScript-accessible index deleter methods should be declared with the following signature to form a <b><code>Nan::IndexDeleterCallback</code></b>:
```c++
typedef void(*IndexDeleterCallback)(uint32_t,
const PropertyCallbackInfo<v8::Boolean>&);
```
Example:
```c++
void IndexDeleterName(uint32_t index, const PropertyCallbackInfo<v8::Boolean>& info);
```
You do not need to declare a new `HandleScope` within a index deleter as one is implicitly created for you.
A helper macro `NAN_INDEX_DELETER(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_index_query"></a>
### Index query declaration
JavaScript-accessible index query methods should be declared with the following signature to form a <b><code>Nan::IndexQueryCallback</code></b>:
```c++
typedef void(*IndexQueryCallback)(uint32_t,
const PropertyCallbackInfo<v8::Integer>&);
```
Example:
```c++
void IndexQueryName(uint32_t index, const PropertyCallbackInfo<v8::Integer>& info);
```
You do not need to declare a new `HandleScope` within a index query method as one is implicitly created for you.
A helper macro `NAN_INDEX_QUERY(methodname)` exists, compatible with NAN v1 method declarations.
Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors).
<a name="api_nan_set_method"></a>
### Nan::SetMethod()
Sets a method with a given name directly on a JavaScript object where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>).
Signature:
```c++
void Nan::SetMethod(v8::Local<v8::Object> recv,
const char *name,
Nan::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>())
void Nan::SetMethod(v8::Local<v8::Template> templ,
const char *name,
Nan::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>())
```
<a name="api_nan_set_prototype_method"></a>
### Nan::SetPrototypeMethod()
Sets a method with a given name on a `FunctionTemplate`'s prototype where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>).
Signature:
```c++
void Nan::SetPrototypeMethod(v8::Local<v8::FunctionTemplate> recv,
const char* name,
Nan::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>())
```
<a name="api_nan_set_accessor"></a>
### Nan::SetAccessor()
Sets getters and setters for a property with a given name on an `ObjectTemplate` or a plain `Object`. Accepts getters with the `Nan::GetterCallback` signature (see <a href="#api_nan_getter">Getter declaration</a>) and setters with the `Nan::SetterCallback` signature (see <a href="#api_nan_setter">Setter declaration</a>).
Signature:
```c++
void SetAccessor(v8::Local<v8::ObjectTemplate> tpl,
v8::Local<v8::String> name,
Nan::GetterCallback getter,
Nan::SetterCallback setter = 0,
v8::Local<v8::Value> data = v8::Local<v8::Value>(),
v8::AccessControl settings = v8::DEFAULT,
v8::PropertyAttribute attribute = v8::None,
imp::Sig signature = imp::Sig());
bool SetAccessor(v8::Local<v8::Object> obj,
v8::Local<v8::String> name,
Nan::GetterCallback getter,
Nan::SetterCallback setter = 0,
v8::Local<v8::Value> data = v8::Local<v8::Value>(),
v8::AccessControl settings = v8::DEFAULT,
v8::PropertyAttribute attribute = v8::None)
```
See the V8 [`ObjectTemplate#SetAccessor()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#aca0ed196f8a9adb1f68b1aadb6c9cd77) and [`Object#SetAccessor()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ae91b3b56b357f285288c89fbddc46d1b) for further information about how to use `Nan::SetAccessor()`.
<a name="api_nan_set_named_property_handler"></a>
### Nan::SetNamedPropertyHandler()
Sets named property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts:
* Property getters with the `Nan::PropertyGetterCallback` signature (see <a href="#api_nan_property_getter">Property getter declaration</a>)
* Property setters with the `Nan::PropertySetterCallback` signature (see <a href="#api_nan_property_setter">Property setter declaration</a>)
* Property query methods with the `Nan::PropertyQueryCallback` signature (see <a href="#api_nan_property_query">Property query declaration</a>)
* Property deleters with the `Nan::PropertyDeleterCallback` signature (see <a href="#api_nan_property_deleter">Property deleter declaration</a>)
* Property enumerators with the `Nan::PropertyEnumeratorCallback` signature (see <a href="#api_nan_property_enumerator">Property enumerator declaration</a>)
Signature:
```c++
void SetNamedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl,
Nan::PropertyGetterCallback getter,
Nan::PropertySetterCallback setter = 0,
Nan::PropertyQueryCallback query = 0,
Nan::PropertyDeleterCallback deleter = 0,
Nan::PropertyEnumeratorCallback enumerator = 0,
v8::Local<v8::Value> data = v8::Local<v8::Value>())
```
See the V8 [`ObjectTemplate#SetNamedPropertyHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#a33b3ebd7de641f6cc6414b7de01fc1c7) for further information about how to use `Nan::SetNamedPropertyHandler()`.
<a name="api_nan_set_indexed_property_handler"></a>
### Nan::SetIndexedPropertyHandler()
Sets indexed property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts:
* Indexed property getters with the `Nan::IndexGetterCallback` signature (see <a href="#api_nan_index_getter">Index getter declaration</a>)
* Indexed property setters with the `Nan::IndexSetterCallback` signature (see <a href="#api_nan_index_setter">Index setter declaration</a>)
* Indexed property query methods with the `Nan::IndexQueryCallback` signature (see <a href="#api_nan_index_query">Index query declaration</a>)
* Indexed property deleters with the `Nan::IndexDeleterCallback` signature (see <a href="#api_nan_index_deleter">Index deleter declaration</a>)
* Indexed property enumerators with the `Nan::IndexEnumeratorCallback` signature (see <a href="#api_nan_index_enumerator">Index enumerator declaration</a>)
Signature:
```c++
void SetIndexedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl,
Nan::IndexGetterCallback getter,
Nan::IndexSetterCallback setter = 0,
Nan::IndexQueryCallback query = 0,
Nan::IndexDeleterCallback deleter = 0,
Nan::IndexEnumeratorCallback enumerator = 0,
v8::Local<v8::Value> data = v8::Local<v8::Value>())
```
See the V8 [`ObjectTemplate#SetIndexedPropertyHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#ac89f06d634add0e890452033f7d17ff1) for further information about how to use `Nan::SetIndexedPropertyHandler()`.
<a name="api_nan_set_template"></a>
### Nan::SetTemplate()
Adds properties on an `Object`'s or `Function`'s template.
Signature:
```c++
void Nan::SetTemplate(v8::Local<v8::Template> templ,
const char *name,
v8::Local<v8::Data> value);
void Nan::SetTemplate(v8::Local<v8::Template> templ,
v8::Local<v8::String> name,
v8::Local<v8::Data> value,
v8::PropertyAttribute attributes)
```
Calls the `Template`'s [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#ae3fbaff137557aa6a0233bc7e52214ac).
<a name="api_nan_set_prototype_template"></a>
### Nan::SetPrototypeTemplate()
Adds properties on an `Object`'s or `Function`'s prototype template.
Signature:
```c++
void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ,
const char *name,
v8::Local<v8::Data> value);
void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ,
v8::Local<v8::String> name,
v8::Local<v8::Data> value,
v8::PropertyAttribute attributes)
```
Calls the `FunctionTemplate`'s _PrototypeTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).
<a name="api_nan_set_instance_template"></a>
### Nan::SetInstanceTemplate()
Use to add instance properties on `FunctionTemplate`'s.
Signature:
```c++
void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ,
const char *name,
v8::Local<v8::Data> value);
void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ,
v8::Local<v8::String> name,
v8::Local<v8::Data> value,
v8::PropertyAttribute attributes)
```
Calls the `FunctionTemplate`'s _InstanceTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf).
<a name="api_nan_set_call_handler"></a>
### Nan::SetCallHandler()
Set the call-handler callback for a `v8::FunctionTemplate`.
This callback is called whenever the function created from this FunctionTemplate is called.
Signature:
```c++
void Nan::SetCallHandler(v8::Local<v8::FunctionTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>())
```
Calls the `FunctionTemplate`'s [`SetCallHandler()`](https://v8docs.nodesource.com/node-8.16/d8/d83/classv8_1_1_function_template.html#ab7574b298db3c27fbc2ed465c08ea2f8).
<a name="api_nan_set_call_as_function_handler"></a>
### Nan::SetCallAsFunctionHandler()
Sets the callback to be used when calling instances created from the `v8::ObjectTemplate` as a function.
If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function.
Signature:
```c++
void Nan::SetCallAsFunctionHandler(v8::Local<v8::ObjectTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>())
```
Calls the `ObjectTemplate`'s [`SetCallAsFunctionHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#a5e9612fc80bf6db8f2da199b9b0bd04e).

147
node_modules/nan/doc/new.md generated vendored Normal file
View File

@ -0,0 +1,147 @@
## New
NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
- <a href="#api_nan_new"><b><code>Nan::New()</code></b></a>
- <a href="#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a>
- <a href="#api_nan_null"><b><code>Nan::Null()</code></b></a>
- <a href="#api_nan_true"><b><code>Nan::True()</code></b></a>
- <a href="#api_nan_false"><b><code>Nan::False()</code></b></a>
- <a href="#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a>
<a name="api_nan_new"></a>
### Nan::New()
`Nan::New()` should be used to instantiate new JavaScript objects.
Refer to the specific V8 type in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/d1/d83/classv8_1_1_data.html) for information on the types of arguments required for instantiation.
Signatures:
Return types are mostly omitted from the signatures for simplicity. In most cases the type will be contained within a `v8::Local<T>`. The following types will be contained within a `Nan::MaybeLocal<T>`: `v8::String`, `v8::Date`, `v8::RegExp`, `v8::Script`, `v8::UnboundScript`.
Empty objects:
```c++
Nan::New<T>();
```
Generic single and multiple-argument:
```c++
Nan::New<T>(A0 arg0);
Nan::New<T>(A0 arg0, A1 arg1);
Nan::New<T>(A0 arg0, A1 arg1, A2 arg2);
Nan::New<T>(A0 arg0, A1 arg1, A2 arg2, A3 arg3);
```
For creating `v8::FunctionTemplate` and `v8::Function` objects:
_The definition of `Nan::FunctionCallback` can be found in the [Method declaration](./methods.md#api_nan_method) documentation._
```c++
Nan::New<T>(Nan::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>());
Nan::New<T>(Nan::FunctionCallback callback,
v8::Local<v8::Value> data = v8::Local<v8::Value>(),
A2 a2 = A2());
```
Native number types:
```c++
v8::Local<v8::Boolean> Nan::New<T>(bool value);
v8::Local<v8::Int32> Nan::New<T>(int32_t value);
v8::Local<v8::Uint32> Nan::New<T>(uint32_t value);
v8::Local<v8::Number> Nan::New<T>(double value);
```
String types:
```c++
Nan::MaybeLocal<v8::String> Nan::New<T>(std::string const& value);
Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value, int length);
Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value);
Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value);
Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value, int length);
```
Specialized types:
```c++
v8::Local<v8::String> Nan::New<T>(v8::String::ExternalStringResource * value);
v8::Local<v8::String> Nan::New<T>(Nan::ExternalOneByteStringResource * value);
v8::Local<v8::RegExp> Nan::New<T>(v8::Local<v8::String> pattern, v8::RegExp::Flags flags);
```
Note that `Nan::ExternalOneByteStringResource` maps to [`v8::String::ExternalOneByteStringResource`](https://v8docs.nodesource.com/node-8.16/d9/db3/classv8_1_1_string_1_1_external_one_byte_string_resource.html), and `v8::String::ExternalAsciiStringResource` in older versions of V8.
<a name="api_nan_undefined"></a>
### Nan::Undefined()
A helper method to reference the `v8::Undefined` object in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Primitive> Nan::Undefined()
```
<a name="api_nan_null"></a>
### Nan::Null()
A helper method to reference the `v8::Null` object in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Primitive> Nan::Null()
```
<a name="api_nan_true"></a>
### Nan::True()
A helper method to reference the `v8::Boolean` object representing the `true` value in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Boolean> Nan::True()
```
<a name="api_nan_false"></a>
### Nan::False()
A helper method to reference the `v8::Boolean` object representing the `false` value in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Boolean> Nan::False()
```
<a name="api_nan_empty_string"></a>
### Nan::EmptyString()
Call [`v8::String::Empty`](https://v8docs.nodesource.com/node-8.16/d2/db3/classv8_1_1_string.html#a7c1bc8886115d7ee46f1d571dd6ebc6d) to reference the empty string in a way that is compatible across all supported versions of V8.
Signature:
```c++
v8::Local<v8::String> Nan::EmptyString()
```
<a name="api_nan_new_one_byte_string"></a>
### Nan::NewOneByteString()
An implementation of [`v8::String::NewFromOneByte()`](https://v8docs.nodesource.com/node-8.16/d2/db3/classv8_1_1_string.html#a5264d50b96d2c896ce525a734dc10f09) provided for consistent availability and API across supported versions of V8. Allocates a new string from Latin-1 data.
Signature:
```c++
Nan::MaybeLocal<v8::String> Nan::NewOneByteString(const uint8_t * value,
int length = -1)
```

123
node_modules/nan/doc/node_misc.md generated vendored Normal file
View File

@ -0,0 +1,123 @@
## Miscellaneous Node Helpers
- <a href="#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a>
- <a href="#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a>
- <a href="#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a>
- <a href="#api_nan_export"><b><code>Nan::Export()</code></b></a>
<a name="api_nan_asyncresource"></a>
### Nan::AsyncResource
This class is analogous to the `AsyncResource` JavaScript class exposed by Node's [async_hooks][] API.
When calling back into JavaScript asynchronously, special care must be taken to ensure that the runtime can properly track
async hops. `Nan::AsyncResource` is a class that provides an RAII wrapper around `node::EmitAsyncInit`, `node::EmitAsyncDestroy`,
and `node::MakeCallback`. Using this mechanism to call back into JavaScript, as opposed to `Nan::MakeCallback` or
`v8::Function::Call` ensures that the callback is executed in the correct async context. This ensures that async mechanisms
such as domains and [async_hooks][] function correctly.
Definition:
```c++
class AsyncResource {
public:
AsyncResource(v8::Local<v8::String> name,
v8::Local<v8::Object> resource = New<v8::Object>());
AsyncResource(const char* name,
v8::Local<v8::Object> resource = New<v8::Object>());
~AsyncResource();
v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
v8::Local<v8::Function> func,
int argc,
v8::Local<v8::Value>* argv);
v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
v8::Local<v8::String> symbol,
int argc,
v8::Local<v8::Value>* argv);
v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target,
const char* method,
int argc,
v8::Local<v8::Value>* argv);
};
```
* `name`: Identifier for the kind of resource that is being provided for diagnostics information exposed by the [async_hooks][]
API. This will be passed to the possible `init` hook as the `type`. To avoid name collisions with other modules we recommend
that the name include the name of the owning module as a prefix. For example `mysql` module could use something like
`mysql:batch-db-query-resource`.
* `resource`: An optional object associated with the async work that will be passed to the possible [async_hooks][]
`init` hook. If this parameter is omitted, or an empty handle is provided, this object will be created automatically.
* When calling JS on behalf of this resource, one can use `runInAsyncScope`. This will ensure that the callback runs in the
correct async execution context.
* `AsyncDestroy` is automatically called when an AsyncResource object is destroyed.
For more details, see the Node [async_hooks][] documentation. You might also want to take a look at the documentation for the
[N-API counterpart][napi]. For example usage, see the `asyncresource.cpp` example in the `test/cpp` directory.
<a name="api_nan_make_callback"></a>
### Nan::MakeCallback()
Deprecated wrappers around the legacy `node::MakeCallback()` APIs. Node.js 10+
has deprecated these legacy APIs as they do not provide a mechanism to preserve
async context.
We recommend that you use the `AsyncResource` class and `AsyncResource::runInAsyncScope` instead of using `Nan::MakeCallback` or
`v8::Function#Call()` directly. `AsyncResource` properly takes care of running the callback in the correct async execution
context something that is essential for functionality like domains, async_hooks and async debugging.
Signatures:
```c++
NAN_DEPRECATED
v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
v8::Local<v8::Function> func,
int argc,
v8::Local<v8::Value>* argv);
NAN_DEPRECATED
v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
v8::Local<v8::String> symbol,
int argc,
v8::Local<v8::Value>* argv);
NAN_DEPRECATED
v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target,
const char* method,
int argc,
v8::Local<v8::Value>* argv);
```
<a name="api_nan_module_init"></a>
### NAN_MODULE_INIT()
Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object.
See example below.
<a name="api_nan_export"></a>
### Nan::Export()
A simple helper to register a `v8::FunctionTemplate` from a JavaScript-accessible method (see [Methods](./methods.md)) as a property on an object. Can be used in a way similar to assigning properties to `module.exports` in JavaScript.
Signature:
```c++
void Export(v8::Local<v8::Object> target, const char *name, Nan::FunctionCallback f)
```
Also available as the shortcut `NAN_EXPORT` macro.
Example:
```c++
NAN_METHOD(Foo) {
...
}
NAN_MODULE_INIT(Init) {
NAN_EXPORT(target, Foo);
}
```
[async_hooks]: https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html
[napi]: https://nodejs.org/dist/latest-v9.x/docs/api/n-api.html#n_api_custom_asynchronous_operations

263
node_modules/nan/doc/object_wrappers.md generated vendored Normal file
View File

@ -0,0 +1,263 @@
## Object Wrappers
The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects.
- <a href="#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a>
<a name="api_nan_object_wrap"></a>
### Nan::ObjectWrap()
A reimplementation of `node::ObjectWrap` that adds some API not present in older versions of Node. Should be preferred over `node::ObjectWrap` in all cases for consistency.
Definition:
```c++
class ObjectWrap {
public:
ObjectWrap();
virtual ~ObjectWrap();
template <class T>
static inline T* Unwrap(v8::Local<v8::Object> handle);
inline v8::Local<v8::Object> handle();
inline Nan::Persistent<v8::Object>& persistent();
protected:
inline void Wrap(v8::Local<v8::Object> handle);
inline void MakeWeak();
/* Ref() marks the object as being attached to an event loop.
* Refed objects will not be garbage collected, even if
* all references are lost.
*/
virtual void Ref();
/* Unref() marks an object as detached from the event loop. This is its
* default state. When an object with a "weak" reference changes from
* attached to detached state it will be freed. Be careful not to access
* the object after making this call as it might be gone!
* (A "weak reference" means an object that only has a
* persistent handle.)
*
* DO NOT CALL THIS FROM DESTRUCTOR
*/
virtual void Unref();
int refs_; // ro
};
```
See the Node documentation on [Wrapping C++ Objects](https://nodejs.org/api/addons.html#addons_wrapping_c_objects) for more details.
### This vs. Holder
When calling `Unwrap`, it is important that the argument is indeed some JavaScript object which got wrapped by a `Wrap` call for this class or any derived class.
The `Signature` installed by [`Nan::SetPrototypeMethod()`](methods.md#api_nan_set_prototype_method) does ensure that `info.Holder()` is just such an instance.
In Node 0.12 and later, `info.This()` will also be of such a type, since otherwise the invocation will get rejected.
However, in Node 0.10 and before it was possible to invoke a method on a JavaScript object which just had the extension type in its prototype chain.
In such a situation, calling `Unwrap` on `info.This()` will likely lead to a failed assertion causing a crash, but could lead to even more serious corruption.
On the other hand, calling `Unwrap` in an [accessor](methods.md#api_nan_set_accessor) should not use `Holder()` if the accessor is defined on the prototype.
So either define your accessors on the instance template,
or use `This()` after verifying that it is indeed a valid object.
### Examples
#### Basic
```c++
class MyObject : public Nan::ObjectWrap {
public:
static NAN_MODULE_INIT(Init) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("MyObject").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle);
Nan::SetPrototypeMethod(tpl, "getValue", GetValue);
constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
Nan::Set(target, Nan::New("MyObject").ToLocalChecked(),
Nan::GetFunction(tpl).ToLocalChecked());
}
private:
explicit MyObject(double value = 0) : value_(value) {}
~MyObject() {}
static NAN_METHOD(New) {
if (info.IsConstructCall()) {
double value = info[0]->IsUndefined() ? 0 : Nan::To<double>(info[0]).FromJust();
MyObject *obj = new MyObject(value);
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
const int argc = 1;
v8::Local<v8::Value> argv[argc] = {info[0]};
v8::Local<v8::Function> cons = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
}
static NAN_METHOD(GetHandle) {
MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder());
info.GetReturnValue().Set(obj->handle());
}
static NAN_METHOD(GetValue) {
MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder());
info.GetReturnValue().Set(obj->value_);
}
static inline Nan::Persistent<v8::Function> & constructor() {
static Nan::Persistent<v8::Function> my_constructor;
return my_constructor;
}
double value_;
};
NODE_MODULE(objectwrapper, MyObject::Init)
```
To use in Javascript:
```Javascript
var objectwrapper = require('bindings')('objectwrapper');
var obj = new objectwrapper.MyObject(5);
console.log('Should be 5: ' + obj.getValue());
```
#### Factory of wrapped objects
```c++
class MyFactoryObject : public Nan::ObjectWrap {
public:
static NAN_MODULE_INIT(Init) {
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "getValue", GetValue);
constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
}
static NAN_METHOD(NewInstance) {
v8::Local<v8::Function> cons = Nan::New(constructor());
double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0;
const int argc = 1;
v8::Local<v8::Value> argv[1] = {Nan::New(value)};
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
// Needed for the next example:
inline double value() const {
return value_;
}
private:
explicit MyFactoryObject(double value = 0) : value_(value) {}
~MyFactoryObject() {}
static NAN_METHOD(New) {
if (info.IsConstructCall()) {
double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0;
MyFactoryObject * obj = new MyFactoryObject(value);
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
const int argc = 1;
v8::Local<v8::Value> argv[argc] = {info[0]};
v8::Local<v8::Function> cons = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
}
static NAN_METHOD(GetValue) {
MyFactoryObject* obj = ObjectWrap::Unwrap<MyFactoryObject>(info.Holder());
info.GetReturnValue().Set(obj->value_);
}
static inline Nan::Persistent<v8::Function> & constructor() {
static Nan::Persistent<v8::Function> my_constructor;
return my_constructor;
}
double value_;
};
NAN_MODULE_INIT(Init) {
MyFactoryObject::Init(target);
Nan::Set(target,
Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked()
);
}
NODE_MODULE(wrappedobjectfactory, Init)
```
To use in Javascript:
```Javascript
var wrappedobjectfactory = require('bindings')('wrappedobjectfactory');
var obj = wrappedobjectfactory.newFactoryObjectInstance(10);
console.log('Should be 10: ' + obj.getValue());
```
#### Passing wrapped objects around
Use the `MyFactoryObject` class above along with the following:
```c++
static NAN_METHOD(Sum) {
Nan::MaybeLocal<v8::Object> maybe1 = Nan::To<v8::Object>(info[0]);
Nan::MaybeLocal<v8::Object> maybe2 = Nan::To<v8::Object>(info[1]);
// Quick check:
if (maybe1.IsEmpty() || maybe2.IsEmpty()) {
// return value is undefined by default
return;
}
MyFactoryObject* obj1 =
Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe1.ToLocalChecked());
MyFactoryObject* obj2 =
Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe2.ToLocalChecked());
info.GetReturnValue().Set(Nan::New<v8::Number>(obj1->value() + obj2->value()));
}
NAN_MODULE_INIT(Init) {
MyFactoryObject::Init(target);
Nan::Set(target,
Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked()
);
Nan::Set(target,
Nan::New<v8::String>("sum").ToLocalChecked(),
Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Sum)).ToLocalChecked()
);
}
NODE_MODULE(myaddon, Init)
```
To use in Javascript:
```Javascript
var myaddon = require('bindings')('myaddon');
var obj1 = myaddon.newFactoryObjectInstance(5);
var obj2 = myaddon.newFactoryObjectInstance(10);
console.log('sum of object values: ' + myaddon.sum(obj1, obj2));
```

296
node_modules/nan/doc/persistent.md generated vendored Normal file
View File

@ -0,0 +1,296 @@
## Persistent references
An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed.
Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported.
- <a href="#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a>
- <a href="#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a>
- <a href="#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a>
- <a href="#api_nan_persistent"><b><code>Nan::Persistent</code></b></a>
- <a href="#api_nan_global"><b><code>Nan::Global</code></b></a>
- <a href="#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a>
- <a href="#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles).
<a name="api_nan_persistent_base"></a>
### Nan::PersistentBase & v8::PersistentBase
A persistent handle contains a reference to a storage cell in V8 which holds an object value and which is updated by the garbage collector whenever the object is moved. A new storage cell can be created using the constructor or `Nan::PersistentBase::Reset()`. Existing handles can be disposed using an argument-less `Nan::PersistentBase::Reset()`.
Definition:
_(note: this is implemented as `Nan::PersistentBase` for older versions of V8 and the native `v8::PersistentBase` is used for newer versions of V8)_
```c++
template<typename T> class PersistentBase {
public:
/**
* If non-empty, destroy the underlying storage cell
*/
void Reset();
/**
* If non-empty, destroy the underlying storage cell and create a new one with
* the contents of another if it is also non-empty
*/
template<typename S> void Reset(const v8::Local<S> &other);
/**
* If non-empty, destroy the underlying storage cell and create a new one with
* the contents of another if it is also non-empty
*/
template<typename S> void Reset(const PersistentBase<S> &other);
/** Returns true if the handle is empty. */
bool IsEmpty() const;
/**
* If non-empty, destroy the underlying storage cell
* IsEmpty() will return true after this call.
*/
void Empty();
template<typename S> bool operator==(const PersistentBase<S> &that);
template<typename S> bool operator==(const v8::Local<S> &that);
template<typename S> bool operator!=(const PersistentBase<S> &that);
template<typename S> bool operator!=(const v8::Local<S> &that);
/**
* Install a finalization callback on this object.
* NOTE: There is no guarantee as to *when* or even *if* the callback is
* invoked. The invocation is performed solely on a best effort basis.
* As always, GC-based finalization should *not* be relied upon for any
* critical form of resource management! At the moment you can either
* specify a parameter for the callback or the location of two internal
* fields in the dying object.
*/
template<typename P>
void SetWeak(P *parameter,
typename WeakCallbackInfo<P>::Callback callback,
WeakCallbackType type);
void ClearWeak();
/**
* Marks the reference to this object independent. Garbage collector is free
* to ignore any object groups containing this object. Weak callback for an
* independent handle should not assume that it will be preceded by a global
* GC prologue callback or followed by a global GC epilogue callback.
*/
void MarkIndependent() const;
bool IsIndependent() const;
/** Checks if the handle holds the only reference to an object. */
bool IsNearDeath() const;
/** Returns true if the handle's reference is weak. */
bool IsWeak() const
};
```
See the V8 documentation for [`PersistentBase`](https://v8docs.nodesource.com/node-8.16/d4/dca/classv8_1_1_persistent_base.html) for further information.
**Tip:** To get a `v8::Local` reference to the original object back from a `PersistentBase` or `Persistent` object:
```c++
v8::Local<v8::Object> object = Nan::New(persistent);
```
<a name="api_nan_non_copyable_persistent_traits"></a>
### Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits
Default traits for `Nan::Persistent`. This class does not allow use of the a copy constructor or assignment operator. At present `kResetInDestructor` is not set, but that will change in a future version.
Definition:
_(note: this is implemented as `Nan::NonCopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_
```c++
template<typename T> class NonCopyablePersistentTraits {
public:
typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
static const bool kResetInDestructor = false;
template<typename S, typename M>
static void Copy(const Persistent<S, M> &source,
NonCopyablePersistent *dest);
template<typename O> static void Uncompilable();
};
```
See the V8 documentation for [`NonCopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.16/de/d73/classv8_1_1_non_copyable_persistent_traits.html) for further information.
<a name="api_nan_copyable_persistent_traits"></a>
### Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits
A helper class of traits to allow copying and assignment of `Persistent`. This will clone the contents of storage cell, but not any of the flags, etc..
Definition:
_(note: this is implemented as `Nan::CopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_
```c++
template<typename T>
class CopyablePersistentTraits {
public:
typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
static const bool kResetInDestructor = true;
template<typename S, typename M>
static void Copy(const Persistent<S, M> &source,
CopyablePersistent *dest);
};
```
See the V8 documentation for [`CopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.16/da/d5c/structv8_1_1_copyable_persistent_traits.html) for further information.
<a name="api_nan_persistent"></a>
### Nan::Persistent
A type of `PersistentBase` which allows copy and assignment. Copy, assignment and destructor behavior is controlled by the traits class `M`.
Definition:
```c++
template<typename T, typename M = NonCopyablePersistentTraits<T> >
class Persistent;
template<typename T, typename M> class Persistent : public PersistentBase<T> {
public:
/**
* A Persistent with no storage cell.
*/
Persistent();
/**
* Construct a Persistent from a v8::Local. When the v8::Local is non-empty, a
* new storage cell is created pointing to the same object, and no flags are
* set.
*/
template<typename S> Persistent(v8::Local<S> that);
/**
* Construct a Persistent from a Persistent. When the Persistent is non-empty,
* a new storage cell is created pointing to the same object, and no flags are
* set.
*/
Persistent(const Persistent &that);
/**
* The copy constructors and assignment operator create a Persistent exactly
* as the Persistent constructor, but the Copy function from the traits class
* is called, allowing the setting of flags based on the copied Persistent.
*/
Persistent &operator=(const Persistent &that);
template <typename S, typename M2>
Persistent &operator=(const Persistent<S, M2> &that);
/**
* The destructor will dispose the Persistent based on the kResetInDestructor
* flags in the traits class. Since not calling dispose can result in a
* memory leak, it is recommended to always set this flag.
*/
~Persistent();
};
```
See the V8 documentation for [`Persistent`](https://v8docs.nodesource.com/node-8.16/d2/d78/classv8_1_1_persistent.html) for further information.
<a name="api_nan_global"></a>
### Nan::Global
A type of `PersistentBase` which has move semantics.
```c++
template<typename T> class Global : public PersistentBase<T> {
public:
/**
* A Global with no storage cell.
*/
Global();
/**
* Construct a Global from a v8::Local. When the v8::Local is non-empty, a new
* storage cell is created pointing to the same object, and no flags are set.
*/
template<typename S> Global(v8::Local<S> that);
/**
* Construct a Global from a PersistentBase. When the Persistent is non-empty,
* a new storage cell is created pointing to the same object, and no flags are
* set.
*/
template<typename S> Global(const PersistentBase<S> &that);
/**
* Pass allows returning globals from functions, etc.
*/
Global Pass();
};
```
See the V8 documentation for [`Global`](https://v8docs.nodesource.com/node-8.16/d5/d40/classv8_1_1_global.html) for further information.
<a name="api_nan_weak_callback_info"></a>
### Nan::WeakCallbackInfo
`Nan::WeakCallbackInfo` is used as an argument when setting a persistent reference as weak. You may need to free any external resources attached to the object. It is a mirror of `v8:WeakCallbackInfo` as found in newer versions of V8.
Definition:
```c++
template<typename T> class WeakCallbackInfo {
public:
typedef void (*Callback)(const WeakCallbackInfo<T>& data);
v8::Isolate *GetIsolate() const;
/**
* Get the parameter that was associated with the weak handle.
*/
T *GetParameter() const;
/**
* Get pointer from internal field, index can be 0 or 1.
*/
void *GetInternalField(int index) const;
};
```
Example usage:
```c++
void weakCallback(const WeakCallbackInfo<int> &data) {
int *parameter = data.GetParameter();
delete parameter;
}
Persistent<v8::Object> obj;
int *data = new int(0);
obj.SetWeak(data, callback, WeakCallbackType::kParameter);
```
See the V8 documentation for [`WeakCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d8/d06/classv8_1_1_weak_callback_info.html) for further information.
<a name="api_nan_weak_callback_type"></a>
### Nan::WeakCallbackType
Represents the type of a weak callback.
A weak callback of type `kParameter` makes the supplied parameter to `Nan::PersistentBase::SetWeak` available through `WeakCallbackInfo::GetParameter`.
A weak callback of type `kInternalFields` uses up to two internal fields at indices 0 and 1 on the `Nan::PersistentBase<v8::Object>` being made weak.
Note that only `v8::Object`s and derivatives can have internal fields.
Definition:
```c++
enum class WeakCallbackType { kParameter, kInternalFields };
```

73
node_modules/nan/doc/scopes.md generated vendored Normal file
View File

@ -0,0 +1,73 @@
## Scopes
A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works.
A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope.
The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
- <a href="#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a>
- <a href="#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a>
Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection).
<a name="api_nan_handle_scope"></a>
### Nan::HandleScope
A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/node-8.16/d3/d95/classv8_1_1_handle_scope.html).
Definition:
```c++
class Nan::HandleScope {
public:
Nan::HandleScope();
static int NumberOfHandles();
};
```
Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself.
Example:
```c++
// new object is created, it needs a new scope:
void Pointless() {
Nan::HandleScope scope;
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
}
// JavaScript-accessible method already has a HandleScope
NAN_METHOD(Pointless2) {
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
}
```
<a name="api_nan_escapable_handle_scope"></a>
### Nan::EscapableHandleScope
Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it.
Definition:
```c++
class Nan::EscapableHandleScope {
public:
Nan::EscapableHandleScope();
static int NumberOfHandles();
template<typename T> v8::Local<T> Escape(v8::Local<T> value);
}
```
Use `Escape(value)` to return the object.
Example:
```c++
v8::Local<v8::Object> EmptyObj() {
Nan::EscapableHandleScope scope;
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
return scope.Escape(obj);
}
```

38
node_modules/nan/doc/script.md generated vendored Normal file
View File

@ -0,0 +1,38 @@
## Script
NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8.
- <a href="#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a>
- <a href="#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a>
<a name="api_nan_compile_script"></a>
### Nan::CompileScript()
A wrapper around [`v8::ScriptCompiler::Compile()`](https://v8docs.nodesource.com/node-8.16/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b).
Note that `Nan::BoundScript` is an alias for `v8::Script`.
Signature:
```c++
Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(
v8::Local<v8::String> s,
const v8::ScriptOrigin& origin);
Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(v8::Local<v8::String> s);
```
<a name="api_nan_run_script"></a>
### Nan::RunScript()
Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`.
Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8.
Signature:
```c++
Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::UnboundScript> script)
Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::BoundScript> script)
```

62
node_modules/nan/doc/string_bytes.md generated vendored Normal file
View File

@ -0,0 +1,62 @@
## Strings & Bytes
Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing.
- <a href="#api_nan_encoding"><b><code>Nan::Encoding</code></b></a>
- <a href="#api_nan_encode"><b><code>Nan::Encode()</code></b></a>
- <a href="#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a>
- <a href="#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a>
<a name="api_nan_encoding"></a>
### Nan::Encoding
An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node.
Definition:
```c++
enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER }
```
<a name="api_nan_encode"></a>
### Nan::Encode()
A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node.
Signature:
```c++
v8::Local<v8::Value> Nan::Encode(const void *buf,
size_t len,
enum Nan::Encoding encoding = BINARY);
```
<a name="api_nan_decode_bytes"></a>
### Nan::DecodeBytes()
A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node.
Signature:
```c++
ssize_t Nan::DecodeBytes(v8::Local<v8::Value> val,
enum Nan::Encoding encoding = BINARY);
```
<a name="api_nan_decode_write"></a>
### Nan::DecodeWrite()
A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node.
Signature:
```c++
ssize_t Nan::DecodeWrite(char *buf,
size_t len,
v8::Local<v8::Value> val,
enum Nan::Encoding encoding = BINARY);
```

199
node_modules/nan/doc/v8_internals.md generated vendored Normal file
View File

@ -0,0 +1,199 @@
## V8 internals
The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods.
- <a href="#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a>
- <a href="#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a>
- <a href="#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a>
- <a href="#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a>
- <a href="#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a>
- <a href="#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a>
- <a href="#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a>
- <a href="#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a>
- <a href="#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a>
- <a href="#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a>
- <a href="#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a>
- <a href="#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a>
- <a href="#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a>
- <a href="#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a>
- <a href="#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a>
<a name="api_nan_gc_callback"></a>
### NAN_GC_CALLBACK(callbackname)
Use `NAN_GC_CALLBACK` to declare your callbacks for `Nan::AddGCPrologueCallback()` and `Nan::AddGCEpilogueCallback()`. Your new method receives the arguments `v8::GCType type` and `v8::GCCallbackFlags flags`.
```c++
static Nan::Persistent<Function> callback;
NAN_GC_CALLBACK(gcPrologueCallback) {
v8::Local<Value> argv[] = { Nan::New("prologue").ToLocalChecked() };
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(callback), 1, argv);
}
NAN_METHOD(Hook) {
callback.Reset(To<Function>(args[0]).ToLocalChecked());
Nan::AddGCPrologueCallback(gcPrologueCallback);
info.GetReturnValue().Set(info.Holder());
}
```
<a name="api_nan_add_gc_epilogue_callback"></a>
### Nan::AddGCEpilogueCallback()
Signature:
```c++
void Nan::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, v8::GCType gc_type_filter = v8::kGCTypeAll)
```
Calls V8's [`AddGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a580f976e4290cead62c2fc4dd396be3e).
<a name="api_nan_remove_gc_epilogue_callback"></a>
### Nan::RemoveGCEpilogueCallback()
Signature:
```c++
void Nan::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback)
```
Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#adca9294555a3908e9f23c7bb0f0f284c).
<a name="api_nan_add_gc_prologue_callback"></a>
### Nan::AddGCPrologueCallback()
Signature:
```c++
void Nan::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback, v8::GCType gc_type_filter callback)
```
Calls V8's [`AddGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a6dbef303603ebdb03da6998794ea05b8).
<a name="api_nan_remove_gc_prologue_callback"></a>
### Nan::RemoveGCPrologueCallback()
Signature:
```c++
void Nan::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback)
```
Calls V8's [`RemoveGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a5f72c7cda21415ce062bbe5c58abe09e).
<a name="api_nan_get_heap_statistics"></a>
### Nan::GetHeapStatistics()
Signature:
```c++
void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics)
```
Calls V8's [`GetHeapStatistics()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a5593ac74687b713095c38987e5950b34).
<a name="api_nan_set_counter_function"></a>
### Nan::SetCounterFunction()
Signature:
```c++
void Nan::SetCounterFunction(v8::CounterLookupCallback cb)
```
Calls V8's [`SetCounterFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a045d7754e62fa0ec72ae6c259b29af94).
<a name="api_nan_set_create_histogram_function"></a>
### Nan::SetCreateHistogramFunction()
Signature:
```c++
void Nan::SetCreateHistogramFunction(v8::CreateHistogramCallback cb)
```
Calls V8's [`SetCreateHistogramFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a542d67e85089cb3f92aadf032f99e732).
<a name="api_nan_set_add_histogram_sample_function"></a>
### Nan::SetAddHistogramSampleFunction()
Signature:
```c++
void Nan::SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb)
```
Calls V8's [`SetAddHistogramSampleFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#aeb420b690bc2c216882d6fdd00ddd3ea).
<a name="api_nan_idle_notification"></a>
### Nan::IdleNotification()
Signature:
```c++
bool Nan::IdleNotification(int idle_time_in_ms)
```
Calls V8's [`IdleNotification()` or `IdleNotificationDeadline()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ad6a2a02657f5425ad460060652a5a118) depending on V8 version.
<a name="api_nan_low_memory_notification"></a>
### Nan::LowMemoryNotification()
Signature:
```c++
void Nan::LowMemoryNotification()
```
Calls V8's [`LowMemoryNotification()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a24647f61d6b41f69668094bdcd6ea91f).
<a name="api_nan_context_disposed_notification"></a>
### Nan::ContextDisposedNotification()
Signature:
```c++
void Nan::ContextDisposedNotification()
```
Calls V8's [`ContextDisposedNotification()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b).
<a name="api_nan_get_internal_field_pointer"></a>
### Nan::GetInternalFieldPointer()
Gets a pointer to the internal field with at `index` from a V8 `Object` handle.
Signature:
```c++
void* Nan::GetInternalFieldPointer(v8::Local<v8::Object> object, int index)
```
Calls the Object's [`GetAlignedPointerFromInternalField()` or `GetPointerFromInternalField()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a580ea84afb26c005d6762eeb9e3c308f) depending on the version of V8.
<a name="api_nan_set_internal_field_pointer"></a>
### Nan::SetInternalFieldPointer()
Sets the value of the internal field at `index` on a V8 `Object` handle.
Signature:
```c++
void Nan::SetInternalFieldPointer(v8::Local<v8::Object> object, int index, void* value)
```
Calls the Object's [`SetAlignedPointerInInternalField()` or `SetPointerInInternalField()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab3c57184263cf29963ef0017bec82281) depending on the version of V8.
<a name="api_nan_adjust_external_memory"></a>
### Nan::AdjustExternalMemory()
Signature:
```c++
int Nan::AdjustExternalMemory(int bytesChange)
```
Calls V8's [`AdjustAmountOfExternalAllocatedMemory()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ae1a59cac60409d3922582c4af675473e).

85
node_modules/nan/doc/v8_misc.md generated vendored Normal file
View File

@ -0,0 +1,85 @@
## Miscellaneous V8 Helpers
- <a href="#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a>
- <a href="#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a>
- <a href="#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a>
- <a href="#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a>
- <a href="#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a>
<a name="api_nan_utf8_string"></a>
### Nan::Utf8String
Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object.
An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/node-8.16/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8.
Definition:
```c++
class Nan::Utf8String {
public:
Nan::Utf8String(v8::Local<v8::Value> from);
int length() const;
char* operator*();
const char* operator*() const;
};
```
<a name="api_nan_get_current_context"></a>
### Nan::GetCurrentContext()
A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8.
Signature:
```c++
v8::Local<v8::Context> Nan::GetCurrentContext()
```
<a name="api_nan_set_isolate_data"></a>
### Nan::SetIsolateData()
A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36).
Signature:
```c++
void Nan::SetIsolateData(v8::Isolate *isolate, T *data)
```
<a name="api_nan_get_isolate_data"></a>
### Nan::GetIsolateData()
A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257).
Signature:
```c++
T *Nan::GetIsolateData(v8::Isolate *isolate)
```
<a name="api_nan_typedarray_contents"></a>
### Nan::TypedArrayContents<T>
A helper class for accessing the contents of an ArrayBufferView (aka a typedarray) from C++. If the input array is not a valid typedarray, then the data pointer of TypedArrayContents will default to `NULL` and the length will be 0. If the data pointer is not compatible with the alignment requirements of type, an assertion error will fail.
Note that you must store a reference to the `array` object while you are accessing its contents.
Definition:
```c++
template<typename T>
class Nan::TypedArrayContents {
public:
TypedArrayContents(v8::Local<Value> array);
size_t length() const;
T* const operator*();
const T* const operator*() const;
};
```

1
node_modules/nan/include_dirs.js generated vendored Normal file
View File

@ -0,0 +1 @@
console.log(require('path').relative('.', __dirname));

2898
node_modules/nan/nan.h generated vendored Normal file

File diff suppressed because it is too large Load Diff

88
node_modules/nan/nan_callbacks.h generated vendored Normal file
View File

@ -0,0 +1,88 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_H_
#define NAN_CALLBACKS_H_
template<typename T> class FunctionCallbackInfo;
template<typename T> class PropertyCallbackInfo;
template<typename T> class Global;
typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&);
typedef void(*GetterCallback)
(v8::Local<v8::String>, const PropertyCallbackInfo<v8::Value>&);
typedef void(*SetterCallback)(
v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<void>&);
typedef void(*PropertyGetterCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*PropertySetterCallback)(
v8::Local<v8::String>,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*PropertyEnumeratorCallback)
(const PropertyCallbackInfo<v8::Array>&);
typedef void(*PropertyDeleterCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Boolean>&);
typedef void(*PropertyQueryCallback)(
v8::Local<v8::String>,
const PropertyCallbackInfo<v8::Integer>&);
typedef void(*IndexGetterCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*IndexSetterCallback)(
uint32_t,
v8::Local<v8::Value>,
const PropertyCallbackInfo<v8::Value>&);
typedef void(*IndexEnumeratorCallback)
(const PropertyCallbackInfo<v8::Array>&);
typedef void(*IndexDeleterCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Boolean>&);
typedef void(*IndexQueryCallback)(
uint32_t,
const PropertyCallbackInfo<v8::Integer>&);
namespace imp {
typedef v8::Local<v8::AccessorSignature> Sig;
static const int kDataIndex = 0;
static const int kFunctionIndex = 1;
static const int kFunctionFieldCount = 2;
static const int kGetterIndex = 1;
static const int kSetterIndex = 2;
static const int kAccessorFieldCount = 3;
static const int kPropertyGetterIndex = 1;
static const int kPropertySetterIndex = 2;
static const int kPropertyEnumeratorIndex = 3;
static const int kPropertyDeleterIndex = 4;
static const int kPropertyQueryIndex = 5;
static const int kPropertyFieldCount = 6;
static const int kIndexPropertyGetterIndex = 1;
static const int kIndexPropertySetterIndex = 2;
static const int kIndexPropertyEnumeratorIndex = 3;
static const int kIndexPropertyDeleterIndex = 4;
static const int kIndexPropertyQueryIndex = 5;
static const int kIndexPropertyFieldCount = 6;
} // end of namespace imp
#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION
# include "nan_callbacks_12_inl.h" // NOLINT(build/include)
#else
# include "nan_callbacks_pre_12_inl.h" // NOLINT(build/include)
#endif
#endif // NAN_CALLBACKS_H_

514
node_modules/nan/nan_callbacks_12_inl.h generated vendored Normal file
View File

@ -0,0 +1,514 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_12_INL_H_
#define NAN_CALLBACKS_12_INL_H_
template<typename T>
class ReturnValue {
v8::ReturnValue<T> value_;
public:
template <class S>
explicit inline ReturnValue(const v8::ReturnValue<S> &value) :
value_(value) {}
template <class S>
explicit inline ReturnValue(const ReturnValue<S>& that)
: value_(that.value_) {
TYPE_CHECK(T, S);
}
// Handle setters
template <typename S> inline void Set(const v8::Local<S> &handle) {
TYPE_CHECK(T, S);
value_.Set(handle);
}
template <typename S> inline void Set(const Global<S> &handle) {
TYPE_CHECK(T, S);
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && \
(V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 && \
defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8))))
value_.Set(handle);
#else
value_.Set(*reinterpret_cast<const v8::Persistent<S>*>(&handle));
const_cast<Global<S> &>(handle).Reset();
#endif
}
// Fast primitive setters
inline void Set(bool value) {
TYPE_CHECK(T, v8::Boolean);
value_.Set(value);
}
inline void Set(double i) {
TYPE_CHECK(T, v8::Number);
value_.Set(i);
}
inline void Set(int32_t i) {
TYPE_CHECK(T, v8::Integer);
value_.Set(i);
}
inline void Set(uint32_t i) {
TYPE_CHECK(T, v8::Integer);
value_.Set(i);
}
// Fast JS primitive setters
inline void SetNull() {
TYPE_CHECK(T, v8::Primitive);
value_.SetNull();
}
inline void SetUndefined() {
TYPE_CHECK(T, v8::Primitive);
value_.SetUndefined();
}
inline void SetEmptyString() {
TYPE_CHECK(T, v8::String);
value_.SetEmptyString();
}
// Convenience getter for isolate
inline v8::Isolate *GetIsolate() const {
return value_.GetIsolate();
}
// Pointer setter: Uncompilable to prevent inadvertent misuse.
template<typename S>
inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
};
template<typename T>
class FunctionCallbackInfo {
const v8::FunctionCallbackInfo<T> &info_;
const v8::Local<v8::Value> data_;
public:
explicit inline FunctionCallbackInfo(
const v8::FunctionCallbackInfo<T> &info
, v8::Local<v8::Value> data) :
info_(info)
, data_(data) {}
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(info_.GetReturnValue());
}
#if NODE_MAJOR_VERSION < 10
inline v8::Local<v8::Function> Callee() const { return info_.Callee(); }
#endif
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
inline bool IsConstructCall() const { return info_.IsConstructCall(); }
inline int Length() const { return info_.Length(); }
inline v8::Local<v8::Value> operator[](int i) const { return info_[i]; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kCalleeIndex = 5;
static const int kContextSaveIndex = 6;
static const int kArgsLength = 7;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
};
template<typename T>
class PropertyCallbackInfo {
const v8::PropertyCallbackInfo<T> &info_;
const v8::Local<v8::Value> data_;
public:
explicit inline PropertyCallbackInfo(
const v8::PropertyCallbackInfo<T> &info
, const v8::Local<v8::Value> data) :
info_(info)
, data_(data) {}
inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(info_.GetReturnValue());
}
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kThisIndex = 5;
static const int kArgsLength = 6;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo)
};
namespace imp {
static
void FunctionCallbackWrapper(const v8::FunctionCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
FunctionCallback callback = reinterpret_cast<FunctionCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
FunctionCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
callback(cbinfo);
}
typedef void (*NativeFunction)(const v8::FunctionCallbackInfo<v8::Value> &);
#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
static
void GetterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativeGetter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void SetterCallbackWrapper(
v8::Local<v8::Name> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<void> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property.As<v8::String>(), value, cbinfo);
}
typedef void (*NativeSetter)(
v8::Local<v8::Name>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<void> &);
#else
static
void GetterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativeGetter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void SetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<void> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativeSetter)(
v8::Local<v8::String>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<void> &);
#endif
#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION
static
void PropertyGetterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativePropertyGetter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertySetterCallbackWrapper(
v8::Local<v8::Name> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), value, cbinfo);
}
typedef void (*NativePropertySetter)(
v8::Local<v8::Name>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertyEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativePropertyEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void PropertyDeleterCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (NativePropertyDeleter)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void PropertyQueryCallbackWrapper(
v8::Local<v8::Name> property
, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property.As<v8::String>(), cbinfo);
}
typedef void (*NativePropertyQuery)
(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer> &);
#else
static
void PropertyGetterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativePropertyGetter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertySetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativePropertySetter)(
v8::Local<v8::String>
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void PropertyEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativePropertyEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void PropertyDeleterCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (NativePropertyDeleter)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void PropertyQueryCallbackWrapper(
v8::Local<v8::String> property
, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
}
typedef void (*NativePropertyQuery)
(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Integer> &);
#endif
static
void IndexGetterCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexGetter)
(uint32_t, const v8::PropertyCallbackInfo<v8::Value> &);
static
void IndexSetterCallbackWrapper(
uint32_t index
, v8::Local<v8::Value> value
, const v8::PropertyCallbackInfo<v8::Value> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertySetterIndex)
.As<v8::External>()->Value()));
callback(index, value, cbinfo);
}
typedef void (*NativeIndexSetter)(
uint32_t
, v8::Local<v8::Value>
, const v8::PropertyCallbackInfo<v8::Value> &);
static
void IndexEnumeratorCallbackWrapper(
const v8::PropertyCallbackInfo<v8::Array> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(
kIndexPropertyEnumeratorIndex).As<v8::External>()->Value()));
callback(cbinfo);
}
typedef void (*NativeIndexEnumerator)
(const v8::PropertyCallbackInfo<v8::Array> &);
static
void IndexDeleterCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexDeleter)
(uint32_t, const v8::PropertyCallbackInfo<v8::Boolean> &);
static
void IndexQueryCallbackWrapper(
uint32_t index, const v8::PropertyCallbackInfo<v8::Integer> &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
}
typedef void (*NativeIndexQuery)
(uint32_t, const v8::PropertyCallbackInfo<v8::Integer> &);
} // end of namespace imp
#endif // NAN_CALLBACKS_12_INL_H_

520
node_modules/nan/nan_callbacks_pre_12_inl.h generated vendored Normal file
View File

@ -0,0 +1,520 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CALLBACKS_PRE_12_INL_H_
#define NAN_CALLBACKS_PRE_12_INL_H_
namespace imp {
template<typename T> class ReturnValueImp;
} // end of namespace imp
template<typename T>
class ReturnValue {
v8::Isolate *isolate_;
v8::Persistent<T> *value_;
friend class imp::ReturnValueImp<T>;
public:
template <class S>
explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent<S> *p) :
isolate_(isolate), value_(p) {}
template <class S>
explicit inline ReturnValue(const ReturnValue<S>& that)
: isolate_(that.isolate_), value_(that.value_) {
TYPE_CHECK(T, S);
}
// Handle setters
template <typename S> inline void Set(const v8::Local<S> &handle) {
TYPE_CHECK(T, S);
value_->Dispose();
*value_ = v8::Persistent<T>::New(handle);
}
template <typename S> inline void Set(const Global<S> &handle) {
TYPE_CHECK(T, S);
value_->Dispose();
*value_ = v8::Persistent<T>::New(handle.persistent);
const_cast<Global<S> &>(handle).Reset();
}
// Fast primitive setters
inline void Set(bool value) {
v8::HandleScope scope;
TYPE_CHECK(T, v8::Boolean);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Boolean::New(value));
}
inline void Set(double i) {
v8::HandleScope scope;
TYPE_CHECK(T, v8::Number);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Number::New(i));
}
inline void Set(int32_t i) {
v8::HandleScope scope;
TYPE_CHECK(T, v8::Integer);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Int32::New(i));
}
inline void Set(uint32_t i) {
v8::HandleScope scope;
TYPE_CHECK(T, v8::Integer);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Uint32::NewFromUnsigned(i));
}
// Fast JS primitive setters
inline void SetNull() {
v8::HandleScope scope;
TYPE_CHECK(T, v8::Primitive);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Null());
}
inline void SetUndefined() {
v8::HandleScope scope;
TYPE_CHECK(T, v8::Primitive);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::Undefined());
}
inline void SetEmptyString() {
v8::HandleScope scope;
TYPE_CHECK(T, v8::String);
value_->Dispose();
*value_ = v8::Persistent<T>::New(v8::String::Empty());
}
// Convenience getter for isolate
inline v8::Isolate *GetIsolate() const {
return isolate_;
}
// Pointer setter: Uncompilable to prevent inadvertent misuse.
template<typename S>
inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); }
};
template<typename T>
class FunctionCallbackInfo {
const v8::Arguments &args_;
v8::Local<v8::Value> data_;
ReturnValue<T> return_value_;
v8::Persistent<T> retval_;
public:
explicit inline FunctionCallbackInfo(
const v8::Arguments &args
, v8::Local<v8::Value> data) :
args_(args)
, data_(data)
, return_value_(args.GetIsolate(), &retval_)
, retval_(v8::Persistent<T>::New(v8::Undefined())) {}
inline ~FunctionCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<T> GetReturnValue() const {
return ReturnValue<T>(return_value_);
}
inline v8::Local<v8::Function> Callee() const { return args_.Callee(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> Holder() const { return args_.Holder(); }
inline bool IsConstructCall() const { return args_.IsConstructCall(); }
inline int Length() const { return args_.Length(); }
inline v8::Local<v8::Value> operator[](int i) const { return args_[i]; }
inline v8::Local<v8::Object> This() const { return args_.This(); }
inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kCalleeIndex = 5;
static const int kContextSaveIndex = 6;
static const int kArgsLength = 7;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo)
};
template<typename T>
class PropertyCallbackInfoBase {
const v8::AccessorInfo &info_;
const v8::Local<v8::Value> data_;
public:
explicit inline PropertyCallbackInfoBase(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
info_(info)
, data_(data) {}
inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); }
inline v8::Local<v8::Value> Data() const { return data_; }
inline v8::Local<v8::Object> This() const { return info_.This(); }
inline v8::Local<v8::Object> Holder() const { return info_.Holder(); }
protected:
static const int kHolderIndex = 0;
static const int kIsolateIndex = 1;
static const int kReturnValueDefaultValueIndex = 2;
static const int kReturnValueIndex = 3;
static const int kDataIndex = 4;
static const int kThisIndex = 5;
static const int kArgsLength = 6;
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase)
};
template<typename T>
class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> {
ReturnValue<T> return_value_;
v8::Persistent<T> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
PropertyCallbackInfoBase<T>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<T>::New(v8::Undefined())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<T> GetReturnValue() const { return return_value_; }
};
template<>
class PropertyCallbackInfo<v8::Array> :
public PropertyCallbackInfoBase<v8::Array> {
ReturnValue<v8::Array> return_value_;
v8::Persistent<v8::Array> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
PropertyCallbackInfoBase<v8::Array>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Array>::New(v8::Local<v8::Array>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Array> GetReturnValue() const {
return return_value_;
}
};
template<>
class PropertyCallbackInfo<v8::Boolean> :
public PropertyCallbackInfoBase<v8::Boolean> {
ReturnValue<v8::Boolean> return_value_;
v8::Persistent<v8::Boolean> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
PropertyCallbackInfoBase<v8::Boolean>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Boolean>::New(v8::Local<v8::Boolean>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Boolean> GetReturnValue() const {
return return_value_;
}
};
template<>
class PropertyCallbackInfo<v8::Integer> :
public PropertyCallbackInfoBase<v8::Integer> {
ReturnValue<v8::Integer> return_value_;
v8::Persistent<v8::Integer> retval_;
public:
explicit inline PropertyCallbackInfo(
const v8::AccessorInfo &info
, const v8::Local<v8::Value> data) :
PropertyCallbackInfoBase<v8::Integer>(info, data)
, return_value_(info.GetIsolate(), &retval_)
, retval_(v8::Persistent<v8::Integer>::New(v8::Local<v8::Integer>())) {}
inline ~PropertyCallbackInfo() {
retval_.Dispose();
retval_.Clear();
}
inline ReturnValue<v8::Integer> GetReturnValue() const {
return return_value_;
}
};
namespace imp {
template<typename T>
class ReturnValueImp : public ReturnValue<T> {
public:
explicit ReturnValueImp(ReturnValue<T> that) :
ReturnValue<T>(that) {}
inline v8::Handle<T> Value() {
return *ReturnValue<T>::value_;
}
};
static
v8::Handle<v8::Value> FunctionCallbackWrapper(const v8::Arguments &args) {
v8::Local<v8::Object> obj = args.Data().As<v8::Object>();
FunctionCallback callback = reinterpret_cast<FunctionCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value()));
FunctionCallbackInfo<v8::Value>
cbinfo(args, obj->GetInternalField(kDataIndex));
callback(cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeFunction)(const v8::Arguments &);
static
v8::Handle<v8::Value> GetterCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
GetterCallback callback = reinterpret_cast<GetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kGetterIndex).As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeGetter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
void SetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<void>
cbinfo(info, obj->GetInternalField(kDataIndex));
SetterCallback callback = reinterpret_cast<SetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kSetterIndex).As<v8::External>()->Value()));
callback(property, value, cbinfo);
}
typedef void (*NativeSetter)
(v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> PropertyGetterCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativePropertyGetter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> PropertySetterCallbackWrapper(
v8::Local<v8::String> property
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertySetterIndex)
.As<v8::External>()->Value()));
callback(property, value, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativePropertySetter)
(v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Array> PropertyEnumeratorCallbackWrapper(
const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyEnumeratorCallback callback =
reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Array> (*NativePropertyEnumerator)
(const v8::AccessorInfo &);
static
v8::Handle<v8::Boolean> PropertyDeleterCallbackWrapper(
v8::Local<v8::String> property
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Boolean> (NativePropertyDeleter)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Integer> PropertyQueryCallbackWrapper(
v8::Local<v8::String> property, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(property, cbinfo);
return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Integer> (*NativePropertyQuery)
(v8::Local<v8::String>, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> IndexGetterCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyGetterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeIndexGetter)
(uint32_t, const v8::AccessorInfo &);
static
v8::Handle<v8::Value> IndexSetterCallbackWrapper(
uint32_t index
, v8::Local<v8::Value> value
, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Value>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertySetterIndex)
.As<v8::External>()->Value()));
callback(index, value, cbinfo);
return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Value> (*NativeIndexSetter)
(uint32_t, v8::Local<v8::Value>, const v8::AccessorInfo &);
static
v8::Handle<v8::Array> IndexEnumeratorCallbackWrapper(
const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Array>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyEnumeratorIndex)
.As<v8::External>()->Value()));
callback(cbinfo);
return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Array> (*NativeIndexEnumerator)
(const v8::AccessorInfo &);
static
v8::Handle<v8::Boolean> IndexDeleterCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Boolean>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyDeleterIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Boolean> (*NativeIndexDeleter)
(uint32_t, const v8::AccessorInfo &);
static
v8::Handle<v8::Integer> IndexQueryCallbackWrapper(
uint32_t index, const v8::AccessorInfo &info) {
v8::Local<v8::Object> obj = info.Data().As<v8::Object>();
PropertyCallbackInfo<v8::Integer>
cbinfo(info, obj->GetInternalField(kDataIndex));
IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>(
reinterpret_cast<intptr_t>(
obj->GetInternalField(kIndexPropertyQueryIndex)
.As<v8::External>()->Value()));
callback(index, cbinfo);
return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value();
}
typedef v8::Handle<v8::Integer> (*NativeIndexQuery)
(uint32_t, const v8::AccessorInfo &);
} // end of namespace imp
#endif // NAN_CALLBACKS_PRE_12_INL_H_

72
node_modules/nan/nan_converters.h generated vendored Normal file
View File

@ -0,0 +1,72 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_H_
#define NAN_CONVERTERS_H_
namespace imp {
template<typename T> struct ToFactoryBase {
typedef MaybeLocal<T> return_t;
};
template<typename T> struct ValueFactoryBase { typedef Maybe<T> return_t; };
template<typename T> struct ToFactory;
template<>
struct ToFactory<v8::Function> : ToFactoryBase<v8::Function> {
static inline return_t convert(v8::Local<v8::Value> val) {
if (val.IsEmpty() || !val->IsFunction()) return MaybeLocal<v8::Function>();
return MaybeLocal<v8::Function>(val.As<v8::Function>());
}
};
#define X(TYPE) \
template<> \
struct ToFactory<v8::TYPE> : ToFactoryBase<v8::TYPE> { \
static inline return_t convert(v8::Local<v8::Value> val); \
};
X(Boolean)
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
#undef X
#define X(TYPE) \
template<> \
struct ToFactory<TYPE> : ValueFactoryBase<TYPE> { \
static inline return_t convert(v8::Local<v8::Value> val); \
};
X(bool)
X(double)
X(int64_t)
X(uint32_t)
X(int32_t)
#undef X
} // end of namespace imp
template<typename T>
inline
typename imp::ToFactory<T>::return_t To(v8::Local<v8::Value> val) {
return imp::ToFactory<T>::convert(val);
}
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
# include "nan_converters_43_inl.h"
#else
# include "nan_converters_pre_43_inl.h"
#endif
#endif // NAN_CONVERTERS_H_

68
node_modules/nan/nan_converters_43_inl.h generated vendored Normal file
View File

@ -0,0 +1,68 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_43_INL_H_
#define NAN_CONVERTERS_43_INL_H_
#define X(TYPE) \
imp::ToFactory<v8::TYPE>::return_t \
imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \
v8::Isolate *isolate = v8::Isolate::GetCurrent(); \
v8::EscapableHandleScope scope(isolate); \
return scope.Escape( \
val->To ## TYPE(isolate->GetCurrentContext()) \
.FromMaybe(v8::Local<v8::TYPE>())); \
}
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
// V8 <= 7.0
#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0)
X(Boolean)
#else
imp::ToFactory<v8::Boolean>::return_t \
imp::ToFactory<v8::Boolean>::convert(v8::Local<v8::Value> val) { \
v8::Isolate *isolate = v8::Isolate::GetCurrent(); \
v8::EscapableHandleScope scope(isolate); \
return scope.Escape(val->ToBoolean(isolate)); \
}
#endif
#undef X
#define X(TYPE, NAME) \
imp::ToFactory<TYPE>::return_t \
imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \
v8::Isolate *isolate = v8::Isolate::GetCurrent(); \
v8::HandleScope scope(isolate); \
return val->NAME ## Value(isolate->GetCurrentContext()); \
}
X(double, Number)
X(int64_t, Integer)
X(uint32_t, Uint32)
X(int32_t, Int32)
// V8 <= 7.0
#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0)
X(bool, Boolean)
#else
imp::ToFactory<bool>::return_t \
imp::ToFactory<bool>::convert(v8::Local<v8::Value> val) { \
v8::Isolate *isolate = v8::Isolate::GetCurrent(); \
v8::HandleScope scope(isolate); \
return Just<bool>(val->BooleanValue(isolate)); \
}
#endif
#undef X
#endif // NAN_CONVERTERS_43_INL_H_

42
node_modules/nan/nan_converters_pre_43_inl.h generated vendored Normal file
View File

@ -0,0 +1,42 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_CONVERTERS_PRE_43_INL_H_
#define NAN_CONVERTERS_PRE_43_INL_H_
#define X(TYPE) \
imp::ToFactory<v8::TYPE>::return_t \
imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \
return val->To ## TYPE(); \
}
X(Boolean)
X(Number)
X(String)
X(Object)
X(Integer)
X(Uint32)
X(Int32)
#undef X
#define X(TYPE, NAME) \
imp::ToFactory<TYPE>::return_t \
imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \
return Just(val->NAME ## Value()); \
}
X(bool, Boolean)
X(double, Number)
X(int64_t, Integer)
X(uint32_t, Uint32)
X(int32_t, Int32)
#undef X
#endif // NAN_CONVERTERS_PRE_43_INL_H_

29
node_modules/nan/nan_define_own_property_helper.h generated vendored Normal file
View File

@ -0,0 +1,29 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_DEFINE_OWN_PROPERTY_HELPER_H_
#define NAN_DEFINE_OWN_PROPERTY_HELPER_H_
namespace imp {
inline Maybe<bool> DefineOwnPropertyHelper(
v8::PropertyAttribute current
, v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key
, v8::Handle<v8::Value> value
, v8::PropertyAttribute attribs = v8::None) {
return !(current & v8::DontDelete) || // configurable OR
(!(current & v8::ReadOnly) && // writable AND
!((attribs ^ current) & ~v8::ReadOnly)) // same excluding RO
? Just<bool>(obj->ForceSet(key, value, attribs))
: Nothing<bool>();
}
} // end of namespace imp
#endif // NAN_DEFINE_OWN_PROPERTY_HELPER_H_

430
node_modules/nan/nan_implementation_12_inl.h generated vendored Normal file
View File

@ -0,0 +1,430 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_IMPLEMENTATION_12_INL_H_
#define NAN_IMPLEMENTATION_12_INL_H_
//==============================================================================
// node v0.11 implementation
//==============================================================================
namespace imp {
//=== Array ====================================================================
Factory<v8::Array>::return_t
Factory<v8::Array>::New() {
return v8::Array::New(v8::Isolate::GetCurrent());
}
Factory<v8::Array>::return_t
Factory<v8::Array>::New(int length) {
return v8::Array::New(v8::Isolate::GetCurrent(), length);
}
//=== Boolean ==================================================================
Factory<v8::Boolean>::return_t
Factory<v8::Boolean>::New(bool value) {
return v8::Boolean::New(v8::Isolate::GetCurrent(), value);
}
//=== Boolean Object ===========================================================
Factory<v8::BooleanObject>::return_t
Factory<v8::BooleanObject>::New(bool value) {
#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
return v8::BooleanObject::New(
v8::Isolate::GetCurrent(), value).As<v8::BooleanObject>();
#else
return v8::BooleanObject::New(value).As<v8::BooleanObject>();
#endif
}
//=== Context ==================================================================
Factory<v8::Context>::return_t
Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
, v8::Local<v8::ObjectTemplate> tmpl
, v8::Local<v8::Value> obj) {
return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj);
}
//=== Date =====================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(v8::Date::New(isolate->GetCurrentContext(), value)
.FromMaybe(v8::Local<v8::Value>()).As<v8::Date>());
}
#else
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>();
}
#endif
//=== External =================================================================
Factory<v8::External>::return_t
Factory<v8::External>::New(void * value) {
return v8::External::New(v8::Isolate::GetCurrent(), value);
}
//=== Function =================================================================
Factory<v8::Function>::return_t
Factory<v8::Function>::New( FunctionCallback callback
, v8::Local<v8::Value> data) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(isolate, reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
#if NODE_MAJOR_VERSION >= 10
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Function> function =
v8::Function::New(context, imp::FunctionCallbackWrapper, obj)
.ToLocalChecked();
#else
v8::Local<v8::Function> function =
v8::Function::New(isolate, imp::FunctionCallbackWrapper, obj);
#endif
return scope.Escape(function);
}
//=== Function Template ========================================================
Factory<v8::FunctionTemplate>::return_t
Factory<v8::FunctionTemplate>::New( FunctionCallback callback
, v8::Local<v8::Value> data
, v8::Local<v8::Signature> signature) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
if (callback) {
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate);
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(isolate, reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
return scope.Escape(v8::FunctionTemplate::New( isolate
, imp::FunctionCallbackWrapper
, obj
, signature));
} else {
return v8::FunctionTemplate::New(isolate, 0, data, signature);
}
}
//=== Number ===================================================================
Factory<v8::Number>::return_t
Factory<v8::Number>::New(double value) {
return v8::Number::New(v8::Isolate::GetCurrent(), value);
}
//=== Number Object ============================================================
Factory<v8::NumberObject>::return_t
Factory<v8::NumberObject>::New(double value) {
return v8::NumberObject::New( v8::Isolate::GetCurrent()
, value).As<v8::NumberObject>();
}
//=== Integer, Int32 and Uint32 ================================================
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(int32_t value) {
return To<T>(T::New(v8::Isolate::GetCurrent(), value));
}
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(uint32_t value) {
return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(int32_t value) {
return To<v8::Uint32>(
v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(uint32_t value) {
return To<v8::Uint32>(
v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value));
}
//=== Object ===================================================================
Factory<v8::Object>::return_t
Factory<v8::Object>::New() {
return v8::Object::New(v8::Isolate::GetCurrent());
}
//=== Object Template ==========================================================
Factory<v8::ObjectTemplate>::return_t
Factory<v8::ObjectTemplate>::New() {
return v8::ObjectTemplate::New(v8::Isolate::GetCurrent());
}
//=== RegExp ===================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(
v8::RegExp::New(isolate->GetCurrentContext(), pattern, flags)
.FromMaybe(v8::Local<v8::RegExp>()));
}
#else
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
return v8::RegExp::New(pattern, flags);
}
#endif
//=== Script ===================================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
v8::ScriptCompiler::Source src(source);
return scope.Escape(
v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src)
.FromMaybe(v8::Local<v8::Script>()));
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
v8::ScriptCompiler::Source src(source, origin);
return scope.Escape(
v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src)
.FromMaybe(v8::Local<v8::Script>()));
}
#else
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src);
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src);
}
#endif
//=== Signature ================================================================
Factory<v8::Signature>::return_t
Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
return v8::Signature::New(v8::Isolate::GetCurrent(), receiver);
}
//=== String ===================================================================
Factory<v8::String>::return_t
Factory<v8::String>::New() {
return v8::String::Empty(v8::Isolate::GetCurrent());
}
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return v8::String::NewFromUtf8(
v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(std::string const& value) {
assert(value.size() <= INT_MAX && "string too long");
return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(),
value.data(), v8::NewStringType::kNormal, static_cast<int>(value.size()));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
v8::NewStringType::kNormal, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(ExternalOneByteStringResource * value) {
return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value);
}
#else
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value,
v8::String::kNormalString, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(
std::string const& value) /* NOLINT(build/include_what_you_use) */ {
assert(value.size() <= INT_MAX && "string too long");
return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value.data(),
v8::String::kNormalString,
static_cast<int>(value.size()));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value,
v8::String::kNormalString, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return v8::String::NewExternal(v8::Isolate::GetCurrent(), value);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(ExternalOneByteStringResource * value) {
return v8::String::NewExternal(v8::Isolate::GetCurrent(), value);
}
#endif
//=== String Object ============================================================
// See https://github.com/nodejs/nan/pull/811#discussion_r224594980.
// Disable the warning as there is no way around it.
// TODO(bnoordhuis) Use isolate-based version in Node.js v12.
Factory<v8::StringObject>::return_t
Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
// V8 > 7.0
#if V8_MAJOR_VERSION > 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION > 0)
return v8::StringObject::New(v8::Isolate::GetCurrent(), value)
.As<v8::StringObject>();
#else
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4996)
#endif
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
return v8::StringObject::New(value).As<v8::StringObject>();
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
}
//=== Unbound Script ===========================================================
#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \
(V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3))
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::CompileUnboundScript(
v8::Isolate::GetCurrent(), &src);
}
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::CompileUnboundScript(
v8::Isolate::GetCurrent(), &src);
}
#else
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) {
v8::ScriptCompiler::Source src(source);
return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src);
}
Factory<v8::UnboundScript>::return_t
Factory<v8::UnboundScript>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
v8::ScriptCompiler::Source src(source, origin);
return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src);
}
#endif
} // end of namespace imp
//=== Presistents and Handles ==================================================
#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION
template <typename T>
inline v8::Local<T> New(v8::Handle<T> h) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), h);
}
#endif
template <typename T, typename M>
inline v8::Local<T> New(v8::Persistent<T, M> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
template <typename T, typename M>
inline v8::Local<T> New(Persistent<T, M> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
template <typename T>
inline v8::Local<T> New(Global<T> const& p) {
return v8::Local<T>::New(v8::Isolate::GetCurrent(), p);
}
#endif // NAN_IMPLEMENTATION_12_INL_H_

263
node_modules/nan/nan_implementation_pre_12_inl.h generated vendored Normal file
View File

@ -0,0 +1,263 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_
#define NAN_IMPLEMENTATION_PRE_12_INL_H_
//==============================================================================
// node v0.10 implementation
//==============================================================================
namespace imp {
//=== Array ====================================================================
Factory<v8::Array>::return_t
Factory<v8::Array>::New() {
return v8::Array::New();
}
Factory<v8::Array>::return_t
Factory<v8::Array>::New(int length) {
return v8::Array::New(length);
}
//=== Boolean ==================================================================
Factory<v8::Boolean>::return_t
Factory<v8::Boolean>::New(bool value) {
return v8::Boolean::New(value)->ToBoolean();
}
//=== Boolean Object ===========================================================
Factory<v8::BooleanObject>::return_t
Factory<v8::BooleanObject>::New(bool value) {
return v8::BooleanObject::New(value).As<v8::BooleanObject>();
}
//=== Context ==================================================================
Factory<v8::Context>::return_t
Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions
, v8::Local<v8::ObjectTemplate> tmpl
, v8::Local<v8::Value> obj) {
v8::Persistent<v8::Context> ctx = v8::Context::New(extensions, tmpl, obj);
v8::Local<v8::Context> lctx = v8::Local<v8::Context>::New(ctx);
ctx.Dispose();
return lctx;
}
//=== Date =====================================================================
Factory<v8::Date>::return_t
Factory<v8::Date>::New(double value) {
return v8::Date::New(value).As<v8::Date>();
}
//=== External =================================================================
Factory<v8::External>::return_t
Factory<v8::External>::New(void * value) {
return v8::External::New(value);
}
//=== Function =================================================================
Factory<v8::Function>::return_t
Factory<v8::Function>::New( FunctionCallback callback
, v8::Local<v8::Value> data) {
v8::HandleScope scope;
return scope.Close(Factory<v8::FunctionTemplate>::New(
callback, data, v8::Local<v8::Signature>())
->GetFunction());
}
//=== FunctionTemplate =========================================================
Factory<v8::FunctionTemplate>::return_t
Factory<v8::FunctionTemplate>::New( FunctionCallback callback
, v8::Local<v8::Value> data
, v8::Local<v8::Signature> signature) {
if (callback) {
v8::HandleScope scope;
v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New();
tpl->SetInternalFieldCount(imp::kFunctionFieldCount);
v8::Local<v8::Object> obj = tpl->NewInstance();
obj->SetInternalField(
imp::kFunctionIndex
, v8::External::New(reinterpret_cast<void *>(callback)));
v8::Local<v8::Value> val = v8::Local<v8::Value>::New(data);
if (!val.IsEmpty()) {
obj->SetInternalField(imp::kDataIndex, val);
}
// Note(agnat): Emulate length argument here. Unfortunately, I couldn't find
// a way. Have at it though...
return scope.Close(
v8::FunctionTemplate::New(imp::FunctionCallbackWrapper
, obj
, signature));
} else {
return v8::FunctionTemplate::New(0, data, signature);
}
}
//=== Number ===================================================================
Factory<v8::Number>::return_t
Factory<v8::Number>::New(double value) {
return v8::Number::New(value);
}
//=== Number Object ============================================================
Factory<v8::NumberObject>::return_t
Factory<v8::NumberObject>::New(double value) {
return v8::NumberObject::New(value).As<v8::NumberObject>();
}
//=== Integer, Int32 and Uint32 ================================================
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(int32_t value) {
return To<T>(T::New(value));
}
template <typename T>
typename IntegerFactory<T>::return_t
IntegerFactory<T>::New(uint32_t value) {
return To<T>(T::NewFromUnsigned(value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(int32_t value) {
return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
}
Factory<v8::Uint32>::return_t
Factory<v8::Uint32>::New(uint32_t value) {
return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value));
}
//=== Object ===================================================================
Factory<v8::Object>::return_t
Factory<v8::Object>::New() {
return v8::Object::New();
}
//=== Object Template ==========================================================
Factory<v8::ObjectTemplate>::return_t
Factory<v8::ObjectTemplate>::New() {
return v8::ObjectTemplate::New();
}
//=== RegExp ===================================================================
Factory<v8::RegExp>::return_t
Factory<v8::RegExp>::New(
v8::Local<v8::String> pattern
, v8::RegExp::Flags flags) {
return v8::RegExp::New(pattern, flags);
}
//=== Script ===================================================================
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source) {
return v8::Script::New(source);
}
Factory<v8::Script>::return_t
Factory<v8::Script>::New( v8::Local<v8::String> source
, v8::ScriptOrigin const& origin) {
return v8::Script::New(source, const_cast<v8::ScriptOrigin*>(&origin));
}
//=== Signature ================================================================
Factory<v8::Signature>::return_t
Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) {
return v8::Signature::New(receiver);
}
//=== String ===================================================================
Factory<v8::String>::return_t
Factory<v8::String>::New() {
return v8::String::Empty();
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const char * value, int length) {
return v8::String::New(value, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(
std::string const& value) /* NOLINT(build/include_what_you_use) */ {
assert(value.size() <= INT_MAX && "string too long");
return v8::String::New(value.data(), static_cast<int>(value.size()));
}
Factory<v8::String>::return_t
Factory<v8::String>::New(const uint16_t * value, int length) {
return v8::String::New(value, length);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalStringResource * value) {
return v8::String::NewExternal(value);
}
Factory<v8::String>::return_t
Factory<v8::String>::New(v8::String::ExternalAsciiStringResource * value) {
return v8::String::NewExternal(value);
}
//=== String Object ============================================================
Factory<v8::StringObject>::return_t
Factory<v8::StringObject>::New(v8::Local<v8::String> value) {
return v8::StringObject::New(value).As<v8::StringObject>();
}
} // end of namespace imp
//=== Presistents and Handles ==================================================
template <typename T>
inline v8::Local<T> New(v8::Handle<T> h) {
return v8::Local<T>::New(h);
}
template <typename T>
inline v8::Local<T> New(v8::Persistent<T> const& p) {
return v8::Local<T>::New(p);
}
template <typename T, typename M>
inline v8::Local<T> New(Persistent<T, M> const& p) {
return v8::Local<T>::New(p.persistent);
}
template <typename T>
inline v8::Local<T> New(Global<T> const& p) {
return v8::Local<T>::New(p.persistent);
}
#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_

166
node_modules/nan/nan_json.h generated vendored Normal file
View File

@ -0,0 +1,166 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_JSON_H_
#define NAN_JSON_H_
#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION
#define NAN_JSON_H_NEED_PARSE 1
#else
#define NAN_JSON_H_NEED_PARSE 0
#endif // NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION
#if NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION
#define NAN_JSON_H_NEED_STRINGIFY 0
#else
#define NAN_JSON_H_NEED_STRINGIFY 1
#endif // NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION
class JSON {
public:
JSON() {
#if NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY
Nan::HandleScope scope;
Nan::MaybeLocal<v8::Value> maybe_global_json = Nan::Get(
Nan::GetCurrentContext()->Global(),
Nan::New("JSON").ToLocalChecked()
);
assert(!maybe_global_json.IsEmpty() && "global JSON is empty");
v8::Local<v8::Value> val_global_json = maybe_global_json.ToLocalChecked();
assert(val_global_json->IsObject() && "global JSON is not an object");
Nan::MaybeLocal<v8::Object> maybe_obj_global_json =
Nan::To<v8::Object>(val_global_json);
assert(!maybe_obj_global_json.IsEmpty() && "global JSON object is empty");
v8::Local<v8::Object> global_json = maybe_obj_global_json.ToLocalChecked();
#if NAN_JSON_H_NEED_PARSE
Nan::MaybeLocal<v8::Value> maybe_parse_method = Nan::Get(
global_json, Nan::New("parse").ToLocalChecked()
);
assert(!maybe_parse_method.IsEmpty() && "JSON.parse is empty");
v8::Local<v8::Value> parse_method = maybe_parse_method.ToLocalChecked();
assert(parse_method->IsFunction() && "JSON.parse is not a function");
parse_cb_.Reset(parse_method.As<v8::Function>());
#endif // NAN_JSON_H_NEED_PARSE
#if NAN_JSON_H_NEED_STRINGIFY
Nan::MaybeLocal<v8::Value> maybe_stringify_method = Nan::Get(
global_json, Nan::New("stringify").ToLocalChecked()
);
assert(!maybe_stringify_method.IsEmpty() && "JSON.stringify is empty");
v8::Local<v8::Value> stringify_method =
maybe_stringify_method.ToLocalChecked();
assert(
stringify_method->IsFunction() && "JSON.stringify is not a function"
);
stringify_cb_.Reset(stringify_method.As<v8::Function>());
#endif // NAN_JSON_H_NEED_STRINGIFY
#endif // NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY
}
inline
Nan::MaybeLocal<v8::Value> Parse(v8::Local<v8::String> json_string) {
Nan::EscapableHandleScope scope;
#if NAN_JSON_H_NEED_PARSE
return scope.Escape(parse(json_string));
#else
Nan::MaybeLocal<v8::Value> result;
#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && \
NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION
result = v8::JSON::Parse(json_string);
#else
#if NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION
v8::Local<v8::Context> context_or_isolate = Nan::GetCurrentContext();
#else
v8::Isolate* context_or_isolate = v8::Isolate::GetCurrent();
#endif // NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION
result = v8::JSON::Parse(context_or_isolate, json_string);
#endif // NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION &&
// NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION
if (result.IsEmpty()) return v8::Local<v8::Value>();
return scope.Escape(result.ToLocalChecked());
#endif // NAN_JSON_H_NEED_PARSE
}
inline
Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object) {
Nan::EscapableHandleScope scope;
Nan::MaybeLocal<v8::String> result =
#if NAN_JSON_H_NEED_STRINGIFY
Nan::To<v8::String>(stringify(json_object));
#else
v8::JSON::Stringify(Nan::GetCurrentContext(), json_object);
#endif // NAN_JSON_H_NEED_STRINGIFY
if (result.IsEmpty()) return v8::Local<v8::String>();
return scope.Escape(result.ToLocalChecked());
}
inline
Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object,
v8::Local<v8::String> gap) {
Nan::EscapableHandleScope scope;
Nan::MaybeLocal<v8::String> result =
#if NAN_JSON_H_NEED_STRINGIFY
Nan::To<v8::String>(stringify(json_object, gap));
#else
v8::JSON::Stringify(Nan::GetCurrentContext(), json_object, gap);
#endif // NAN_JSON_H_NEED_STRINGIFY
if (result.IsEmpty()) return v8::Local<v8::String>();
return scope.Escape(result.ToLocalChecked());
}
private:
NAN_DISALLOW_ASSIGN_COPY_MOVE(JSON)
#if NAN_JSON_H_NEED_PARSE
Nan::Callback parse_cb_;
#endif // NAN_JSON_H_NEED_PARSE
#if NAN_JSON_H_NEED_STRINGIFY
Nan::Callback stringify_cb_;
#endif // NAN_JSON_H_NEED_STRINGIFY
#if NAN_JSON_H_NEED_PARSE
inline v8::Local<v8::Value> parse(v8::Local<v8::Value> arg) {
assert(!parse_cb_.IsEmpty() && "parse_cb_ is empty");
AsyncResource resource("nan:JSON.parse");
return parse_cb_.Call(1, &arg, &resource).FromMaybe(v8::Local<v8::Value>());
}
#endif // NAN_JSON_H_NEED_PARSE
#if NAN_JSON_H_NEED_STRINGIFY
inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg) {
assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty");
AsyncResource resource("nan:JSON.stringify");
return stringify_cb_.Call(1, &arg, &resource)
.FromMaybe(v8::Local<v8::Value>());
}
inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg,
v8::Local<v8::String> gap) {
assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty");
v8::Local<v8::Value> argv[] = {
arg,
Nan::Null(),
gap
};
AsyncResource resource("nan:JSON.stringify");
return stringify_cb_.Call(3, argv, &resource)
.FromMaybe(v8::Local<v8::Value>());
}
#endif // NAN_JSON_H_NEED_STRINGIFY
};
#endif // NAN_JSON_H_

356
node_modules/nan/nan_maybe_43_inl.h generated vendored Normal file
View File

@ -0,0 +1,356 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_MAYBE_43_INL_H_
#define NAN_MAYBE_43_INL_H_
template<typename T>
using MaybeLocal = v8::MaybeLocal<T>;
inline
MaybeLocal<v8::String> ToDetailString(v8::Local<v8::Value> val) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(val->ToDetailString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
}
inline
MaybeLocal<v8::Uint32> ToArrayIndex(v8::Local<v8::Value> val) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(val->ToArrayIndex(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::Uint32>()));
}
inline
Maybe<bool> Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return a->Equals(isolate->GetCurrentContext(), b);
}
inline
MaybeLocal<v8::Object> NewInstance(v8::Local<v8::Function> h) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(h->NewInstance(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::Object>()));
}
inline
MaybeLocal<v8::Object> NewInstance(
v8::Local<v8::Function> h
, int argc
, v8::Local<v8::Value> argv[]) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(h->NewInstance(isolate->GetCurrentContext(), argc, argv)
.FromMaybe(v8::Local<v8::Object>()));
}
inline
MaybeLocal<v8::Object> NewInstance(v8::Local<v8::ObjectTemplate> h) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(h->NewInstance(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::Object>()));
}
inline MaybeLocal<v8::Function> GetFunction(
v8::Local<v8::FunctionTemplate> t) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(t->GetFunction(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::Function>()));
}
inline Maybe<bool> Set(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key
, v8::Local<v8::Value> value) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->Set(isolate->GetCurrentContext(), key, value);
}
inline Maybe<bool> Set(
v8::Local<v8::Object> obj
, uint32_t index
, v8::Local<v8::Value> value) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->Set(isolate->GetCurrentContext(), index, value);
}
#if NODE_MODULE_VERSION < NODE_4_0_MODULE_VERSION
#include "nan_define_own_property_helper.h" // NOLINT(build/include)
#endif
inline Maybe<bool> DefineOwnProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key
, v8::Local<v8::Value> value
, v8::PropertyAttribute attribs = v8::None) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
#if NODE_MODULE_VERSION >= NODE_4_0_MODULE_VERSION
return obj->DefineOwnProperty(isolate->GetCurrentContext(), key, value,
attribs);
#else
Maybe<v8::PropertyAttribute> maybeCurrent =
obj->GetPropertyAttributes(isolate->GetCurrentContext(), key);
if (maybeCurrent.IsNothing()) {
return Nothing<bool>();
}
v8::PropertyAttribute current = maybeCurrent.FromJust();
return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs);
#endif
}
NAN_DEPRECATED inline Maybe<bool> ForceSet(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key
, v8::Local<v8::Value> value
, v8::PropertyAttribute attribs = v8::None) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION
return key->IsName()
? obj->DefineOwnProperty(isolate->GetCurrentContext(),
key.As<v8::Name>(), value, attribs)
: Nothing<bool>();
#else
return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs);
#endif
}
inline MaybeLocal<v8::Value> Get(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(obj->Get(isolate->GetCurrentContext(), key)
.FromMaybe(v8::Local<v8::Value>()));
}
inline
MaybeLocal<v8::Value> Get(v8::Local<v8::Object> obj, uint32_t index) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(obj->Get(isolate->GetCurrentContext(), index)
.FromMaybe(v8::Local<v8::Value>()));
}
inline v8::PropertyAttribute GetPropertyAttributes(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->GetPropertyAttributes(isolate->GetCurrentContext(), key)
.FromJust();
}
inline Maybe<bool> Has(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->Has(isolate->GetCurrentContext(), key);
}
inline Maybe<bool> Has(v8::Local<v8::Object> obj, uint32_t index) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->Has(isolate->GetCurrentContext(), index);
}
inline Maybe<bool> Delete(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->Delete(isolate->GetCurrentContext(), key);
}
inline
Maybe<bool> Delete(v8::Local<v8::Object> obj, uint32_t index) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->Delete(isolate->GetCurrentContext(), index);
}
inline
MaybeLocal<v8::Array> GetPropertyNames(v8::Local<v8::Object> obj) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(obj->GetPropertyNames(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::Array>()));
}
inline
MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Local<v8::Object> obj) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(obj->GetOwnPropertyNames(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::Array>()));
}
inline Maybe<bool> SetPrototype(
v8::Local<v8::Object> obj
, v8::Local<v8::Value> prototype) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->SetPrototype(isolate->GetCurrentContext(), prototype);
}
inline MaybeLocal<v8::String> ObjectProtoToString(
v8::Local<v8::Object> obj) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(obj->ObjectProtoToString(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
}
inline Maybe<bool> HasOwnProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->HasOwnProperty(isolate->GetCurrentContext(), key);
}
inline Maybe<bool> HasRealNamedProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->HasRealNamedProperty(isolate->GetCurrentContext(), key);
}
inline Maybe<bool> HasRealIndexedProperty(
v8::Local<v8::Object> obj
, uint32_t index) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->HasRealIndexedProperty(isolate->GetCurrentContext(), index);
}
inline Maybe<bool> HasRealNamedCallbackProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return obj->HasRealNamedCallbackProperty(isolate->GetCurrentContext(), key);
}
inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(obj->GetRealNamedPropertyInPrototypeChain(
isolate->GetCurrentContext(), key)
.FromMaybe(v8::Local<v8::Value>()));
}
inline MaybeLocal<v8::Value> GetRealNamedProperty(
v8::Local<v8::Object> obj
, v8::Local<v8::String> key) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(
obj->GetRealNamedProperty(isolate->GetCurrentContext(), key)
.FromMaybe(v8::Local<v8::Value>()));
}
inline MaybeLocal<v8::Value> CallAsFunction(
v8::Local<v8::Object> obj
, v8::Local<v8::Object> recv
, int argc
, v8::Local<v8::Value> argv[]) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(
obj->CallAsFunction(isolate->GetCurrentContext(), recv, argc, argv)
.FromMaybe(v8::Local<v8::Value>()));
}
inline MaybeLocal<v8::Value> CallAsConstructor(
v8::Local<v8::Object> obj
, int argc, v8::Local<v8::Value> argv[]) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(
obj->CallAsConstructor(isolate->GetCurrentContext(), argc, argv)
.FromMaybe(v8::Local<v8::Value>()));
}
inline
MaybeLocal<v8::String> GetSourceLine(v8::Local<v8::Message> msg) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(msg->GetSourceLine(isolate->GetCurrentContext())
.FromMaybe(v8::Local<v8::String>()));
}
inline Maybe<int> GetLineNumber(v8::Local<v8::Message> msg) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return msg->GetLineNumber(isolate->GetCurrentContext());
}
inline Maybe<int> GetStartColumn(v8::Local<v8::Message> msg) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return msg->GetStartColumn(isolate->GetCurrentContext());
}
inline Maybe<int> GetEndColumn(v8::Local<v8::Message> msg) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::HandleScope scope(isolate);
return msg->GetEndColumn(isolate->GetCurrentContext());
}
inline MaybeLocal<v8::Object> CloneElementAt(
v8::Local<v8::Array> array
, uint32_t index) {
#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION)
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Value> elem;
v8::Local<v8::Object> obj;
if (!array->Get(context, index).ToLocal(&elem)) {
return scope.Escape(obj);
}
if (!elem->ToObject(context).ToLocal(&obj)) {
return scope.Escape(v8::Local<v8::Object>());
}
return scope.Escape(obj->Clone());
#else
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(array->CloneElementAt(isolate->GetCurrentContext(), index)
.FromMaybe(v8::Local<v8::Object>()));
#endif
}
inline MaybeLocal<v8::Value> Call(
v8::Local<v8::Function> fun
, v8::Local<v8::Object> recv
, int argc
, v8::Local<v8::Value> argv[]) {
v8::Isolate *isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
return scope.Escape(fun->Call(isolate->GetCurrentContext(), recv, argc, argv)
.FromMaybe(v8::Local<v8::Value>()));
}
#endif // NAN_MAYBE_43_INL_H_

268
node_modules/nan/nan_maybe_pre_43_inl.h generated vendored Normal file
View File

@ -0,0 +1,268 @@
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
#ifndef NAN_MAYBE_PRE_43_INL_H_
#define NAN_MAYBE_PRE_43_INL_H_
template<typename T>
class MaybeLocal {
public:
inline MaybeLocal() : val_(v8::Local<T>()) {}
template<typename S>
# if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION
inline
MaybeLocal(v8::Local<S> that) : val_(that) {} // NOLINT(runtime/explicit)
# else
inline
MaybeLocal(v8::Local<S> that) : // NOLINT(runtime/explicit)
val_(*reinterpret_cast<v8::Local<T>*>(&that)) {}
# endif
inline bool IsEmpty() const { return val_.IsEmpty(); }
template<typename S>
inline bool ToLocal(v8::Local<S> *out) const {
*out = val_;
return !IsEmpty();
}
inline v8::Local<T> ToLocalChecked() const {
#if defined(V8_ENABLE_CHECKS)
assert(!IsEmpty() && "ToLocalChecked is Empty");
#endif // V8_ENABLE_CHECKS
return val_;
}
template<typename S>
inline v8::Local<S> FromMaybe(v8::Local<S> default_value) const {
return IsEmpty() ? default_value : v8::Local<S>(val_);
}
private:
v8::Local<T> val_;
};
inline
MaybeLocal<v8::String> ToDetailString(v8::Handle<v8::Value> val) {
return MaybeLocal<v8::String>(val->ToDetailString());
}
inline
MaybeLocal<v8::Uint32> ToArrayIndex(v8::Handle<v8::Value> val) {
return MaybeLocal<v8::Uint32>(val->ToArrayIndex());
}
inline
Maybe<bool> Equals(v8::Handle<v8::Value> a, v8::Handle<v8::Value>(b)) {
return Just<bool>(a->Equals(b));
}
inline
MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::Function> h) {
return MaybeLocal<v8::Object>(h->NewInstance());
}
inline
MaybeLocal<v8::Object> NewInstance(
v8::Local<v8::Function> h
, int argc
, v8::Local<v8::Value> argv[]) {
return MaybeLocal<v8::Object>(h->NewInstance(argc, argv));
}
inline
MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::ObjectTemplate> h) {
return MaybeLocal<v8::Object>(h->NewInstance());
}
inline
MaybeLocal<v8::Function> GetFunction(v8::Handle<v8::FunctionTemplate> t) {
return MaybeLocal<v8::Function>(t->GetFunction());
}
inline Maybe<bool> Set(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> key
, v8::Handle<v8::Value> value) {
return Just<bool>(obj->Set(key, value));
}
inline Maybe<bool> Set(
v8::Handle<v8::Object> obj
, uint32_t index
, v8::Handle<v8::Value> value) {
return Just<bool>(obj->Set(index, value));
}
#include "nan_define_own_property_helper.h" // NOLINT(build/include)
inline Maybe<bool> DefineOwnProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key
, v8::Handle<v8::Value> value
, v8::PropertyAttribute attribs = v8::None) {
v8::PropertyAttribute current = obj->GetPropertyAttributes(key);
return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs);
}
NAN_DEPRECATED inline Maybe<bool> ForceSet(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> key
, v8::Handle<v8::Value> value
, v8::PropertyAttribute attribs = v8::None) {
return Just<bool>(obj->ForceSet(key, value, attribs));
}
inline MaybeLocal<v8::Value> Get(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> key) {
return MaybeLocal<v8::Value>(obj->Get(key));
}
inline MaybeLocal<v8::Value> Get(
v8::Handle<v8::Object> obj
, uint32_t index) {
return MaybeLocal<v8::Value>(obj->Get(index));
}
inline Maybe<v8::PropertyAttribute> GetPropertyAttributes(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> key) {
return Just<v8::PropertyAttribute>(obj->GetPropertyAttributes(key));
}
inline Maybe<bool> Has(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->Has(key));
}
inline Maybe<bool> Has(
v8::Handle<v8::Object> obj
, uint32_t index) {
return Just<bool>(obj->Has(index));
}
inline Maybe<bool> Delete(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->Delete(key));
}
inline Maybe<bool> Delete(
v8::Handle<v8::Object> obj
, uint32_t index) {
return Just<bool>(obj->Delete(index));
}
inline
MaybeLocal<v8::Array> GetPropertyNames(v8::Handle<v8::Object> obj) {
return MaybeLocal<v8::Array>(obj->GetPropertyNames());
}
inline
MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Handle<v8::Object> obj) {
return MaybeLocal<v8::Array>(obj->GetOwnPropertyNames());
}
inline Maybe<bool> SetPrototype(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Value> prototype) {
return Just<bool>(obj->SetPrototype(prototype));
}
inline MaybeLocal<v8::String> ObjectProtoToString(
v8::Handle<v8::Object> obj) {
return MaybeLocal<v8::String>(obj->ObjectProtoToString());
}
inline Maybe<bool> HasOwnProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->HasOwnProperty(key));
}
inline Maybe<bool> HasRealNamedProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->HasRealNamedProperty(key));
}
inline Maybe<bool> HasRealIndexedProperty(
v8::Handle<v8::Object> obj
, uint32_t index) {
return Just<bool>(obj->HasRealIndexedProperty(index));
}
inline Maybe<bool> HasRealNamedCallbackProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return Just<bool>(obj->HasRealNamedCallbackProperty(key));
}
inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return MaybeLocal<v8::Value>(
obj->GetRealNamedPropertyInPrototypeChain(key));
}
inline MaybeLocal<v8::Value> GetRealNamedProperty(
v8::Handle<v8::Object> obj
, v8::Handle<v8::String> key) {
return MaybeLocal<v8::Value>(obj->GetRealNamedProperty(key));
}
inline MaybeLocal<v8::Value> CallAsFunction(
v8::Handle<v8::Object> obj
, v8::Handle<v8::Object> recv
, int argc
, v8::Handle<v8::Value> argv[]) {
return MaybeLocal<v8::Value>(obj->CallAsFunction(recv, argc, argv));
}
inline MaybeLocal<v8::Value> CallAsConstructor(
v8::Handle<v8::Object> obj
, int argc
, v8::Local<v8::Value> argv[]) {
return MaybeLocal<v8::Value>(obj->CallAsConstructor(argc, argv));
}
inline
MaybeLocal<v8::String> GetSourceLine(v8::Handle<v8::Message> msg) {
return MaybeLocal<v8::String>(msg->GetSourceLine());
}
inline Maybe<int> GetLineNumber(v8::Handle<v8::Message> msg) {
return Just<int>(msg->GetLineNumber());
}
inline Maybe<int> GetStartColumn(v8::Handle<v8::Message> msg) {
return Just<int>(msg->GetStartColumn());
}
inline Maybe<int> GetEndColumn(v8::Handle<v8::Message> msg) {
return Just<int>(msg->GetEndColumn());
}
inline MaybeLocal<v8::Object> CloneElementAt(
v8::Handle<v8::Array> array
, uint32_t index) {
return MaybeLocal<v8::Object>(array->CloneElementAt(index));
}
inline MaybeLocal<v8::Value> Call(
v8::Local<v8::Function> fun
, v8::Local<v8::Object> recv
, int argc
, v8::Local<v8::Value> argv[]) {
return MaybeLocal<v8::Value>(fun->Call(recv, argc, argv));
}
#endif // NAN_MAYBE_PRE_43_INL_H_

Some files were not shown because too many files have changed in this diff Show More