I_Jemin

Validate Input

Showing 49 changed files with 10068 additions and 11 deletions
const Joi = require('joi');
const express = require('express');
const app = express();
app.use(express.json());
const courses = [
{ id: 1, name: 'course1'},
{ id: 2, name: 'course2'},
{ id: 3, name: 'course3'},
{ id: 1, name: 'course1' },
{ id: 2, name: 'course2' },
{ id: 3, name: 'course3' },
];
// Corespond to HTTP
......@@ -15,21 +16,34 @@ const courses = [
// app.put();
// app.delete()
app.get('/',(req,res)=> {
app.get('/', (req, res) => {
res.send('Hello World!!!');
});
app.get('/api/courses',(req,res) => {
app.get('/api/courses', (req, res) => {
res.send(courses);
});
app.get('/api/courses/:id',(req,res) => {
const course = courses.find(c=> c.id === parseInt(req.params.id));
if(!course) res.status(404).send('The course with the given ID was not found');
app.get('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id));
if (!course) res.status(404).send('The course with the given ID was not found');
res.send(course);
});
app.post('/api/courses',(req,res)=> {
app.post('/api/courses', (req, res) => {
// Define Schema
const schema = {
name: Joi.string().min(3).required()
};
const result = Joi.validate(req.body, schema);
if (result.error) {
// 400 Bad Request
res.status(400).send(result.error.details[0].message);
return;
}
const course = {
id: courses.length + 1,
name: req.body.name
......@@ -42,4 +56,4 @@ app.post('/api/courses',(req,res)=> {
// PORT
const port = process.env.PORT || 3000;
app.listen(port,()=> console.log(`Listening on port ${port}...`));
app.listen(port, () => console.log(`Listening on port ${port}...`));
......
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.
![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)
'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;
}());
'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) {
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(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) {
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;
};
exports.wait = function (timeout) {
return new Promise((resolve) => setTimeout(resolve, timeout));
};
exports.block = function () {
return new Promise(exports.ignore);
};
{
"_from": "hoek@5.x.x",
"_id": "hoek@5.0.3",
"_inBundle": false,
"_integrity": "sha512-Bmr56pxML1c9kU+NS51SMFkiVQAb+9uFfXwyqR2tn4w2FPvmPt65eZ9aCcEfRXd9G74HkZnILC6p967pED4aiw==",
"_location": "/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",
"/topo"
],
"_resolved": "https://registry.npmjs.org/hoek/-/hoek-5.0.3.tgz",
"_shasum": "b71d40d943d0a95da01956b547f83c4a5b4a34ac",
"_spec": "hoek@5.x.x",
"_where": "/Users/jeminlee/git-projects/node-practice/express-demo/node_modules/joi",
"bugs": {
"url": "https://github.com/hapijs/hoek/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"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.3"
}
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
# 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.org', {errorLevel: true});
0
> Isemail.validate('test@e.com', {errorLevel: true});
6
> Isemail.validate('test@e.com', {errorLevel: 7});
0
> Isemail.validate('test@e.com', {errorLevel: 6});
6
```
<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"
// 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.
*
* The callback function will always be called
* with the result of the operation.
*
* ```
* import * as IsEmail from "isemail";
*
* const log = result => console.log(`Result: ${result}`);
* IsEmail.validate("test@e.com");
* // => true
* ```
*/
validate(email: string): boolean;
/**
* Check that an email address conforms to RFCs 5321, 5322, 6530 and others.
*
* The callback function will always be called
* with the result of the operation.
*
* ```
* 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.
*
* The callback function will always be called
* with the result of the operation.
*
* ```
* 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;
'use strict';
// Load modules
const Punycode = require('punycode');
// Declare internals
const internals = {
hasOwn: Object.prototype.hasOwnProperty,
indexOf: Array.prototype.indexOf,
defaultThreshold: 16,
maxIPv6Groups: 8,
categories: {
valid: 1,
dnsWarn: 7,
rfc5321: 15,
cfws: 31,
deprecated: 63,
rfc5322: 127,
error: 255
},
diagnoses: {
// Address is valid
valid: 0,
// Address is valid for SMTP but has unusual elements
rfc5321TLD: 9,
rfc5321TLDNumeric: 10,
rfc5321QuotedString: 11,
rfc5321AddressLiteral: 12,
// Address is valid for message, but must be modified for envelope
cfwsComment: 17,
cfwsFWS: 18,
// Address contains non-ASCII when the allowUnicode option is false
// Has to be > internals.defaultThreshold so that it's rejected
// without an explicit errorLevel:
undesiredNonAscii: 25,
// Address contains deprecated elements, but may still be valid in some contexts
deprecatedLocalPart: 33,
deprecatedFWS: 34,
deprecatedQTEXT: 35,
deprecatedQP: 36,
deprecatedComment: 37,
deprecatedCTEXT: 38,
deprecatedIPv6: 39,
deprecatedCFWSNearAt: 49,
// Address is only valid according to broad definition in RFC 5322, but is otherwise invalid
rfc5322Domain: 65,
rfc5322TooLong: 66,
rfc5322LocalTooLong: 67,
rfc5322DomainTooLong: 68,
rfc5322LabelTooLong: 69,
rfc5322DomainLiteral: 70,
rfc5322DomainLiteralOBSDText: 71,
rfc5322IPv6GroupCount: 72,
rfc5322IPv62x2xColon: 73,
rfc5322IPv6BadCharacter: 74,
rfc5322IPv6MaxGroups: 75,
rfc5322IPv6ColonStart: 76,
rfc5322IPv6ColonEnd: 77,
// Address is invalid for any purpose
errExpectingDTEXT: 129,
errNoLocalPart: 130,
errNoDomain: 131,
errConsecutiveDots: 132,
errATEXTAfterCFWS: 133,
errATEXTAfterQS: 134,
errATEXTAfterDomainLiteral: 135,
errExpectingQPair: 136,
errExpectingATEXT: 137,
errExpectingQTEXT: 138,
errExpectingCTEXT: 139,
errBackslashEnd: 140,
errDotStart: 141,
errDotEnd: 142,
errDomainHyphenStart: 143,
errDomainHyphenEnd: 144,
errUnclosedQuotedString: 145,
errUnclosedComment: 146,
errUnclosedDomainLiteral: 147,
errFWSCRLFx2: 148,
errFWSCRLFEnd: 149,
errCRNoLF: 150,
errUnknownTLD: 160,
errDomainTooShort: 161
},
components: {
localpart: 0,
domain: 1,
literal: 2,
contextComment: 3,
contextFWS: 4,
contextQuotedString: 5,
contextQuotedPair: 6
}
};
internals.specials = function () {
const specials = '()<>[]:;@\\,."'; // US-ASCII visible characters not valid for atext (http://tools.ietf.org/html/rfc5322#section-3.2.3)
const lookup = new Array(0x100);
lookup.fill(false);
for (let i = 0; i < specials.length; ++i) {
lookup[specials.codePointAt(i)] = true;
}
return function (code) {
return lookup[code];
};
}();
internals.c0Controls = function () {
const lookup = new Array(0x100);
lookup.fill(false);
// add C0 control characters
for (let i = 0; i < 33; ++i) {
lookup[i] = true;
}
return function (code) {
return lookup[code];
};
}();
internals.c1Controls = function () {
const lookup = new Array(0x100);
lookup.fill(false);
// add C1 control characters
for (let i = 127; i < 160; ++i) {
lookup[i] = true;
}
return function (code) {
return lookup[code];
};
}();
internals.regex = {
ipV4: /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
ipV6: /^[a-fA-F\d]{0,4}$/
};
// $lab:coverage:off$
internals.nulNormalize = function (email) {
let emailPieces = email.split('\u0000');
emailPieces = emailPieces.map((string) => {
return string.normalize('NFC');
});
return emailPieces.join('\u0000');
};
// $lab:coverage:on$
internals.checkIpV6 = function (items) {
return items.every((value) => internals.regex.ipV6.test(value));
};
internals.validDomain = function (tldAtom, options) {
if (options.tldBlacklist) {
if (Array.isArray(options.tldBlacklist)) {
return internals.indexOf.call(options.tldBlacklist, tldAtom) === -1;
}
return !internals.hasOwn.call(options.tldBlacklist, tldAtom);
}
if (Array.isArray(options.tldWhitelist)) {
return internals.indexOf.call(options.tldWhitelist, tldAtom) !== -1;
}
return internals.hasOwn.call(options.tldWhitelist, tldAtom);
};
/**
* Check that an email address conforms to RFCs 5321, 5322, 6530 and others
*
* We distinguish clearly between a Mailbox as defined by RFC 5321 and an
* addr-spec as defined by RFC 5322. Depending on the context, either can be
* regarded as a valid email address. The RFC 5321 Mailbox specification is
* more restrictive (comments, white space and obsolete forms are not allowed).
*
* @param {string} email The email address to check. See README for specifics.
* @param {Object} options The (optional) options:
* {*} errorLevel Determines the boundary between valid and invalid
* addresses.
* {*} tldBlacklist The set of domains to consider invalid.
* {*} tldWhitelist The set of domains to consider valid.
* {*} allowUnicode Whether to allow non-ASCII characters, defaults to true.
* {*} minDomainAtoms The minimum number of domain atoms which must be present
* for the address to be valid.
* @param {function(number|boolean)} callback The (optional) callback handler.
* @return {*}
*/
exports.validate = internals.validate = function (email, options, callback) {
options = options || {};
email = internals.normalize(email);
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof callback !== 'function') {
callback = null;
}
let diagnose;
let threshold;
if (typeof options.errorLevel === 'number') {
diagnose = true;
threshold = options.errorLevel;
}
else {
diagnose = !!options.errorLevel;
threshold = internals.diagnoses.valid;
}
if (options.tldWhitelist) {
if (typeof options.tldWhitelist === 'string') {
options.tldWhitelist = [options.tldWhitelist];
}
else if (typeof options.tldWhitelist !== 'object') {
throw new TypeError('expected array or object tldWhitelist');
}
}
if (options.tldBlacklist) {
if (typeof options.tldBlacklist === 'string') {
options.tldBlacklist = [options.tldBlacklist];
}
else if (typeof options.tldBlacklist !== 'object') {
throw new TypeError('expected array or object tldBlacklist');
}
}
if (options.minDomainAtoms && (options.minDomainAtoms !== ((+options.minDomainAtoms) | 0) || options.minDomainAtoms < 0)) {
throw new TypeError('expected positive integer minDomainAtoms');
}
let maxResult = internals.diagnoses.valid;
const updateResult = (value) => {
if (value > maxResult) {
maxResult = value;
}
};
const allowUnicode = options.allowUnicode === undefined || !!options.allowUnicode;
if (!allowUnicode && /[^\x00-\x7f]/.test(email)) {
updateResult(internals.diagnoses.undesiredNonAscii);
}
const context = {
now: internals.components.localpart,
prev: internals.components.localpart,
stack: [internals.components.localpart]
};
let prevToken = '';
const parseData = {
local: '',
domain: ''
};
const atomData = {
locals: [''],
domains: ['']
};
let elementCount = 0;
let elementLength = 0;
let crlfCount = 0;
let charCode;
let hyphenFlag = false;
let assertEnd = false;
const emailLength = email.length;
let token; // Token is used outside the loop, must declare similarly
for (let i = 0; i < emailLength; i += token.length) {
// Utilize codepoints to account for Unicode surrogate pairs
token = String.fromCodePoint(email.codePointAt(i));
switch (context.now) {
// Local-part
case internals.components.localpart:
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// local-part = dot-atom / quoted-string / obs-local-part
//
// dot-atom = [CFWS] dot-atom-text [CFWS]
//
// dot-atom-text = 1*atext *("." 1*atext)
//
// quoted-string = [CFWS]
// DQUOTE *([FWS] qcontent) [FWS] DQUOTE
// [CFWS]
//
// obs-local-part = word *("." word)
//
// word = atom / quoted-string
//
// atom = [CFWS] 1*atext [CFWS]
switch (token) {
// Comment
case '(':
if (elementLength === 0) {
// Comments are OK at the beginning of an element
updateResult(elementCount === 0 ? internals.diagnoses.cfwsComment : internals.diagnoses.deprecatedComment);
}
else {
updateResult(internals.diagnoses.cfwsComment);
// Cannot start a comment in an element, should be end
assertEnd = true;
}
context.stack.push(context.now);
context.now = internals.components.contextComment;
break;
// Next dot-atom element
case '.':
if (elementLength === 0) {
// Another dot, already?
updateResult(elementCount === 0 ? internals.diagnoses.errDotStart : internals.diagnoses.errConsecutiveDots);
}
else {
// The entire local-part can be a quoted string for RFC 5321; if one atom is quoted it's an RFC 5322 obsolete form
if (assertEnd) {
updateResult(internals.diagnoses.deprecatedLocalPart);
}
// CFWS & quoted strings are OK again now we're at the beginning of an element (although they are obsolete forms)
assertEnd = false;
elementLength = 0;
++elementCount;
parseData.local += token;
atomData.locals[elementCount] = '';
}
break;
// Quoted string
case '"':
if (elementLength === 0) {
// The entire local-part can be a quoted string for RFC 5321; if one atom is quoted it's an RFC 5322 obsolete form
updateResult(elementCount === 0 ? internals.diagnoses.rfc5321QuotedString : internals.diagnoses.deprecatedLocalPart);
parseData.local += token;
atomData.locals[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
// Quoted string must be the entire element
assertEnd = true;
context.stack.push(context.now);
context.now = internals.components.contextQuotedString;
}
else {
updateResult(internals.diagnoses.errExpectingATEXT);
}
break;
// Folding white space
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case ' ':
case '\t':
if (elementLength === 0) {
updateResult(elementCount === 0 ? internals.diagnoses.cfwsFWS : internals.diagnoses.deprecatedFWS);
}
else {
// We can't start FWS in the middle of an element, better be end
assertEnd = true;
}
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
case '@':
// At this point we should have a valid local-part
// $lab:coverage:off$
if (context.stack.length !== 1) {
throw new Error('unexpected item on context stack');
}
// $lab:coverage:on$
if (parseData.local.length === 0) {
// Fatal error
updateResult(internals.diagnoses.errNoLocalPart);
}
else if (elementLength === 0) {
// Fatal error
updateResult(internals.diagnoses.errDotEnd);
}
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 the maximum total length of a user name or other local-part is 64
// octets
else if (Buffer.byteLength(parseData.local, 'utf8') > 64) {
updateResult(internals.diagnoses.rfc5322LocalTooLong);
}
// http://tools.ietf.org/html/rfc5322#section-3.4.1 comments and folding white space SHOULD NOT be used around "@" in the
// addr-spec
//
// http://tools.ietf.org/html/rfc2119
// 4. SHOULD NOT this phrase, or the phrase "NOT RECOMMENDED" mean that there may exist valid reasons in particular
// circumstances when the particular behavior is acceptable or even useful, but the full implications should be understood
// and the case carefully weighed before implementing any behavior described with this label.
else if (context.prev === internals.components.contextComment || context.prev === internals.components.contextFWS) {
updateResult(internals.diagnoses.deprecatedCFWSNearAt);
}
// Clear everything down for the domain parsing
context.now = internals.components.domain;
context.stack[0] = internals.components.domain;
elementCount = 0;
elementLength = 0;
assertEnd = false; // CFWS can only appear at the end of the element
break;
// ATEXT
default:
// http://tools.ietf.org/html/rfc5322#section-3.2.3
// atext = ALPHA / DIGIT / ; Printable US-ASCII
// "!" / "#" / ; characters not including
// "$" / "%" / ; specials. Used for atoms.
// "&" / "'" /
// "*" / "+" /
// "-" / "/" /
// "=" / "?" /
// "^" / "_" /
// "`" / "{" /
// "|" / "}" /
// "~"
if (assertEnd) {
// We have encountered atext where it is no longer valid
switch (context.prev) {
case internals.components.contextComment:
case internals.components.contextFWS:
updateResult(internals.diagnoses.errATEXTAfterCFWS);
break;
case internals.components.contextQuotedString:
updateResult(internals.diagnoses.errATEXTAfterQS);
break;
// $lab:coverage:off$
default:
throw new Error('more atext found where none is allowed, but unrecognized prev context: ' + context.prev);
// $lab:coverage:on$
}
}
else {
context.prev = context.now;
charCode = token.codePointAt(0);
// Especially if charCode == 10
if (internals.specials(charCode) || internals.c0Controls(charCode) || internals.c1Controls(charCode)) {
// Fatal error
updateResult(internals.diagnoses.errExpectingATEXT);
}
parseData.local += token;
atomData.locals[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
}
}
break;
case internals.components.domain:
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// domain = dot-atom / domain-literal / obs-domain
//
// dot-atom = [CFWS] dot-atom-text [CFWS]
//
// dot-atom-text = 1*atext *("." 1*atext)
//
// domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
//
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
//
// obs-domain = atom *("." atom)
//
// atom = [CFWS] 1*atext [CFWS]
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// Mailbox = Local-part "@" ( Domain / address-literal )
//
// Domain = sub-domain *("." sub-domain)
//
// address-literal = "[" ( IPv4-address-literal /
// IPv6-address-literal /
// General-address-literal ) "]"
// ; See Section 4.1.3
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// Note: A liberal syntax for the domain portion of addr-spec is
// given here. However, the domain portion contains addressing
// information specified by and used in other protocols (e.g.,
// [RFC1034], [RFC1035], [RFC1123], [RFC5321]). It is therefore
// incumbent upon implementations to conform to the syntax of
// addresses for the context in which they are used.
//
// is_email() author's note: it's not clear how to interpret this in
// he context of a general email address validator. The conclusion I
// have reached is this: "addressing information" must comply with
// RFC 5321 (and in turn RFC 1035), anything that is "semantically
// invisible" must comply only with RFC 5322.
switch (token) {
// Comment
case '(':
if (elementLength === 0) {
// Comments at the start of the domain are deprecated in the text, comments at the start of a subdomain are obs-domain
// http://tools.ietf.org/html/rfc5322#section-3.4.1
updateResult(elementCount === 0 ? internals.diagnoses.deprecatedCFWSNearAt : internals.diagnoses.deprecatedComment);
}
else {
// We can't start a comment mid-element, better be at the end
assertEnd = true;
updateResult(internals.diagnoses.cfwsComment);
}
context.stack.push(context.now);
context.now = internals.components.contextComment;
break;
// Next dot-atom element
case '.':
const punycodeLength = Punycode.encode(atomData.domains[elementCount]).length;
if (elementLength === 0) {
// Another dot, already? Fatal error.
updateResult(elementCount === 0 ? internals.diagnoses.errDotStart : internals.diagnoses.errConsecutiveDots);
}
else if (hyphenFlag) {
// Previous subdomain ended in a hyphen. Fatal error.
updateResult(internals.diagnoses.errDomainHyphenEnd);
}
else if (punycodeLength > 63) {
// RFC 5890 specifies that domain labels that are encoded using the Punycode algorithm
// must adhere to the <= 63 octet requirement.
// This includes string prefixes from the Punycode algorithm.
//
// https://tools.ietf.org/html/rfc5890#section-2.3.2.1
// labels 63 octets or less
updateResult(internals.diagnoses.rfc5322LabelTooLong);
}
// CFWS is OK again now we're at the beginning of an element (although
// it may be obsolete CFWS)
assertEnd = false;
elementLength = 0;
++elementCount;
atomData.domains[elementCount] = '';
parseData.domain += token;
break;
// Domain literal
case '[':
if (parseData.domain.length === 0) {
// Domain literal must be the only component
assertEnd = true;
elementLength += Buffer.byteLength(token, 'utf8');
context.stack.push(context.now);
context.now = internals.components.literal;
parseData.domain += token;
atomData.domains[elementCount] += token;
parseData.literal = '';
}
else {
// Fatal error
updateResult(internals.diagnoses.errExpectingATEXT);
}
break;
// Folding white space
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case ' ':
case '\t':
if (elementLength === 0) {
updateResult(elementCount === 0 ? internals.diagnoses.deprecatedCFWSNearAt : internals.diagnoses.deprecatedFWS);
}
else {
// We can't start FWS in the middle of an element, so this better be the end
updateResult(internals.diagnoses.cfwsFWS);
assertEnd = true;
}
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
// This must be ATEXT
default:
// RFC 5322 allows any atext...
// http://tools.ietf.org/html/rfc5322#section-3.2.3
// atext = ALPHA / DIGIT / ; Printable US-ASCII
// "!" / "#" / ; characters not including
// "$" / "%" / ; specials. Used for atoms.
// "&" / "'" /
// "*" / "+" /
// "-" / "/" /
// "=" / "?" /
// "^" / "_" /
// "`" / "{" /
// "|" / "}" /
// "~"
// But RFC 5321 only allows letter-digit-hyphen to comply with DNS rules
// (RFCs 1034 & 1123)
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// sub-domain = Let-dig [Ldh-str]
//
// Let-dig = ALPHA / DIGIT
//
// Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
//
if (assertEnd) {
// We have encountered ATEXT where it is no longer valid
switch (context.prev) {
case internals.components.contextComment:
case internals.components.contextFWS:
updateResult(internals.diagnoses.errATEXTAfterCFWS);
break;
case internals.components.literal:
updateResult(internals.diagnoses.errATEXTAfterDomainLiteral);
break;
// $lab:coverage:off$
default:
throw new Error('more atext found where none is allowed, but unrecognized prev context: ' + context.prev);
// $lab:coverage:on$
}
}
charCode = token.codePointAt(0);
// Assume this token isn't a hyphen unless we discover it is
hyphenFlag = false;
if (internals.specials(charCode) || internals.c0Controls(charCode) || internals.c1Controls(charCode)) {
// Fatal error
updateResult(internals.diagnoses.errExpectingATEXT);
}
else if (token === '-') {
if (elementLength === 0) {
// Hyphens cannot be at the beginning of a subdomain, fatal error
updateResult(internals.diagnoses.errDomainHyphenStart);
}
hyphenFlag = true;
}
// Check if it's a neither a number nor a latin/unicode letter
else if (charCode < 48 || (charCode > 122 && charCode < 192) || (charCode > 57 && charCode < 65) || (charCode > 90 && charCode < 97)) {
// This is not an RFC 5321 subdomain, but still OK by RFC 5322
updateResult(internals.diagnoses.rfc5322Domain);
}
parseData.domain += token;
atomData.domains[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
}
break;
// Domain literal
case internals.components.literal:
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
//
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
//
// obs-dtext = obs-NO-WS-CTL / quoted-pair
switch (token) {
// End of domain literal
case ']':
if (maxResult < internals.categories.deprecated) {
// Could be a valid RFC 5321 address literal, so let's check
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// address-literal = "[" ( IPv4-address-literal /
// IPv6-address-literal /
// General-address-literal ) "]"
// ; See Section 4.1.3
//
// http://tools.ietf.org/html/rfc5321#section-4.1.3
// IPv4-address-literal = Snum 3("." Snum)
//
// IPv6-address-literal = "IPv6:" IPv6-addr
//
// General-address-literal = Standardized-tag ":" 1*dcontent
//
// Standardized-tag = Ldh-str
// ; Standardized-tag MUST be specified in a
// ; Standards-Track RFC and registered with IANA
//
// dcontent = %d33-90 / ; Printable US-ASCII
// %d94-126 ; excl. "[", "\", "]"
//
// Snum = 1*3DIGIT
// ; representing a decimal integer
// ; value in the range 0 through 255
//
// IPv6-addr = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp
//
// IPv6-hex = 1*4HEXDIG
//
// IPv6-full = IPv6-hex 7(":" IPv6-hex)
//
// IPv6-comp = [IPv6-hex *5(":" IPv6-hex)] "::"
// [IPv6-hex *5(":" IPv6-hex)]
// ; The "::" represents at least 2 16-bit groups of
// ; zeros. No more than 6 groups in addition to the
// ; "::" may be present.
//
// IPv6v4-full = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal
//
// IPv6v4-comp = [IPv6-hex *3(":" IPv6-hex)] "::"
// [IPv6-hex *3(":" IPv6-hex) ":"]
// IPv4-address-literal
// ; The "::" represents at least 2 16-bit groups of
// ; zeros. No more than 4 groups in addition to the
// ; "::" and IPv4-address-literal may be present.
let index = -1;
let addressLiteral = parseData.literal;
const matchesIP = internals.regex.ipV4.exec(addressLiteral);
// Maybe extract IPv4 part from the end of the address-literal
if (matchesIP) {
index = matchesIP.index;
if (index !== 0) {
// Convert IPv4 part to IPv6 format for futher testing
addressLiteral = addressLiteral.slice(0, index) + '0:0';
}
}
if (index === 0) {
// Nothing there except a valid IPv4 address, so...
updateResult(internals.diagnoses.rfc5321AddressLiteral);
}
else if (addressLiteral.slice(0, 5).toLowerCase() !== 'ipv6:') {
updateResult(internals.diagnoses.rfc5322DomainLiteral);
}
else {
const match = addressLiteral.slice(5);
let maxGroups = internals.maxIPv6Groups;
const groups = match.split(':');
index = match.indexOf('::');
if (!~index) {
// Need exactly the right number of groups
if (groups.length !== maxGroups) {
updateResult(internals.diagnoses.rfc5322IPv6GroupCount);
}
}
else if (index !== match.lastIndexOf('::')) {
updateResult(internals.diagnoses.rfc5322IPv62x2xColon);
}
else {
if (index === 0 || index === match.length - 2) {
// RFC 4291 allows :: at the start or end of an address with 7 other groups in addition
++maxGroups;
}
if (groups.length > maxGroups) {
updateResult(internals.diagnoses.rfc5322IPv6MaxGroups);
}
else if (groups.length === maxGroups) {
// Eliding a single "::"
updateResult(internals.diagnoses.deprecatedIPv6);
}
}
// IPv6 testing strategy
if (match[0] === ':' && match[1] !== ':') {
updateResult(internals.diagnoses.rfc5322IPv6ColonStart);
}
else if (match[match.length - 1] === ':' && match[match.length - 2] !== ':') {
updateResult(internals.diagnoses.rfc5322IPv6ColonEnd);
}
else if (internals.checkIpV6(groups)) {
updateResult(internals.diagnoses.rfc5321AddressLiteral);
}
else {
updateResult(internals.diagnoses.rfc5322IPv6BadCharacter);
}
}
}
else {
updateResult(internals.diagnoses.rfc5322DomainLiteral);
}
parseData.domain += token;
atomData.domains[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
context.prev = context.now;
context.now = context.stack.pop();
break;
case '\\':
updateResult(internals.diagnoses.rfc5322DomainLiteralOBSDText);
context.stack.push(context.now);
context.now = internals.components.contextQuotedPair;
break;
// Folding white space
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case ' ':
case '\t':
updateResult(internals.diagnoses.cfwsFWS);
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
// DTEXT
default:
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
//
// obs-dtext = obs-NO-WS-CTL / quoted-pair
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
charCode = token.codePointAt(0);
// '\r', '\n', ' ', and '\t' have already been parsed above
if ((charCode !== 127 && internals.c1Controls(charCode)) || charCode === 0 || token === '[') {
// Fatal error
updateResult(internals.diagnoses.errExpectingDTEXT);
break;
}
else if (internals.c0Controls(charCode) || charCode === 127) {
updateResult(internals.diagnoses.rfc5322DomainLiteralOBSDText);
}
parseData.literal += token;
parseData.domain += token;
atomData.domains[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
}
break;
// Quoted string
case internals.components.contextQuotedString:
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// quoted-string = [CFWS]
// DQUOTE *([FWS] qcontent) [FWS] DQUOTE
// [CFWS]
//
// qcontent = qtext / quoted-pair
switch (token) {
// Quoted pair
case '\\':
context.stack.push(context.now);
context.now = internals.components.contextQuotedPair;
break;
// Folding white space. Spaces are allowed as regular characters inside a quoted string - it's only FWS if we include '\t' or '\r\n'
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case '\t':
// http://tools.ietf.org/html/rfc5322#section-3.2.2
// Runs of FWS, comment, or CFWS that occur between lexical tokens in
// a structured header field are semantically interpreted as a single
// space character.
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// the CRLF in any FWS/CFWS that appears within the quoted-string [is]
// semantically "invisible" and therefore not part of the
// quoted-string
parseData.local += ' ';
atomData.locals[elementCount] += ' ';
elementLength += Buffer.byteLength(token, 'utf8');
updateResult(internals.diagnoses.cfwsFWS);
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
// End of quoted string
case '"':
parseData.local += token;
atomData.locals[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
context.prev = context.now;
context.now = context.stack.pop();
break;
// QTEXT
default:
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// qtext = %d33 / ; Printable US-ASCII
// %d35-91 / ; characters not including
// %d93-126 / ; "\" or the quote character
// obs-qtext
//
// obs-qtext = obs-NO-WS-CTL
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
charCode = token.codePointAt(0);
if ((charCode !== 127 && internals.c1Controls(charCode)) || charCode === 0 || charCode === 10) {
updateResult(internals.diagnoses.errExpectingQTEXT);
}
else if (internals.c0Controls(charCode) || charCode === 127) {
updateResult(internals.diagnoses.deprecatedQTEXT);
}
parseData.local += token;
atomData.locals[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
}
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// If the string can be represented as a dot-atom (that is, it contains
// no characters other than atext characters or "." surrounded by atext
// characters), then the dot-atom form SHOULD be used and the quoted-
// string form SHOULD NOT be used.
break;
// Quoted pair
case internals.components.contextQuotedPair:
// http://tools.ietf.org/html/rfc5322#section-3.2.1
// quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
//
// VCHAR = %d33-126 ; visible (printing) characters
// WSP = SP / HTAB ; white space
//
// obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
//
// i.e. obs-qp = "\" (%d0-8, %d10-31 / %d127)
charCode = token.codePointAt(0);
if (charCode !== 127 && internals.c1Controls(charCode)) {
// Fatal error
updateResult(internals.diagnoses.errExpectingQPair);
}
else if ((charCode < 31 && charCode !== 9) || charCode === 127) {
// ' ' and '\t' are allowed
updateResult(internals.diagnoses.deprecatedQP);
}
// At this point we know where this qpair occurred so we could check to see if the character actually needed to be quoted at all.
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// the sending system SHOULD transmit the form that uses the minimum quoting possible.
context.prev = context.now;
// End of qpair
context.now = context.stack.pop();
const escapeToken = '\\' + token;
switch (context.now) {
case internals.components.contextComment:
break;
case internals.components.contextQuotedString:
parseData.local += escapeToken;
atomData.locals[elementCount] += escapeToken;
// The maximum sizes specified by RFC 5321 are octet counts, so we must include the backslash
elementLength += 2;
break;
case internals.components.literal:
parseData.domain += escapeToken;
atomData.domains[elementCount] += escapeToken;
// The maximum sizes specified by RFC 5321 are octet counts, so we must include the backslash
elementLength += 2;
break;
// $lab:coverage:off$
default:
throw new Error('quoted pair logic invoked in an invalid context: ' + context.now);
// $lab:coverage:on$
}
break;
// Comment
case internals.components.contextComment:
// http://tools.ietf.org/html/rfc5322#section-3.2.2
// comment = "(" *([FWS] ccontent) [FWS] ")"
//
// ccontent = ctext / quoted-pair / comment
switch (token) {
// Nested comment
case '(':
// Nested comments are ok
context.stack.push(context.now);
context.now = internals.components.contextComment;
break;
// End of comment
case ')':
context.prev = context.now;
context.now = context.stack.pop();
break;
// Quoted pair
case '\\':
context.stack.push(context.now);
context.now = internals.components.contextQuotedPair;
break;
// Folding white space
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case ' ':
case '\t':
updateResult(internals.diagnoses.cfwsFWS);
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
// CTEXT
default:
// http://tools.ietf.org/html/rfc5322#section-3.2.3
// ctext = %d33-39 / ; Printable US-ASCII
// %d42-91 / ; characters not including
// %d93-126 / ; "(", ")", or "\"
// obs-ctext
//
// obs-ctext = obs-NO-WS-CTL
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
charCode = token.codePointAt(0);
if (charCode === 0 || charCode === 10 || (charCode !== 127 && internals.c1Controls(charCode))) {
// Fatal error
updateResult(internals.diagnoses.errExpectingCTEXT);
break;
}
else if (internals.c0Controls(charCode) || charCode === 127) {
updateResult(internals.diagnoses.deprecatedCTEXT);
}
}
break;
// Folding white space
case internals.components.contextFWS:
// http://tools.ietf.org/html/rfc5322#section-3.2.2
// FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
// ; Folding white space
// But note the erratum:
// http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908:
// In the obsolete syntax, any amount of folding white space MAY be
// inserted where the obs-FWS rule is allowed. This creates the
// possibility of having two consecutive "folds" in a line, and
// therefore the possibility that a line which makes up a folded header
// field could be composed entirely of white space.
//
// obs-FWS = 1*([CRLF] WSP)
if (prevToken === '\r') {
if (token === '\r') {
// Fatal error
updateResult(internals.diagnoses.errFWSCRLFx2);
break;
}
if (++crlfCount > 1) {
// Multiple folds => obsolete FWS
updateResult(internals.diagnoses.deprecatedFWS);
}
else {
crlfCount = 1;
}
}
switch (token) {
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
}
break;
case ' ':
case '\t':
break;
default:
if (prevToken === '\r') {
// Fatal error
updateResult(internals.diagnoses.errFWSCRLFEnd);
}
crlfCount = 0;
// End of FWS
context.prev = context.now;
context.now = context.stack.pop();
// Look at this token again in the parent context
--i;
}
prevToken = token;
break;
// Unexpected context
// $lab:coverage:off$
default:
throw new Error('unknown context: ' + context.now);
// $lab:coverage:on$
} // Primary state machine
if (maxResult > internals.categories.rfc5322) {
// Fatal error, no point continuing
break;
}
} // Token loop
// Check for errors
if (maxResult < internals.categories.rfc5322) {
const punycodeLength = Punycode.encode(parseData.domain).length;
// Fatal errors
if (context.now === internals.components.contextQuotedString) {
updateResult(internals.diagnoses.errUnclosedQuotedString);
}
else if (context.now === internals.components.contextQuotedPair) {
updateResult(internals.diagnoses.errBackslashEnd);
}
else if (context.now === internals.components.contextComment) {
updateResult(internals.diagnoses.errUnclosedComment);
}
else if (context.now === internals.components.literal) {
updateResult(internals.diagnoses.errUnclosedDomainLiteral);
}
else if (token === '\r') {
updateResult(internals.diagnoses.errFWSCRLFEnd);
}
else if (parseData.domain.length === 0) {
updateResult(internals.diagnoses.errNoDomain);
}
else if (elementLength === 0) {
updateResult(internals.diagnoses.errDotEnd);
}
else if (hyphenFlag) {
updateResult(internals.diagnoses.errDomainHyphenEnd);
}
// Other errors
else if (punycodeLength > 255) {
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.2
// The maximum total length of a domain name or number is 255 octets.
updateResult(internals.diagnoses.rfc5322DomainTooLong);
}
else if (Buffer.byteLength(parseData.local, 'utf8') + punycodeLength + /* '@' */ 1 > 254) {
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// Forward-path = Path
//
// Path = "<" [ A-d-l ":" ] Mailbox ">"
//
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3
// The maximum total length of a reverse-path or forward-path is 256 octets (including the punctuation and element separators).
//
// Thus, even without (obsolete) routing information, the Mailbox can only be 254 characters long. This is confirmed by this verified
// erratum to RFC 3696:
//
// http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690
// However, there is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands of 254 characters. Since
// addresses that do not fit in those fields are not normally useful, the upper limit on address lengths should normally be considered
// to be 254.
updateResult(internals.diagnoses.rfc5322TooLong);
}
else if (elementLength > 63) {
// http://tools.ietf.org/html/rfc1035#section-2.3.4
// labels 63 octets or less
updateResult(internals.diagnoses.rfc5322LabelTooLong);
}
else if (options.minDomainAtoms && atomData.domains.length < options.minDomainAtoms) {
updateResult(internals.diagnoses.errDomainTooShort);
}
else if (options.tldWhitelist || options.tldBlacklist) {
const tldAtom = atomData.domains[elementCount];
if (!internals.validDomain(tldAtom, options)) {
updateResult(internals.diagnoses.errUnknownTLD);
}
}
} // Check for errors
// Finish
if (maxResult < internals.categories.dnsWarn) {
// Per RFC 5321, domain atoms are limited to letter-digit-hyphen, so we only need to check code <= 57 to check for a digit
const code = atomData.domains[elementCount].codePointAt(0);
if (code <= 57) {
updateResult(internals.diagnoses.rfc5321TLDNumeric);
}
}
if (maxResult < threshold) {
maxResult = internals.diagnoses.valid;
}
const finishResult = diagnose ? maxResult : maxResult < internals.defaultThreshold;
if (callback) {
callback(finishResult);
}
return finishResult;
};
exports.diagnoses = internals.validate.diagnoses = (function () {
const diag = {};
const keys = Object.keys(internals.diagnoses);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
diag[key] = internals.diagnoses[key];
}
return diag;
})();
exports.normalize = internals.normalize = function (email) {
// $lab:coverage:off$
if (process.version[1] === '4' && email.indexOf('\u0000') >= 0) {
return internals.nulNormalize(email);
}
// $lab:coverage:on$
return email.normalize('NFC');
};
{
"_from": "isemail@3.x.x",
"_id": "isemail@3.1.1",
"_inBundle": false,
"_integrity": "sha512-mVjAjvdPkpwXW61agT2E9AkGoegZO7SdJGCezWwxnETL58f5KwJ4vSVAMBUL5idL6rTlYAIGkX3n4suiviMLNw==",
"_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.1.1.tgz",
"_shasum": "e8450fe78ff1b48347db599122adcd0668bd92b5",
"_spec": "isemail@3.x.x",
"_where": "/Users/jeminlee/git-projects/node-practice/express-demo/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": "3.x.x",
"lab": "15.x.x"
},
"engines": {
"node": ">=4.0.0"
},
"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.1.1"
}
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).
Copyright (c) 2012-2017, 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
![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.1.2/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()
}).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
# 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.
'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);
};
'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;
};
'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');
// 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')
};
internals.applyDefaults = function (schema) {
Hoek.assert(this, 'Must be invoked on a Joi instance.');
if (this._defaults) {
schema = this._defaults(schema);
}
schema._currentJoi = this;
return schema;
};
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.applyDefaults.call(this, any);
};
root.alternatives = root.alt = function (...args) {
const alternatives = internals.applyDefaults.call(this, internals.alternatives);
return args.length ? alternatives.try.apply(alternatives, args) : alternatives;
};
root.array = function (...args) {
Hoek.assert(args.length === 0, 'Joi.array() does not allow arguments.');
return internals.applyDefaults.call(this, internals.array);
};
root.boolean = root.bool = function (...args) {
Hoek.assert(args.length === 0, 'Joi.boolean() does not allow arguments.');
return internals.applyDefaults.call(this, internals.boolean);
};
root.binary = function (...args) {
Hoek.assert(args.length === 0, 'Joi.binary() does not allow arguments.');
return internals.applyDefaults.call(this, internals.binary);
};
root.date = function (...args) {
Hoek.assert(args.length === 0, 'Joi.date() does not allow arguments.');
return internals.applyDefaults.call(this, internals.date);
};
root.func = function (...args) {
Hoek.assert(args.length === 0, 'Joi.func() does not allow arguments.');
return internals.applyDefaults.call(this, internals.func);
};
root.number = function (...args) {
Hoek.assert(args.length === 0, 'Joi.number() does not allow arguments.');
return internals.applyDefaults.call(this, internals.number);
};
root.object = function (...args) {
const object = internals.applyDefaults.call(this, internals.object);
return args.length ? object.keys(...args) : object;
};
root.string = function (...args) {
Hoek.assert(args.length === 0, 'Joi.string() does not allow arguments.');
return internals.applyDefaults.call(this, internals.string);
};
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] : {};
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(typeof path === 'string', 'path must be a string');
if (path === '') {
return schema;
}
const parts = path.split('.');
const children = schema._inner.children;
if (!children) {
return;
}
const key = parts[0];
for (let i = 0; i < children.length; ++i) {
const child = children[i];
if (child.key === key) {
return this.reach(child.schema, path.substr(key.length + 1));
}
}
};
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 = this._settings || { language: {} };
this._settings.language = Hoek.applyToDefaults(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 () {
return internals.applyDefaults.call(this, instance);
};
}
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();
'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}}"',
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}}'
},
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',
base64: 'must be a valid base64 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'
}
};
'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);
}
};
'use strict';
// Load modules
const Joi = require('../');
// 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();
'use strict';
const Ref = require('./ref');
module.exports = class Set {
constructor() {
this._set = [];
}
add(value, refs) {
if (!Ref.isRef(value) && this.has(value, null, null, false)) {
return;
}
if (refs !== undefined) { // If it's a merge, we don't have any refs
Ref.push(refs, value);
}
this._set.push(value);
return this;
}
merge(add, remove) {
for (let i = 0; i < add._set.length; ++i) {
this.add(add._set[i]);
}
for (let i = 0; i < remove._set.length; ++i) {
this.remove(remove._set[i]);
}
return this;
}
remove(value) {
this._set = this._set.filter((item) => value !== item);
return this;
}
has(value, state, options, insensitive) {
for (let i = 0; i < this._set.length; ++i) {
let items = this._set[i];
if (state && Ref.isRef(items)) { // Only resolve references if there is a state, otherwise it's a merge
items = items(state.reference || state.parent, options);
}
if (!Array.isArray(items)) {
items = [items];
}
for (let j = 0; j < items.length; ++j) {
const item = items[j];
if (typeof value !== typeof item) {
continue;
}
if (value === item ||
(value instanceof Date && item instanceof Date && value.getTime() === item.getTime()) ||
(insensitive && typeof value === 'string' && value.toLowerCase() === item.toLowerCase()) ||
(Buffer.isBuffer(value) && Buffer.isBuffer(item) && value.length === item.length && value.toString('binary') === item.toString('binary'))) {
return true;
}
}
}
return false;
}
values(options) {
if (options && options.stripUndefined) {
const values = [];
for (let i = 0; i < this._set.length; ++i) {
const item = this._set[i];
if (item !== undefined) {
values.push(item);
}
}
return values;
}
return this._set.slice();
}
slice() {
const newSet = new Set();
newSet._set = this._set.slice();
return newSet;
}
concat(source) {
const newSet = new Set();
newSet._set = this._set.concat(source._set);
return newSet;
}
};
'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 = [];
}
_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 = Any.prototype.describe.call(this);
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();
'use strict';
// Load modules
const Hoek = require('hoek');
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
}
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 = internals.concatSettings(this._settings);
obj._baseType = this._baseType;
obj._valids = Hoek.clone(this._valids);
obj._invalids = Hoek.clone(this._invalids);
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 ? internals.concatSettings(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 = internals.concatSettings(obj._settings, options);
return obj;
}
strict(isStrict) {
const obj = this.clone();
obj._settings = obj._settings || {};
obj._settings.convert = isStrict === undefined ? false : !isStrict;
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 = internals.concatSettings(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', null, 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', null, state, options));
if (options.abortEarly) {
return finish();
}
}
}
}
// Required values did not match
if (this._flags.allowOnly) {
errors.push(this.createError('any.allowOnly', { valids: this._valids.values({ stripUndefined: true }) }, state, options));
if (options.abortEarly) {
return finish();
}
}
// Helper.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 = internals.concatSettings(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
};
};
internals.concatSettings = function (target, source) {
// Used to avoid cloning context
if (!target &&
!source) {
return null;
}
const obj = Object.assign({}, target);
if (source) {
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;
};
'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 = Any.prototype.describe.call(this);
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) {
Hoek.assert(comparator === undefined ||
typeof comparator === 'function' ||
typeof comparator === 'string', 'comparator must be a function or a string');
const settings = {};
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: {},
number: {},
undefined: {},
boolean: {},
object: new Map(),
function: new Map(),
custom: new Map()
};
const compare = settings.comparator || Hoek.deepEqual;
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 (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();
'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 = new Buffer(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();
'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 = Any.prototype.describe.call(this);
description.truthy = [true].concat(this._inner.truthySet.values());
description.falsy = [false].concat(this._inner.falsySet.values());
return description;
}
};
module.exports = new internals.Boolean();
'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);
module.exports = new internals.Date();
'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();
'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();
'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', null, 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;
}
};
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();
'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 = [];
}
_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 = Hoek.mapToObject(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];
delete unprocessed[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
let unprocessedKeys = Object.keys(unprocessed);
if (unprocessedKeys.length &&
this._inner.patterns.length) {
for (let i = 0; i < unprocessedKeys.length; ++i) {
const key = unprocessedKeys[i];
const localState = { key, path: state.path.concat(key), parent: target, reference: state.reference };
const item = target[key];
for (let j = 0; j < this._inner.patterns.length; ++j) {
const pattern = this._inner.patterns[j];
if (pattern.regex.test(key)) {
delete unprocessed[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;
}
}
}
unprocessedKeys = Object.keys(unprocessed);
}
if ((this._inner.children || this._inner.patterns.length) && unprocessedKeys.length) {
if ((options.stripUnknown && this._flags.allowUnknown !== true) ||
options.skipFunctions) {
const stripUnknown = options.stripUnknown
? (options.stripUnknown === true ? true : !!options.stripUnknown.objects)
: false;
for (let i = 0; i < unprocessedKeys.length; ++i) {
const key = unprocessedKeys[i];
if (stripUnknown) {
delete target[key];
delete unprocessed[key];
}
else if (typeof target[key] === 'function') {
delete unprocessed[key];
}
}
unprocessedKeys = Object.keys(unprocessed);
}
if (unprocessedKeys.length &&
(this._flags.allowUnknown !== undefined ? !this._flags.allowUnknown : !options.allowUnknown)) {
for (let i = 0; i < unprocessedKeys.length; ++i) {
const unprocessedKey = unprocessedKeys[i];
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;
}
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) {
Hoek.assert(pattern instanceof RegExp, 'Invalid regular expression');
Hoek.assert(schema !== undefined, 'Invalid rule');
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();
obj._inner.patterns.push({ regex: 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 = Any.prototype.describe.call(this);
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];
description.patterns.push({ regex: pattern.regex.toString(), 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();
'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;
}
}
}
}
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 regex = internals.uriRegex;
if (uriOptions) {
Hoek.assert(typeof uriOptions === 'object', 'options must be an object');
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 (customScheme || allowRelative || relativeOnly) {
regex = Uri.createUriRegex(customScheme, allowRelative, relativeOnly);
}
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() {
const regex = /^[a-f0-9]+$/i;
return this._test('hex', regex, function (value, state, options) {
if (regex.test(value)) {
return value;
}
return this.createError('string.hex', { value }, state, options);
});
}
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);
});
}
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() {
const 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);
});
obj._flags.trim = true;
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();
'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;
'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 + ']';
/**
* 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.
/**
* fragment = *( pchar / "/" / "?" )
*/
internals.rfc3986.fragment = '[' + pchar + '\\/\\?]*';
};
internals.generate();
module.exports = internals.rfc3986;
'use strict';
// Load Modules
const RFC3986 = require('./rfc3986');
// Declare internals
const internals = {
Uri: {
createUriRegex: function (optionalScheme, allowRelative, relativeOnly) {
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 + '(?:\\?' + RFC3986.query + ')?' + '(?:#' + RFC3986.fragment + ')?$');
}
}
};
module.exports = internals.Uri;
{
"_from": "joi",
"_id": "joi@13.1.2",
"_inBundle": false,
"_integrity": "sha512-bZZSQYW5lPXenOfENvgCBPb9+H6E6MeNWcMtikI04fKphj5tvFL9TOb+H2apJzbCrRw/jebjTH8z6IHLpBytGg==",
"_location": "/joi",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "joi",
"name": "joi",
"escapedName": "joi",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/joi/-/joi-13.1.2.tgz",
"_shasum": "b2db260323cc7f919fafa51e09e2275bd089a97e",
"_spec": "joi",
"_where": "/Users/jeminlee/git-projects/node-practice/express-demo",
"bugs": {
"url": "https://github.com/hapijs/joi/issues"
},
"bundleDependencies": false,
"dependencies": {
"hoek": "5.x.x",
"isemail": "3.x.x",
"topo": "3.x.x"
},
"deprecated": false,
"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.1.2"
}
Copyright Mathias Bynens <https://mathiasbynens.be/>
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.
# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js)
Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891).
This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm:
* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C)
* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c)
* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c)
* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287)
* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072))
This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated).
The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1).
## Installation
Via [npm](https://www.npmjs.com/):
```bash
npm install punycode --save
```
In [Node.js](https://nodejs.org/):
```js
const punycode = require('punycode');
```
## API
### `punycode.decode(string)`
Converts a Punycode string of ASCII symbols to a string of Unicode symbols.
```js
// decode domain name parts
punycode.decode('maana-pta'); // 'mañana'
punycode.decode('--dqo34k'); // '☃-⌘'
```
### `punycode.encode(string)`
Converts a string of Unicode symbols to a Punycode string of ASCII symbols.
```js
// encode domain name parts
punycode.encode('mañana'); // 'maana-pta'
punycode.encode('☃-⌘'); // '--dqo34k'
```
### `punycode.toUnicode(input)`
Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode.
```js
// decode domain names
punycode.toUnicode('xn--maana-pta.com');
// → 'mañana.com'
punycode.toUnicode('xn----dqo34k.com');
// → '☃-⌘.com'
// decode email addresses
punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq');
// → 'джумла@джpумлатест.bрфa'
```
### `punycode.toASCII(input)`
Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII.
```js
// encode domain names
punycode.toASCII('mañana.com');
// → 'xn--maana-pta.com'
punycode.toASCII('☃-⌘.com');
// → 'xn----dqo34k.com'
// encode email addresses
punycode.toASCII('джумла@джpумлатест.bрфa');
// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'
```
### `punycode.ucs2`
#### `punycode.ucs2.decode(string)`
Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16.
```js
punycode.ucs2.decode('abc');
// → [0x61, 0x62, 0x63]
// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE:
punycode.ucs2.decode('\uD834\uDF06');
// → [0x1D306]
```
#### `punycode.ucs2.encode(codePoints)`
Creates a string based on an array of numeric code point values.
```js
punycode.ucs2.encode([0x61, 0x62, 0x63]);
// → 'abc'
punycode.ucs2.encode([0x1D306]);
// → '\uD834\uDF06'
```
### `punycode.version`
A string representing the current Punycode.js version number.
## Author
| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") |
|---|
| [Mathias Bynens](https://mathiasbynens.be/) |
## License
Punycode.js is available under the [MIT](https://mths.be/mit) license.
{
"_from": "punycode@2.x.x",
"_id": "punycode@2.1.0",
"_inBundle": false,
"_integrity": "sha1-X4Y+3Im5bbCQdLrXlHvwkFbKTn0=",
"_location": "/punycode",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "punycode@2.x.x",
"name": "punycode",
"escapedName": "punycode",
"rawSpec": "2.x.x",
"saveSpec": null,
"fetchSpec": "2.x.x"
},
"_requiredBy": [
"/isemail"
],
"_resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.0.tgz",
"_shasum": "5f863edc89b96db09074bad7947bf09056ca4e7d",
"_spec": "punycode@2.x.x",
"_where": "/Users/jeminlee/git-projects/node-practice/express-demo/node_modules/isemail",
"author": {
"name": "Mathias Bynens",
"url": "https://mathiasbynens.be/"
},
"bugs": {
"url": "https://github.com/bestiejs/punycode.js/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Mathias Bynens",
"url": "https://mathiasbynens.be/"
}
],
"deprecated": false,
"description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.",
"devDependencies": {
"codecov": "^1.0.1",
"istanbul": "^0.4.1",
"mocha": "^2.5.3"
},
"engines": {
"node": ">=6"
},
"files": [
"LICENSE-MIT.txt",
"punycode.js",
"punycode.es6.js"
],
"homepage": "https://mths.be/punycode",
"jsnext:main": "punycode.es6.js",
"jspm": {
"map": {
"./punycode.js": {
"node": "@node/punycode"
}
}
},
"keywords": [
"punycode",
"unicode",
"idn",
"idna",
"dns",
"url",
"domain"
],
"license": "MIT",
"main": "punycode.js",
"name": "punycode",
"repository": {
"type": "git",
"url": "git+https://github.com/bestiejs/punycode.js.git"
},
"scripts": {
"prepublish": "node scripts/prepublish.js",
"test": "mocha tests"
},
"version": "2.1.0"
}
'use strict';
/** Highest positive signed 32-bit float value */
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128; // 0x80
const delimiter = '-'; // '\x2D'
/** Regular expressions */
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
/** Error messages */
const errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
};
/** Convenience shortcuts */
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
const result = [];
let length = array.length;
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
const parts = string.split('@');
let result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
const labels = string.split('.');
const encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
const output = [];
let counter = 0;
const length = string.length;
while (counter < length) {
const value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// It's a high surrogate, and there is a next character.
const extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
const ucs2encode = array => String.fromCodePoint(...array);
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
const basicToDigit = function(codePoint) {
if (codePoint - 0x30 < 0x0A) {
return codePoint - 0x16;
}
if (codePoint - 0x41 < 0x1A) {
return codePoint - 0x41;
}
if (codePoint - 0x61 < 0x1A) {
return codePoint - 0x61;
}
return base;
};
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
const digitToBasic = function(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
const adapt = function(delta, numPoints, firstTime) {
let k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
const decode = function(input) {
// Don't use UCS-2.
const output = [];
const inputLength = input.length;
let i = 0;
let n = initialN;
let bias = initialBias;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
let basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (let j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
let oldi = i;
for (let w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
const digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
const baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
const out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output.
output.splice(i++, 0, n);
}
return String.fromCodePoint(...output);
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
const encode = function(input) {
const output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
input = ucs2decode(input);
// Cache the length.
let inputLength = input.length;
// Initialize the state.
let n = initialN;
let delta = 0;
let bias = initialBias;
// Handle the basic code points.
for (const currentValue of input) {
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
let basicLength = output.length;
let handledCPCount = basicLength;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
let m = maxInt;
for (const currentValue of input) {
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow.
const handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (const currentValue of input) {
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer.
let q = delta;
for (let k = base; /* no condition */; k += base) {
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
const qMinusT = q - t;
const baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
};
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
const toUnicode = function(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
};
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
const toASCII = function(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
};
/*--------------------------------------------------------------------------*/
/** Define the public API */
const punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '2.1.0',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
export default punycode;
'use strict';
/** Highest positive signed 32-bit float value */
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128; // 0x80
const delimiter = '-'; // '\x2D'
/** Regular expressions */
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
/** Error messages */
const errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
};
/** Convenience shortcuts */
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
const result = [];
let length = array.length;
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
const parts = string.split('@');
let result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
const labels = string.split('.');
const encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
const output = [];
let counter = 0;
const length = string.length;
while (counter < length) {
const value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// It's a high surrogate, and there is a next character.
const extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
const ucs2encode = array => String.fromCodePoint(...array);
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
const basicToDigit = function(codePoint) {
if (codePoint - 0x30 < 0x0A) {
return codePoint - 0x16;
}
if (codePoint - 0x41 < 0x1A) {
return codePoint - 0x41;
}
if (codePoint - 0x61 < 0x1A) {
return codePoint - 0x61;
}
return base;
};
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
const digitToBasic = function(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
const adapt = function(delta, numPoints, firstTime) {
let k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
const decode = function(input) {
// Don't use UCS-2.
const output = [];
const inputLength = input.length;
let i = 0;
let n = initialN;
let bias = initialBias;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
let basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (let j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
let oldi = i;
for (let w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
const digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
const baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
const out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output.
output.splice(i++, 0, n);
}
return String.fromCodePoint(...output);
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
const encode = function(input) {
const output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
input = ucs2decode(input);
// Cache the length.
let inputLength = input.length;
// Initialize the state.
let n = initialN;
let delta = 0;
let bias = initialBias;
// Handle the basic code points.
for (const currentValue of input) {
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
let basicLength = output.length;
let handledCPCount = basicLength;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
let m = maxInt;
for (const currentValue of input) {
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow.
const handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (const currentValue of input) {
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer.
let q = delta;
for (let k = base; /* no condition */; k += base) {
const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
const qMinusT = q - t;
const baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
};
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
const toUnicode = function(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
};
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
const toASCII = function(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
};
/*--------------------------------------------------------------------------*/
/** Define the public API */
const punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '2.1.0',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
module.exports = punycode;
Copyright (c) 2012-2016, 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/topo/graphs/contributors
# topo
Topological sorting with grouping support.
[![Build Status](https://secure.travis-ci.org/hapijs/topo.svg?branch=master)](http://travis-ci.org/hapijs/topo)
Lead Maintainer: [Devin Ivy](https://github.com/devinivy)
## Usage
See the [API Reference](API.md)
**Example**
```node
const Topo = require('topo');
const morning = new Topo();
morning.add('Nap', { after: ['breakfast', 'prep'] });
morning.add([
'Make toast',
'Pour juice'
], { before: 'breakfast', group: 'prep' });
morning.add('Eat breakfast', { group: 'breakfast' });
morning.nodes; // ['Make toast', 'Pour juice', 'Eat breakfast', 'Nap']
```
'use strict';
// Load modules
const Hoek = require('hoek');
// Declare internals
const internals = {};
exports = module.exports = internals.Topo = function () {
this._items = [];
this.nodes = [];
};
internals.Topo.prototype.add = function (nodes, options) {
options = options || {};
// Validate rules
const before = [].concat(options.before || []);
const after = [].concat(options.after || []);
const group = options.group || '?';
const sort = options.sort || 0; // Used for merging only
Hoek.assert(before.indexOf(group) === -1, 'Item cannot come before itself:', group);
Hoek.assert(before.indexOf('?') === -1, 'Item cannot come before unassociated items');
Hoek.assert(after.indexOf(group) === -1, 'Item cannot come after itself:', group);
Hoek.assert(after.indexOf('?') === -1, 'Item cannot come after unassociated items');
([].concat(nodes)).forEach((node, i) => {
const item = {
seq: this._items.length,
sort,
before,
after,
group,
node
};
this._items.push(item);
});
// Insert event
const error = this._sort();
Hoek.assert(!error, 'item', (group !== '?' ? 'added into group ' + group : ''), 'created a dependencies error');
return this.nodes;
};
internals.Topo.prototype.merge = function (others) {
others = [].concat(others);
for (let i = 0; i < others.length; ++i) {
const other = others[i];
if (other) {
for (let j = 0; j < other._items.length; ++j) {
const item = Hoek.shallow(other._items[j]);
this._items.push(item);
}
}
}
// Sort items
this._items.sort(internals.mergeSort);
for (let i = 0; i < this._items.length; ++i) {
this._items[i].seq = i;
}
const error = this._sort();
Hoek.assert(!error, 'merge created a dependencies error');
return this.nodes;
};
internals.mergeSort = function (a, b) {
return a.sort === b.sort ? 0 : (a.sort < b.sort ? -1 : 1);
};
internals.Topo.prototype._sort = function () {
// Construct graph
const graph = {};
const graphAfters = Object.create(null); // A prototype can bungle lookups w/ false positives
const groups = Object.create(null);
for (let i = 0; i < this._items.length; ++i) {
const item = this._items[i];
const seq = item.seq; // Unique across all items
const group = item.group;
// Determine Groups
groups[group] = groups[group] || [];
groups[group].push(seq);
// Build intermediary graph using 'before'
graph[seq] = item.before;
// Build second intermediary graph with 'after'
const after = item.after;
for (let j = 0; j < after.length; ++j) {
graphAfters[after[j]] = (graphAfters[after[j]] || []).concat(seq);
}
}
// Expand intermediary graph
let graphNodes = Object.keys(graph);
for (let i = 0; i < graphNodes.length; ++i) {
const node = graphNodes[i];
const expandedGroups = [];
const graphNodeItems = Object.keys(graph[node]);
for (let j = 0; j < graphNodeItems.length; ++j) {
const group = graph[node][graphNodeItems[j]];
groups[group] = groups[group] || [];
for (let k = 0; k < groups[group].length; ++k) {
expandedGroups.push(groups[group][k]);
}
}
graph[node] = expandedGroups;
}
// Merge intermediary graph using graphAfters into final graph
const afterNodes = Object.keys(graphAfters);
for (let i = 0; i < afterNodes.length; ++i) {
const group = afterNodes[i];
if (groups[group]) {
for (let j = 0; j < groups[group].length; ++j) {
const node = groups[group][j];
graph[node] = graph[node].concat(graphAfters[group]);
}
}
}
// Compile ancestors
let children;
const ancestors = {};
graphNodes = Object.keys(graph);
for (let i = 0; i < graphNodes.length; ++i) {
const node = graphNodes[i];
children = graph[node];
for (let j = 0; j < children.length; ++j) {
ancestors[children[j]] = (ancestors[children[j]] || []).concat(node);
}
}
// Topo sort
const visited = {};
const sorted = [];
for (let i = 0; i < this._items.length; ++i) { // Really looping thru item.seq values out of order
let next = i;
if (ancestors[i]) {
next = null;
for (let j = 0; j < this._items.length; ++j) { // As above, these are item.seq values
if (visited[j] === true) {
continue;
}
if (!ancestors[j]) {
ancestors[j] = [];
}
const shouldSeeCount = ancestors[j].length;
let seenCount = 0;
for (let k = 0; k < shouldSeeCount; ++k) {
if (visited[ancestors[j][k]]) {
++seenCount;
}
}
if (seenCount === shouldSeeCount) {
next = j;
break;
}
}
}
if (next !== null) {
visited[next] = true;
sorted.push(next);
}
}
if (sorted.length !== this._items.length) {
return new Error('Invalid dependencies');
}
const seqIndex = {};
for (let i = 0; i < this._items.length; ++i) {
const item = this._items[i];
seqIndex[item.seq] = item;
}
const sortedNodes = [];
this._items = sorted.map((value) => {
const sortedItem = seqIndex[value];
sortedNodes.push(sortedItem.node);
return sortedItem;
});
this.nodes = sortedNodes;
};
{
"_from": "topo@3.x.x",
"_id": "topo@3.0.0",
"_inBundle": false,
"_integrity": "sha512-Tlu1fGlR90iCdIPURqPiufqAlCZYzLjHYVVbcFWDMcX7+tK8hdZWAfsMrD/pBul9jqHHwFjNdf1WaxA9vTRRhw==",
"_location": "/topo",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "topo@3.x.x",
"name": "topo",
"escapedName": "topo",
"rawSpec": "3.x.x",
"saveSpec": null,
"fetchSpec": "3.x.x"
},
"_requiredBy": [
"/joi"
],
"_resolved": "https://registry.npmjs.org/topo/-/topo-3.0.0.tgz",
"_shasum": "37e48c330efeac784538e0acd3e62ca5e231fe7a",
"_spec": "topo@3.x.x",
"_where": "/Users/jeminlee/git-projects/node-practice/express-demo/node_modules/joi",
"bugs": {
"url": "https://github.com/hapijs/topo/issues"
},
"bundleDependencies": false,
"dependencies": {
"hoek": "5.x.x"
},
"deprecated": false,
"description": "Topological sorting with grouping support",
"devDependencies": {
"code": "5.x.x",
"lab": "14.x.x"
},
"engines": {
"node": ">=8.0.0"
},
"homepage": "https://github.com/hapijs/topo#readme",
"keywords": [
"topological",
"sort",
"toposort",
"topsort"
],
"license": "BSD-3-Clause",
"main": "lib/index.js",
"name": "topo",
"repository": {
"type": "git",
"url": "git://github.com/hapijs/topo.git"
},
"scripts": {
"test": "lab -a code -t 100 -L",
"test-cov-html": "lab -a code -t 100 -L -r html -o coverage.html"
},
"version": "3.0.0"
}
......@@ -159,6 +159,11 @@
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
},
"hoek": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/hoek/-/hoek-5.0.3.tgz",
"integrity": "sha512-Bmr56pxML1c9kU+NS51SMFkiVQAb+9uFfXwyqR2tn4w2FPvmPt65eZ9aCcEfRXd9G74HkZnILC6p967pED4aiw=="
},
"http-errors": {
"version": "1.6.2",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz",
......@@ -197,6 +202,24 @@
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.6.0.tgz",
"integrity": "sha1-4/o1e3c9phnybpXwSdBVxyeW+Gs="
},
"isemail": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/isemail/-/isemail-3.1.1.tgz",
"integrity": "sha512-mVjAjvdPkpwXW61agT2E9AkGoegZO7SdJGCezWwxnETL58f5KwJ4vSVAMBUL5idL6rTlYAIGkX3n4suiviMLNw==",
"requires": {
"punycode": "2.1.0"
}
},
"joi": {
"version": "13.1.2",
"resolved": "https://registry.npmjs.org/joi/-/joi-13.1.2.tgz",
"integrity": "sha512-bZZSQYW5lPXenOfENvgCBPb9+H6E6MeNWcMtikI04fKphj5tvFL9TOb+H2apJzbCrRw/jebjTH8z6IHLpBytGg==",
"requires": {
"hoek": "5.0.3",
"isemail": "3.1.1",
"topo": "3.0.0"
}
},
"media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
......@@ -267,6 +290,11 @@
"ipaddr.js": "1.6.0"
}
},
"punycode": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.0.tgz",
"integrity": "sha1-X4Y+3Im5bbCQdLrXlHvwkFbKTn0="
},
"qs": {
"version": "6.5.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz",
......@@ -334,6 +362,14 @@
"resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz",
"integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew=="
},
"topo": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/topo/-/topo-3.0.0.tgz",
"integrity": "sha512-Tlu1fGlR90iCdIPURqPiufqAlCZYzLjHYVVbcFWDMcX7+tK8hdZWAfsMrD/pBul9jqHHwFjNdf1WaxA9vTRRhw==",
"requires": {
"hoek": "5.0.3"
}
},
"type-is": {
"version": "1.6.16",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz",
......
......@@ -10,6 +10,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3"
"express": "^4.16.3",
"joi": "^13.1.2"
}
}
......