Changes of Linux canary v0.0.72

This commit is contained in:
root 2019-03-08 01:15:33 +01:00
parent c93eb51a04
commit b078536372
305 changed files with 31356 additions and 13465 deletions

View File

@ -78,6 +78,7 @@ const requireNative = require('./requireNative');
let coreModule;
function startUpdate() {
console.log('Starting updater.');
const startMinimized = hasArgvFlag('--start-minimized');
appUpdater.update(startMinimized, () => {
@ -102,6 +103,7 @@ function startUpdate() {
}
function startApp() {
console.log('Starting app.');
paths.cleanOldVersions(buildInfo);
const startupMenu = require('./startupMenu');
Menu.setApplicationMenu(startupMenu);
@ -131,7 +133,6 @@ if (preventStartup) {
console.log('Startup prevented.');
// TODO: shouldn't we exit out?
} else {
console.log('Starting updater.');
if (app.isReady()) {
startApp();
} else {

View File

@ -120,6 +120,7 @@ function create(startCallback, newProcessCallback) {
startCallback();
}, () => {
console.log('Another instance exists. Quitting.');
_electron.app.exit(0);
});
}

View File

@ -10,52 +10,46 @@
"topLevelPatterns": [
"devtron@1.4.0",
"mkdirp@^0.5.1",
"request@2.83.0",
"rimraf@^2.5.2",
"yauzl@^2.5.0"
"request@2.88.0",
"rimraf@^2.6.3",
"yauzl@^2.10.0"
],
"lockfileEntries": {
"accessibility-developer-tools@^2.11.0": "https://registry.yarnpkg.com/accessibility-developer-tools/-/accessibility-developer-tools-2.12.0.tgz#3da0cce9d6ec6373964b84f35db7cfc3df7ab514",
"ajv@^5.1.0": "https://registry.yarnpkg.com/ajv/-/ajv-5.5.2.tgz#73b5eeca3fab653e3d3f9422b341ad42205dc965",
"ajv@^6.5.5": "https://registry.yarnpkg.com/ajv/-/ajv-6.8.1.tgz#0890b93742985ebf8973cd365c5b23920ce3cb20",
"asn1@~0.2.3": "https://registry.yarnpkg.com/asn1/-/asn1-0.2.3.tgz#dac8787713c9966849fc8180777ebe9c1ddf3b86",
"assert-plus@1.0.0": "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525",
"assert-plus@^1.0.0": "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525",
"asynckit@^0.4.0": "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79",
"aws-sign2@~0.7.0": "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8",
"aws4@^1.6.0": "https://registry.yarnpkg.com/aws4/-/aws4-1.6.0.tgz#83ef5ca860b2b32e4a0deedee8c771b9db57471e",
"aws4@^1.8.0": "https://registry.yarnpkg.com/aws4/-/aws4-1.8.0.tgz#f0e003d9ca9e7f59c7a508945d7b2ef9a04a542f",
"balanced-match@^1.0.0": "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767",
"bcrypt-pbkdf@^1.0.0": "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz#63bc5dcb61331b92bc05fd528953c33462a06f8d",
"boom@4.x.x": "https://registry.yarnpkg.com/boom/-/boom-4.3.1.tgz#4f8a3005cb4a7e3889f749030fd25b96e01d2e31",
"boom@5.x.x": "https://registry.yarnpkg.com/boom/-/boom-5.2.0.tgz#5dd9da6ee3a5f302077436290cb717d3f4a54e02",
"brace-expansion@^1.1.7": "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.8.tgz#c07b211c7c952ec1f8efd51a77ef0d1d3990a292",
"buffer-crc32@~0.2.3": "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242",
"caseless@~0.12.0": "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc",
"co@^4.6.0": "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184",
"combined-stream@1.0.6": "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818",
"combined-stream@~1.0.5": "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.5.tgz#938370a57b4a51dea2c77c15d5c5fdf895164009",
"combined-stream@^1.0.6": "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.7.tgz#2d1d24317afb8abe95d6d2c0b07b57813539d828",
"combined-stream@~1.0.6": "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.7.tgz#2d1d24317afb8abe95d6d2c0b07b57813539d828",
"concat-map@0.0.1": "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b",
"core-util-is@1.0.2": "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7",
"cryptiles@3.x.x": "https://registry.yarnpkg.com/cryptiles/-/cryptiles-3.1.2.tgz#a89fbb220f5ce25ec56e8c4aa8a4fd7b5b0d29fe",
"dashdash@^1.12.0": "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0",
"delayed-stream@~1.0.0": "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619",
"devtron@1.4.0": "https://registry.yarnpkg.com/devtron/-/devtron-1.4.0.tgz#b5e748bd6e95bbe70bfcc68aae6fe696119441e1",
"ecc-jsbn@~0.1.1": "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505",
"extend@~3.0.1": "https://registry.yarnpkg.com/extend/-/extend-3.0.1.tgz#a755ea7bc1adfcc5a31ce7e762dbaadc5e636444",
"extend@~3.0.2": "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa",
"extsprintf@1.3.0": "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05",
"extsprintf@^1.2.0": "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.0.tgz#e2689f8f356fad62cca65a3a91c5df5f9551692f",
"fast-deep-equal@^1.0.0": "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz#c053477817c86b51daa853c81e059b733d023614",
"fast-deep-equal@^2.0.1": "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz#7b05218ddf9667bf7f370bf7fdb2cb15fdd0aa49",
"fast-json-stable-stringify@^2.0.0": "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz#d5142c0caee6b1189f87d3a76111064f86c8bbf2",
"fd-slicer@~1.0.1": "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.0.1.tgz#8b5bcbd9ec327c5041bf9ab023fd6750f1177e65",
"fd-slicer@~1.1.0": "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e",
"forever-agent@~0.6.1": "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91",
"form-data@~2.3.1": "https://registry.yarnpkg.com/form-data/-/form-data-2.3.2.tgz#4970498be604c20c005d4f5c23aecd21d6b49099",
"form-data@~2.3.2": "https://registry.yarnpkg.com/form-data/-/form-data-2.3.3.tgz#dcce52c05f644f298c6a7ab936bd724ceffbf3a6",
"fs.realpath@^1.0.0": "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f",
"getpass@^0.1.1": "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa",
"glob@^7.0.5": "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15",
"glob@^7.1.3": "https://registry.yarnpkg.com/glob/-/glob-7.1.3.tgz#3960832d3f1574108342dafd3a67b332c0969df1",
"har-schema@^2.0.0": "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92",
"har-validator@~5.0.3": "https://registry.yarnpkg.com/har-validator/-/har-validator-5.0.3.tgz#ba402c266194f15956ef15e0fcf242993f6a7dfd",
"hawk@~6.0.2": "https://registry.yarnpkg.com/hawk/-/hawk-6.0.2.tgz#af4d914eb065f9b5ce4d9d11c1cb2126eecc3038",
"har-validator@~5.1.0": "https://registry.yarnpkg.com/har-validator/-/har-validator-5.1.3.tgz#1ef89ebd3e4996557675eed9893110dc350fa080",
"highlight.js@^9.3.0": "https://registry.yarnpkg.com/highlight.js/-/highlight.js-9.12.0.tgz#e6d9dbe57cbefe60751f02af336195870c90c01e",
"hoek@4.x.x": "https://registry.yarnpkg.com/hoek/-/hoek-4.2.1.tgz#9634502aa12c445dd5a7c5734b572bb8738aacbb",
"http-signature@~1.2.0": "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1",
"humanize-plus@^1.8.1": "https://registry.yarnpkg.com/humanize-plus/-/humanize-plus-1.8.2.tgz#a65b34459ad6367adbb3707a82a3c9f916167030",
"inflight@^1.0.4": "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9",
@ -63,38 +57,40 @@
"is-typedarray@~1.0.0": "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a",
"isstream@~0.1.2": "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a",
"jsbn@~0.1.0": "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513",
"json-schema-traverse@^0.3.0": "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz#349a6d44c53a51de89b40805c5d5e59b417d3340",
"json-schema-traverse@^0.4.1": "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660",
"json-schema@0.2.3": "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13",
"json-stringify-safe@~5.0.1": "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb",
"jsprim@^1.2.2": "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.1.tgz#313e66bc1e5cc06e438bc1b7499c2e5c56acb6a2",
"mime-db@~1.33.0": "https://registry.yarnpkg.com/mime-db/-/mime-db-1.33.0.tgz#a3492050a5cb9b63450541e39d9788d2272783db",
"mime-db@~1.37.0": "https://registry.yarnpkg.com/mime-db/-/mime-db-1.37.0.tgz#0b6a0ce6fdbe9576e25f1f2d2fde8830dc0ad0d8",
"mime-types@^2.1.12": "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.18.tgz#6f323f60a83d11146f831ff11fd66e2fe5503bb8",
"mime-types@~2.1.17": "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.18.tgz#6f323f60a83d11146f831ff11fd66e2fe5503bb8",
"mime-types@~2.1.19": "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.21.tgz#28995aa1ecb770742fe6ae7e58f9181c744b3f96",
"minimatch@^3.0.4": "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083",
"minimist@0.0.8": "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d",
"mkdirp@^0.5.1": "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903",
"oauth-sign@~0.8.2": "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.8.2.tgz#46a6ab7f0aead8deae9ec0565780b7d4efeb9d43",
"oauth-sign@~0.9.0": "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455",
"once@^1.3.0": "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1",
"path-is-absolute@^1.0.0": "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f",
"pend@~1.2.0": "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50",
"performance-now@^2.1.0": "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b",
"psl@^1.1.24": "https://registry.yarnpkg.com/psl/-/psl-1.1.31.tgz#e9aa86d0101b5b105cbe93ac6b784cd547276184",
"punycode@^1.4.1": "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e",
"qs@~6.5.1": "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8",
"request@2.83.0": "https://registry.yarnpkg.com/request/-/request-2.83.0.tgz#ca0b65da02ed62935887808e6f510381034e3356",
"rimraf@^2.5.2": "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36",
"punycode@^2.1.0": "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec",
"qs@~6.5.2": "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36",
"request@2.88.0": "https://registry.yarnpkg.com/request/-/request-2.88.0.tgz#9c2fca4f7d35b592efe57c7f0a55e81052124fef",
"rimraf@^2.6.3": "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab",
"safe-buffer@^5.0.1": "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853",
"safe-buffer@^5.1.1": "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.1.tgz#893312af69b2123def71f57889001671eeb2c853",
"sntp@2.x.x": "https://registry.yarnpkg.com/sntp/-/sntp-2.1.0.tgz#2c6cec14fedc2222739caf9b5c3d85d1cc5a2cc8",
"safe-buffer@^5.1.2": "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d",
"sshpk@^1.7.0": "https://registry.yarnpkg.com/sshpk/-/sshpk-1.13.1.tgz#512df6da6287144316dc4c18fe1cf1d940739be3",
"stringstream@~0.0.5": "https://registry.yarnpkg.com/stringstream/-/stringstream-0.0.5.tgz#4e484cd4de5a0bbbee18e46307710a8a81621878",
"tough-cookie@~2.3.3": "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.4.tgz#ec60cee38ac675063ffc97a5c18970578ee83655",
"tough-cookie@~2.4.3": "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.4.3.tgz#53f36da3f47783b0925afa06ff9f3b165280f781",
"tunnel-agent@^0.6.0": "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd",
"tweetnacl@^0.14.3": "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64",
"tweetnacl@~0.14.0": "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64",
"uuid@^3.1.0": "https://registry.yarnpkg.com/uuid/-/uuid-3.2.1.tgz#12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14",
"uri-js@^4.2.2": "https://registry.yarnpkg.com/uri-js/-/uri-js-4.2.2.tgz#94c540e1ff772956e2299507c010aea6c8838eb0",
"uuid@^3.3.2": "https://registry.yarnpkg.com/uuid/-/uuid-3.3.2.tgz#1b4af4955eb3077c501c23872fc6513811587131",
"verror@1.10.0": "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400",
"wrappy@1": "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f",
"yauzl@^2.5.0": "https://registry.yarnpkg.com/yauzl/-/yauzl-2.9.1.tgz#a81981ea70a57946133883f029c5821a89359a7f"
"yauzl@^2.10.0": "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9"
},
"files": [],
"artifacts": {}

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2015 Evgeny Poberezkin
Copyright (c) 2015-2017 Evgeny Poberezkin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -2,30 +2,35 @@
# Ajv: Another JSON Schema Validator
The fastest JSON Schema validator for Node.js and browser with draft 6 support.
The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07.
[![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv)
[![npm version](https://badge.fury.io/js/ajv.svg)](https://www.npmjs.com/package/ajv)
[![npm@beta](https://img.shields.io/npm/v/ajv/beta.svg)](https://github.com/epoberezkin/ajv/tree/beta)
[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv)
[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
[![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master)
[![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv.svg)](https://greenkeeper.io/)
[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
### _Ajv and [related repositories](#related-packages) will be transfered to [ajv-validator](https://github.com/ajv-validator) org_
__Please note__: Ajv [version 6](https://github.com/epoberezkin/ajv/tree/beta) with [JSON Schema draft-07](http://json-schema.org/work-in-progress) support is released. Use `npm install ajv@beta` to install.
## Using version 6
[JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published.
## Using version 5
[Ajv version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes).
[JSON Schema draft-06](https://trac.tools.ietf.org/html/draft-wright-json-schema-validation-01) is published.
[Ajv version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0) that supports draft-06 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas).
__Please note__: To use Ajv with draft-04 schemas you need to explicitly add meta-schema to the validator instance:
__Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance:
```javascript
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
```
To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId:
```javascript
var ajv = new Ajv({schemaId: 'id'});
// If you want to use both draft-04 and draft-06/07 schemas:
// var ajv = new Ajv({schemaId: 'auto'});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
```
@ -40,6 +45,7 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
- [Command line interface](#command-line-interface)
- Validation
- [Keywords](#validation-keywords)
- [Annotation keywords](#annotation-keywords)
- [Formats](#formats)
- [Combining schemas with $ref](#ref)
- [$data reference](#data-reference)
@ -47,6 +53,7 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
- [Defining custom keywords](#defining-custom-keywords)
- [Asynchronous schema compilation](#asynchronous-schema-compilation)
- [Asynchronous validation](#asynchronous-validation)
- [Security considerations](#security-considerations)
- Modifying data during validation
- [Filtering data](#filtering-data)
- [Assigning defaults](#assigning-defaults)
@ -55,14 +62,15 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
- [Methods](#api)
- [Options](#options)
- [Validation errors](#validation-errors)
- [Plugins](#plugins)
- [Related packages](#related-packages)
- [Packages using Ajv](#some-packages-using-ajv)
- [Some packages using Ajv](#some-packages-using-ajv)
- [Tests, Contributing, History, License](#tests)
## Performance
Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON schemas into super-fast validation functions that are efficient for v8 optimization.
Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.
Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:
@ -79,12 +87,12 @@ Performance of different validators by [json-schema-benchmark](https://github.co
## Features
- Ajv implements full JSON Schema [draft 6](http://json-schema.org/) and draft 4 standards:
- Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards:
- all validation keywords (see [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md))
- full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available)
- support of circular references between schemas
- correct string lengths for strings with unicode pairs (can be turned off)
- [formats](#formats) defined by JSON Schema draft 4 standard and custom formats (can be turned off)
- [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off)
- [validates schemas against meta-schema](#api-validateschema)
- supports [browsers](#using-in-browser) and Node.js 0.10-8.x
- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation
@ -95,9 +103,9 @@ Performance of different validators by [json-schema-benchmark](https://github.co
- [assigning defaults](#assigning-defaults) to missing properties and items
- [coercing data](#coercing-data-types) to the types specified in `type` keywords
- [custom keywords](#defining-custom-keywords)
- draft-6 keywords `const`, `contains` and `propertyNames`
- draft-6 boolean schemas (`true`/`false` as a schema to always pass/fail).
- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON-schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package
- draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else`
- draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail).
- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package
- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords
- [asynchronous validation](#asynchronous-validation) of custom formats and keywords
@ -110,12 +118,6 @@ Currently Ajv is the only validator that passes all the tests from [JSON Schema
npm install ajv
```
or to install [version 6](https://github.com/epoberezkin/ajv/tree/beta):
```
npm install ajv@beta
```
## <a name="usage"></a>Getting started
@ -186,11 +188,11 @@ __Please note__: some frameworks, e.g. Dojo, may redefine global require in such
CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/ajv-cli). It supports:
- compiling JSON-schemas to test their validity
- compiling JSON Schemas to test their validity
- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/epoberezkin/ajv-pack))
- migrate schemas to draft-06 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate))
- validating data file(s) against JSON-schema
- testing expected validity of data against JSON-schema
- migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate))
- validating data file(s) against JSON Schema
- testing expected validity of data against JSON Schema
- referenced schemas
- custom meta-schemas
- files in JSON and JavaScript format
@ -200,7 +202,7 @@ CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/
## Validation keywords
Ajv supports all validation keywords from draft 4 of JSON-schema standard:
Ajv supports all validation keywords from draft-07 of JSON Schema standard:
- [type](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#type)
- [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
@ -208,17 +210,31 @@ Ajv supports all validation keywords from draft 4 of JSON-schema standard:
- [for arrays](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains)
- [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#propertynames)
- [for all types](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#const)
- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf
- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#ifthenelse)
With [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON-schema standard:
With [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard:
- [switch](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#switch-proposed) - conditional validation with a sequence of if/then clauses
- [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match.
- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc.
See [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) for more details.
## Annotation keywords
JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation.
- `title` and `description`: information about the data represented by that schema
- `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options).
- `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults).
- `examples` (NEW in draft-07): an array of data instances. Ajv does not check the validity of these instances against the schema.
- `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.).
- `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64".
- `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png".
__Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance.
## Formats
The following formats are supported for string validation with "format" keyword:
@ -226,9 +242,10 @@ The following formats are supported for string validation with "format" keyword:
- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).
- _time_: time with optional time-zone.
- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)).
- _uri_: full uri with optional protocol.
- _url_: [URL record](https://url.spec.whatwg.org/#concept-url).
- _uri_: full URI.
- _uri-reference_: URI reference, including full and relative URIs.
- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570)
- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url).
- _email_: email address.
- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5).
- _ipv4_: IP address v4.
@ -238,7 +255,9 @@ The following formats are supported for string validation with "format" keyword:
- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901).
- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00).
There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `email`, and `hostname`. See [Options](#options) for details.
__Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here.
There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, `email`, and `hostname`. See [Options](#options) for details.
You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method.
@ -353,7 +372,7 @@ var validData = {
## $merge and $patch keywords
With the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON-schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902).
With the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902).
To add keywords `$merge` and `$patch` to Ajv instance use this code:
@ -427,7 +446,7 @@ The advantages of using custom keywords are:
If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result).
The concerns you have to be aware of when extending JSON-schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas.
The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas.
You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords.
@ -501,39 +520,20 @@ If your schema uses asynchronous formats/keywords or refers to some schema that
__Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail.
Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to either [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent) or with [regenerator](https://github.com/facebook/regenerator) or to [generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) that can be optionally transpiled with regenerator as well. You can also supply any other transpiler as a function. See [Options](#options).
Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function).
Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options).
The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas.
If you are using generators, the compiled validation function can be either wrapped with [co](https://github.com/tj/co) (default) or returned as generator function, that can be used directly, e.g. in [koa](http://koajs.com/) 1.0. `co` is a small library, it is included in Ajv (both as npm dependency and in the browser bundle).
Async functions are currently supported in Chrome 55, Firefox 52, Node.js 7 (with --harmony-async-await) and MS Edge 13 (with flag).
Generator functions are currently supported in Chrome, Firefox and Node.js.
If you are using Ajv in other browsers or in older versions of Node.js you should use one of available transpiling options. All provided async modes use global Promise class. If your platform does not have Promise you should use a polyfill that defines it.
Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property.
Example:
```javascript
/**
* Default mode is non-transpiled generator function wrapped with `co`.
* Using package ajv-async (https://github.com/epoberezkin/ajv-async)
* you can auto-detect the best async mode.
* In this case, without "async" and "transpile" options
* (or with option {async: true})
* Ajv will choose the first supported/installed option in this order:
* 1. native async function
* 2. native generator function wrapped with co
* 3. es7 async functions transpiled with nodent
* 4. es7 async functions transpiled with regenerator
*/
var setupAsync = require('ajv-async');
var ajv = setupAsync(new Ajv);
var ajv = new Ajv;
// require('ajv-async')(ajv);
ajv.addKeyword('idExists', {
async: true,
@ -580,41 +580,25 @@ validate({ userId: 1, postId: 19 })
### Using transpilers with asynchronous validation functions.
To use a transpiler you should separately install it (or load its bundle in the browser).
Ajv npm package includes minified browser bundles of regenerator and nodent in dist folder.
[ajv-async](https://github.com/epoberezkin/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser).
#### Using nodent
```javascript
var setupAsync = require('ajv-async');
var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' });
setupAsync(ajv);
var ajv = new Ajv;
require('ajv-async')(ajv);
// in the browser if you want to load ajv-async bundle separately you can:
// window.ajvAsync(ajv);
var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc);
```
`npm install nodent` or use `nodent.min.js` from dist folder of npm package.
#### Using regenerator
```javascript
var setupAsync = require('ajv-async');
var ajv = new Ajv({ /* async: 'es7', */ transpile: 'regenerator' });
setupAsync(ajv);
var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc);
```
`npm install regenerator` or use `regenerator.min.js` from dist folder of npm package.
#### Using other transpilers
```javascript
var ajv = new Ajv({ async: 'es7', processCode: transpileFunc });
var ajv = new Ajv({ processCode: transpileFunc });
var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc);
```
@ -622,24 +606,55 @@ validate(data).then(successFunc).catch(errorFunc);
See [Options](#options).
#### Comparison of async modes
## Security considerations
|mode|transpile<br>speed*|run-time<br>speed*|bundle<br>size|
|---|:-:|:-:|:-:|
|es7 async<br>(native)|-|0.75|-|
|generators<br>(native)|-|1.0|-|
|es7.nodent|1.35|1.1|215Kb|
|es7.regenerator|1.0|2.7|1109Kb|
|regenerator|1.0|3.2|1109Kb|
JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider.
\* Relative performance in Node.js 7.x — smaller is better.
[nodent](https://github.com/MatAtBread/nodent) has several advantages:
##### Untrusted schemas
- much smaller browser bundle than regenerator
- almost the same performance of generated code as native generators in Node.js and the latest Chrome
- much better performance than native generators in other browsers
- works in IE 9 (regenerator does not)
Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application.
If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent:
- compiling schemas can cause stack overflow (if they are too deep)
- compiling schemas can be slow (e.g. [#557](https://github.com/epoberezkin/ajv/issues/557))
- validating certain data can be slow
It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords.
Regardless the measures you take, using untrusted schemas increases security risks.
##### Circular references in JavaScript objects
Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/epoberezkin/ajv/issues/802).
An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references.
##### Security risks of trusted schemas
Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to):
- `pattern` and `format` for large strings - use `maxLength` to mitigate
- `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate
- `patternProperties` for large property names - use `propertyNames` to mitigate
__Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors).
You can validate your JSON schemas against [this meta-schema](https://github.com/epoberezkin/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed:
```javascript
const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json'));
const schema1 = {format: 'email'};
isSchemaSecure(schema1); // false
const schema2 = {format: 'email', maxLength: 256};
isSchemaSecure(schema2); // true
```
__Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results.
## Filtering data
@ -736,13 +751,11 @@ The schema above is also more efficient - it will compile into a faster function
With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items.
With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults.
This option modifies original data.
__Please note__: by default the default value is inserted in the generated validation code as a literal (starting from v4.0), so the value inserted in the data will be the deep clone of the default in the schema.
If you need to insert the default value in the data by reference pass the option `useDefaults: "shared"`.
Inserting defaults by reference can be faster (in case you have an object in `default`) and it allows to have dynamic values in defaults, e.g. timestamp, without recompiling the schema. The side effect is that modifying the default value in any validated data instance will change the default in the schema and in other validated data instances. See example 3 below.
__Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema.
Example 1 (`default` in `properties`):
@ -785,32 +798,6 @@ console.log(validate(data)); // true
console.log(data); // [ 1, "foo" ]
```
Example 3 (inserting "defaults" by reference):
```javascript
var ajv = new Ajv({ useDefaults: 'shared' });
var schema = {
properties: {
foo: {
default: { bar: 1 }
}
}
}
var validate = ajv.compile(schema);
var data = {};
console.log(validate(data)); // true
console.log(data); // { foo: { bar: 1 } }
data.foo.bar = 2;
var data2 = {};
console.log(validate(data2)); // true
console.log(data2); // { foo: { bar: 2 } }
```
`default` keywords in other cases are ignored:
- not in `properties` or `items` subschemas
@ -884,9 +871,9 @@ Create Ajv instance.
Generate validating function and cache the compiled schema for future use.
Validating function returns boolean and has properties `errors` with the errors from the last validation (`null` if there were no errors) and `schema` with the reference to the original schema.
Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema.
Unless the option `validateSchema` is false, the schema will be validated against meta-schema and if schema is invalid the error will be thrown. See [options](#options).
The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options).
##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise
@ -937,13 +924,13 @@ This allows you to do nice things like the following.
```javascript
var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri);
```
```
##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv
Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option).
There is no need to explicitly add draft 6 meta schema (http://json-schema.org/draft-06/schema and http://json-schema.org/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`.
There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`.
##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean
@ -999,14 +986,14 @@ Custom formats can be also added via `formats` option.
Add custom validation keyword to Ajv instance.
Keyword should be different from all standard JSON schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance.
Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance.
Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`.
It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions.
Example Keywords:
- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions.
- `"example"`: valid, but not recommended as it could collide with future versions of JSON schema etc.
- `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc.
- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword
Keyword definition is an object with the following properties:
@ -1062,16 +1049,18 @@ Defaults:
$data: false,
allErrors: false,
verbose: false,
$comment: false, // NEW in Ajv version 6.0
jsonPointers: false,
uniqueItems: true,
unicode: true,
nullable: false,
format: 'fast',
formats: {},
unknownFormats: true,
schemas: {},
logger: undefined,
// referenced schema options:
schemaId: undefined // recommended '$id'
schemaId: '$id',
missingRefs: true,
extendRefs: 'ignore', // recommended 'fail'
loadSchema: undefined, // function(uri: string): Promise {}
@ -1080,7 +1069,6 @@ Defaults:
useDefaults: false,
coerceTypes: false,
// asynchronous validation options:
async: 'co*',
transpile: undefined, // requires ajv-async package
// advanced options:
meta: true,
@ -1091,7 +1079,7 @@ Defaults:
loopRequired: Infinity,
ownProperties: false,
multipleOfPrecision: false,
errorDataPath: 'object',
errorDataPath: 'object', // deprecated
messages: true,
sourceCode: false,
processCode: undefined, // function (str: string): string {}
@ -1105,15 +1093,20 @@ Defaults:
- _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api).
- _allErrors_: check all rules collecting all errors. Default is to return after the first error.
- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default).
- _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values:
- `false` (default): ignore $comment keyword.
- `true`: log the keyword value to console.
- function: pass the keyword value, its schema path and root schema to the specified function
- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation.
- _uniqueItems_: validate `uniqueItems` keyword (true by default).
- _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters.
- _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/).
- _format_: formats validation mode ('fast' by default). Pass 'full' for more correct and slow validation or `false` not to validate formats at all. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode.
- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
- _unknownFormats_: handling of unknown formats. Option values:
- `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail.
- `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail.
- `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON-schema specification.
- `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification.
- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object.
- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. Option values:
- custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown.
@ -1123,9 +1116,9 @@ Defaults:
##### Referenced schema options
- _schemaId_: this option defines which keywords are used as schema URI. Option value:
- `"$id"` (recommended) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06), ignore `id` keyword (if it is present a warning will be logged).
- `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged).
- `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged).
- `undefined` (default) - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation.
- `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation.
- _missingRefs_: handling of missing referenced schemas. Option values:
- `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted).
- `"ignore"` - to log error during compilation and always pass validation.
@ -1144,10 +1137,11 @@ Defaults:
- `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them).
- `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed.
- `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema).
- _useDefaults_: replace missing properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values:
- _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values:
- `false` (default) - do not use defaults
- `true` - insert defaults by value (safer and slower, object literal is used).
- `"shared"` - insert defaults by reference (faster). If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well.
- `true` - insert defaults by value (object literal is used).
- `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string).
- `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well.
- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md). Option values:
- `false` (default) - no type coercion.
- `true` - coerce scalar data types.
@ -1156,30 +1150,16 @@ Defaults:
##### Asynchronous validation options
- _async_: determines how Ajv compiles asynchronous schemas (see [Asynchronous validation](#asynchronous-validation)) to functions. Option values:
- `"*"` / `"co*"` (default) - compile to generator function ("co*" - wrapped with `co.wrap`). If generators are not supported and you don't provide `processCode` option (or `transpile` option if you use [ajv-async](https://github.com/epoberezkin/ajv-async) package), the exception will be thrown when async schema is compiled.
- `"es7"` - compile to es7 async function. Unless your platform supports them you need to provide `processCode` or `transpile` option. According to [compatibility table](http://kangax.github.io/compat-table/es7/)) async functions are supported by:
- Firefox 52,
- Chrome 55,
- Node.js 7 (with `--harmony-async-await`),
- MS Edge 13 (with flag).
- `undefined`/`true` - auto-detect async mode. It requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. If `transpile` option is not passed, ajv-async will choose the first of supported/installed async/transpile modes in this order:
- "es7" (native async functions),
- "co*" (native generators with co.wrap),
- "es7"/"nodent",
- "co*"/"regenerator" during the creation of the Ajv instance.
If none of the options is available the exception will be thrown.
- _transpile_: Requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values:
- `"nodent"` - transpile with [nodent](https://github.com/MatAtBread/nodent). If nodent is not installed, the exception will be thrown. nodent can only transpile es7 async functions; it will enforce this mode.
- `"regenerator"` - transpile with [regenerator](https://github.com/facebook/regenerator). If regenerator is not installed, the exception will be thrown.
- a function - this function should accept the code of validation function as a string and return transpiled code. This option allows you to use any other transpiler you prefer. If you are passing a function, you can simply pass it to `processCode` option without using ajv-async.
- `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported.
- `true` - always transpile with nodent.
- `false` - do not transpile; if async functions are not supported an exception will be thrown.
##### Advanced options
- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword.
- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can either be http://json-schema.org/schema or http://json-schema.org/draft-04/schema or absent (draft-4 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values:
- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values:
- `true` (default) - if the validation fails, throw the exception.
- `"log"` - if the validation fails, log error.
- `false` - skip schema validation.
@ -1192,7 +1172,7 @@ Defaults:
- _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance.
- _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst.
- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/epoberezkin/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations).
- _errorDataPath_: set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`.
- _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`.
- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n)).
- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call).
- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options:
@ -1247,20 +1227,34 @@ Properties of `params` object in errors depend on the keyword that failed valida
- `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property).
- `type` - property `type` (required type(s), a string, can be a comma-separated list)
- `uniqueItems` - properties `i` and `j` (indices of duplicate items).
- `const` - property `allowedValue` pointing to the value (the schema of the keyword).
- `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword).
- `$ref` - property `ref` with the referenced schema URI.
- `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes).
- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name).
## Plugins
Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions:
- it exports a function
- this function accepts ajv instance as the first parameter and returns the same instance to allow chaining
- this function can accept an optional configuration as the second parameter
If you have published a useful plugin please submit a PR to add it to the next section.
## Related packages
- [ajv-async](https://github.com/epoberezkin/ajv-async) - configure async validation mode
- [ajv-async](https://github.com/epoberezkin/ajv-async) - plugin to configure async validation mode
- [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats
- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface
- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - custom error messages
- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - plugin for custom error messages
- [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages
- [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - instrument generated validation code to measure test coverage of your schemas
- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - custom validation keywords (if/then/else, select, typeof, etc.)
- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - keywords $merge and $patch
- [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas
- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.)
- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - plugin with keywords $merge and $patch
- [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions
@ -1271,7 +1265,7 @@ Properties of `params` object in errors depend on the keyword that failed valida
- [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition
- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator
- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org
- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON-schema http://jsonschemalint.com
- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com
- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js
- [table](https://github.com/gajus/table) - formats data into a string table
- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser
@ -1280,12 +1274,13 @@ Properties of `params` object in errors depend on the keyword that failed valida
- [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation
- [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages
- [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema
- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON-schema with expect in mocha tests
- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests
- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema
- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file
- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app
- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter
- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages
- [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX
## Tests
@ -1311,15 +1306,15 @@ Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/mas
See https://github.com/epoberezkin/ajv/releases
__Please note__: [Changes in version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0).
__Please note__: [Changes in version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0).
[Changes in version 4.6.0](https://github.com/epoberezkin/ajv/releases/tag/4.6.0).
[Version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0).
[Changes in version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0).
[Version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0).
[Changes in version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0).
[Version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0).
[Changes in version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0).
[Version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0).
## License

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

BIN
appasar/canary/node_modules/ajv/lib/.DS_Store generated vendored Normal file

Binary file not shown.

View File

@ -1,12 +1,36 @@
declare var ajv: {
declare var ajv: {
(options?: ajv.Options): ajv.Ajv;
new (options?: ajv.Options): ajv.Ajv;
ValidationError: ValidationError;
MissingRefError: MissingRefError;
new(options?: ajv.Options): ajv.Ajv;
ValidationError: typeof AjvErrors.ValidationError;
MissingRefError: typeof AjvErrors.MissingRefError;
$dataMetaSchema: object;
}
declare namespace AjvErrors {
class ValidationError extends Error {
constructor(errors: Array<ajv.ErrorObject>);
message: string;
errors: Array<ajv.ErrorObject>;
ajv: true;
validation: true;
}
class MissingRefError extends Error {
constructor(baseId: string, ref: string, message?: string);
static message: (baseId: string, ref: string) => string;
message: string;
missingRef: string;
missingSchema: string;
}
}
declare namespace ajv {
type ValidationError = AjvErrors.ValidationError;
type MissingRefError = AjvErrors.MissingRefError;
interface Ajv {
/**
* Validate data using schema
@ -15,7 +39,7 @@ declare namespace ajv {
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
validate(schemaKeyRef: object | string | boolean, data: any): boolean | Thenable<any>;
validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike<any>;
/**
* Create validating function for passed schema.
* @param {object|Boolean} schema schema object
@ -29,9 +53,9 @@ declare namespace ajv {
* @param {object|Boolean} schema schema object
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
* @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function.
* @return {Thenable<ValidateFunction>} validating function
* @return {PromiseLike<ValidateFunction>} validating function
*/
compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): Thenable<ValidateFunction>;
compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike<ValidateFunction>;
/**
* Adds schema to the instance.
* @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
@ -103,12 +127,14 @@ declare namespace ajv {
* @param {object} options optional options with properties `separator` and `dataVar`.
* @return {string} human readable string with all errors descriptions
*/
errorsText(errors?: Array<ErrorObject>, options?: ErrorsTextOptions): string;
errors?: Array<ErrorObject>;
errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string;
errors?: Array<ErrorObject> | null;
}
interface Thenable <R> {
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
interface CustomLogger {
log(...args: any[]): any;
warn(...args: any[]): any;
error(...args: any[]): any;
}
interface ValidateFunction {
@ -118,7 +144,7 @@ declare namespace ajv {
parentData?: object | Array<any>,
parentDataProperty?: string | number,
rootData?: object | Array<any>
): boolean | Thenable<any>;
): boolean | PromiseLike<any>;
schema?: object | boolean;
errors?: null | Array<ErrorObject>;
refs?: object;
@ -139,10 +165,10 @@ declare namespace ajv {
formats?: object;
unknownFormats?: true | string[] | 'ignore';
schemas?: Array<object> | object;
schemaId?: '$id' | 'id';
schemaId?: '$id' | 'id' | 'auto';
missingRefs?: true | 'ignore' | 'fail';
extendRefs?: true | 'ignore' | 'fail';
loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => Thenable<object | boolean>;
loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike<object | boolean>;
removeAdditional?: boolean | 'all' | 'failing';
useDefaults?: boolean | 'shared';
coerceTypes?: boolean | 'array';
@ -161,16 +187,30 @@ declare namespace ajv {
sourceCode?: boolean;
processCode?: (code: string) => string;
cache?: object;
logger?: CustomLogger | false;
nullable?: boolean;
serialize?: ((schema: object | boolean) => any) | false;
}
type FormatValidator = string | RegExp | ((data: string) => boolean | Thenable<any>);
type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike<any>);
type NumberFormatValidator = ((data: number) => boolean | PromiseLike<any>);
interface FormatDefinition {
validate: FormatValidator;
compare: (data1: string, data2: string) => number;
interface NumberFormatDefinition {
type: "number",
validate: NumberFormatValidator;
compare?: (data1: number, data2: number) => number;
async?: boolean;
}
interface StringFormatDefinition {
type?: "string",
validate: FormatValidator;
compare?: (data1: string, data2: string) => number;
async?: boolean;
}
type FormatDefinition = NumberFormatDefinition | StringFormatDefinition;
interface KeywordDefinition {
type?: string | Array<string>;
async?: boolean;
@ -227,7 +267,7 @@ declare namespace ajv {
parentData?: object | Array<any>,
parentDataProperty?: string | number,
rootData?: object | Array<any>
): boolean | Thenable<any>;
): boolean | PromiseLike<any>;
errors?: Array<ErrorObject>;
}
@ -252,11 +292,11 @@ declare namespace ajv {
}
type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams |
DependenciesParams | FormatParams | ComparisonParams |
MultipleOfParams | PatternParams | RequiredParams |
TypeParams | UniqueItemsParams | CustomParams |
PatternGroupsParams | PatternRequiredParams |
PropertyNamesParams | SwitchParams | NoParams | EnumParams;
DependenciesParams | FormatParams | ComparisonParams |
MultipleOfParams | PatternParams | RequiredParams |
TypeParams | UniqueItemsParams | CustomParams |
PatternRequiredParams | PropertyNamesParams |
IfParams | SwitchParams | NoParams | EnumParams;
interface RefParams {
ref: string;
@ -312,12 +352,6 @@ declare namespace ajv {
keyword: string;
}
interface PatternGroupsParams {
reason: string;
limit: number;
pattern: string;
}
interface PatternRequiredParams {
missingPattern: string;
}
@ -326,33 +360,19 @@ declare namespace ajv {
propertyName: string;
}
interface IfParams {
failingKeyword: string;
}
interface SwitchParams {
caseIndex: number;
}
interface NoParams {}
interface NoParams { }
interface EnumParams {
allowedValues: Array<any>;
}
}
declare class ValidationError extends Error {
constructor(errors: Array<ajv.ErrorObject>);
message: string;
errors: Array<ajv.ErrorObject>;
ajv: true;
validation: true;
}
declare class MissingRefError extends Error {
constructor(baseId: string, ref: string, message?: string);
static message: (baseId: string, ref: string) => string;
message: string;
missingRef: string;
missingSchema: string;
}
export = ajv;

View File

@ -7,10 +7,8 @@ var compileSchema = require('./compile')
, stableStringify = require('fast-json-stable-stringify')
, formats = require('./compile/formats')
, rules = require('./compile/rules')
, $dataMetaSchema = require('./$data')
, patternGroups = require('./patternGroups')
, util = require('./compile/util')
, co = require('co');
, $dataMetaSchema = require('./data')
, util = require('./compile/util');
module.exports = Ajv;
@ -38,7 +36,7 @@ Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;
var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema';
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ];
var META_SUPPORT_DATA = ['/properties'];
@ -57,8 +55,6 @@ function Ajv(opts) {
this._refs = {};
this._fragments = {};
this._formats = formats(opts.format);
var schemaUriFormat = this._schemaUriFormat = this._formats['uri-reference'];
this._schemaUriFormatFunc = function (str) { return schemaUriFormat.test(str); };
this._cache = opts.cache || new Cache;
this._loadingSchemas = {};
@ -72,10 +68,10 @@ function Ajv(opts) {
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
addDraft6MetaSchema(this);
addDefaultMetaSchema(this);
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {const: true}});
addInitialSchemas(this);
if (opts.patternGroups) patternGroups(this);
}
@ -99,9 +95,7 @@ function validate(schemaKeyRef, data) {
}
var valid = v(data);
if (v.$async === true)
return this._opts.async == '*' ? co(valid) : valid;
this.errors = v.errors;
if (v.$async !== true) this.errors = v.errors;
return valid;
}
@ -175,13 +169,7 @@ function validateSchema(schema, throwOrLogError) {
this.errors = null;
return true;
}
var currentUriFormat = this._formats.uri;
this._formats.uri = typeof currentUriFormat == 'function'
? this._schemaUriFormatFunc
: this._schemaUriFormat;
var valid;
try { valid = this.validate($schema, schema); }
finally { this._formats.uri = currentUriFormat; }
var valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
var message = 'schema is invalid: ' + this.errorsText();
if (this._opts.validateSchema == 'log') this.logger.error(message);
@ -356,6 +344,10 @@ function _compile(schemaObj, root) {
var v;
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
catch(e) {
delete schemaObj.validate;
throw e;
}
finally {
schemaObj.compiling = false;
if (schemaObj.meta) this._opts = currentOpts;
@ -368,9 +360,11 @@ function _compile(schemaObj, root) {
return v;
/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var _validate = schemaObj.validate;
var result = _validate.apply(null, arguments);
var result = _validate.apply(this, arguments);
callValidate.errors = _validate.errors;
return result;
}
@ -379,9 +373,9 @@ function _compile(schemaObj, root) {
function chooseGetId(opts) {
switch (opts.schemaId) {
case '$id': return _get$Id;
case 'auto': return _get$IdOrId;
case 'id': return _getId;
default: return _get$IdOrId;
default: return _get$Id;
}
}
@ -442,14 +436,14 @@ function addFormat(name, format) {
}
function addDraft6MetaSchema(self) {
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = require('./refs/$data.json');
$dataSchema = require('./refs/data.json');
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
}
if (self._opts.meta === false) return;
var metaSchema = require('./refs/json-schema-draft-06.json');
var metaSchema = require('./refs/json-schema-draft-07.json');
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;

View File

@ -1,31 +0,0 @@
'use strict';
//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
'$ref': require('../dotjs/ref'),
allOf: require('../dotjs/allOf'),
anyOf: require('../dotjs/anyOf'),
const: require('../dotjs/const'),
contains: require('../dotjs/contains'),
dependencies: require('../dotjs/dependencies'),
'enum': require('../dotjs/enum'),
format: require('../dotjs/format'),
items: require('../dotjs/items'),
maximum: require('../dotjs/_limit'),
minimum: require('../dotjs/_limit'),
maxItems: require('../dotjs/_limitItems'),
minItems: require('../dotjs/_limitItems'),
maxLength: require('../dotjs/_limitLength'),
minLength: require('../dotjs/_limitLength'),
maxProperties: require('../dotjs/_limitProperties'),
minProperties: require('../dotjs/_limitProperties'),
multipleOf: require('../dotjs/multipleOf'),
not: require('../dotjs/not'),
oneOf: require('../dotjs/oneOf'),
pattern: require('../dotjs/pattern'),
properties: require('../dotjs/properties'),
propertyNames: require('../dotjs/propertyNames'),
required: require('../dotjs/required'),
uniqueItems: require('../dotjs/uniqueItems'),
validate: require('../dotjs/validate')
};

View File

@ -1,3 +1,5 @@
'use strict';
// do NOT remove this file - it would break pre-compiled schemas
// https://github.com/epoberezkin/ajv/issues/889
module.exports = require('fast-deep-equal');

View File

@ -2,8 +2,8 @@
var util = require('./util');
var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/;
var DAYS = [0,31,29,31,30,31,30,31,31,30,31,30,31];
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
@ -16,7 +16,8 @@ var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$|^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
@ -32,11 +33,11 @@ formats.fast = {
// date: http://tools.ietf.org/html/rfc3339#section-5.6
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6
time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
uri: /^(?:[a-z][a-z0-9+-.]*)(?::|\/)\/?[^\s]*$/i,
'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i,
uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i,
'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
'uri-template': URITEMPLATE,
url: URL,
// email (sources from jsen validator):
@ -54,6 +55,7 @@ formats.fast = {
// JSON-pointer: https://tools.ietf.org/html/rfc6901
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
'json-pointer': JSON_POINTER,
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
'relative-json-pointer': RELATIVE_JSON_POINTER
};
@ -67,25 +69,35 @@ formats.full = {
'uri-reference': URIREF,
'uri-template': URITEMPLATE,
url: URL,
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
hostname: hostname,
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
regex: regex,
uuid: UUID,
'json-pointer': JSON_POINTER,
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
'relative-json-pointer': RELATIVE_JSON_POINTER
};
function isLeapYear(year) {
// https://tools.ietf.org/html/rfc3339#appendix-C
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function date(str) {
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6
var matches = str.match(DATE);
if (!matches) return false;
var month = +matches[1];
var day = +matches[2];
return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month];
var year = +matches[1];
var month = +matches[2];
var day = +matches[3];
return month >= 1 && month <= 12 && day >= 1 &&
day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
}
@ -97,7 +109,9 @@ function time(str, full) {
var minute = matches[2];
var second = matches[3];
var timeZone = matches[5];
return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone);
return ((hour <= 23 && minute <= 59 && second <= 59) ||
(hour == 23 && minute == 59 && second == 60)) &&
(!full || timeZone);
}

View File

@ -11,7 +11,6 @@ var validateGenerator = require('../dotjs/validate');
* Functions below are used inside compiled validations function
*/
var co = require('co');
var ucs2length = util.ucs2length;
var equal = require('fast-deep-equal');
@ -70,9 +69,11 @@ function compile(schema, root, localRefs, baseId) {
endCompiling.call(this, schema, root, baseId);
}
/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var validate = compilation.validate;
var result = validate.apply(null, arguments);
var result = validate.apply(this, arguments);
callValidate.errors = validate.errors;
return result;
}
@ -124,7 +125,6 @@ function compile(schema, root, localRefs, baseId) {
'refVal',
'defaults',
'customRules',
'co',
'equal',
'ucs2length',
'ValidationError',
@ -139,7 +139,6 @@ function compile(schema, root, localRefs, baseId) {
refVal,
defaults,
customRules,
co,
equal,
ucs2length,
ValidationError
@ -224,7 +223,7 @@ function compile(schema, root, localRefs, baseId) {
function resolvedRef(refVal, code) {
return typeof refVal == 'object' || typeof refVal == 'boolean'
? { code: code, schema: refVal, inline: true }
: { code: code, $async: refVal && refVal.$async };
: { code: code, $async: refVal && !!refVal.$async };
}
function usePattern(regexStr) {

View File

@ -1,6 +1,6 @@
'use strict';
var url = require('url')
var URI = require('uri-js')
, equal = require('fast-deep-equal')
, util = require('./util')
, SchemaObject = require('./schema_obj')
@ -67,10 +67,10 @@ function resolve(compile, root, ref) {
*/
function resolveSchema(root, ref) {
/* jshint validthis: true */
var p = url.parse(ref, false, true)
var p = URI.parse(ref)
, refPath = _getFullPath(p)
, baseId = getFullPath(this._getId(root.schema));
if (refPath !== baseId) {
if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
var id = normalizeId(refPath);
var refVal = this._refs[id];
if (typeof refVal == 'string') {
@ -115,9 +115,9 @@ var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
/* jshint validthis: true */
parsedRef.hash = parsedRef.hash || '';
if (parsedRef.hash.slice(0,2) != '#/') return;
var parts = parsedRef.hash.split('/');
parsedRef.fragment = parsedRef.fragment || '';
if (parsedRef.fragment.slice(0,1) != '/') return;
var parts = parsedRef.fragment.split('/');
for (var i = 1; i < parts.length; i++) {
var part = parts[i];
@ -206,14 +206,13 @@ function countKeys(schema) {
function getFullPath(id, normalize) {
if (normalize !== false) id = normalizeId(id);
var p = url.parse(id, false, true);
var p = URI.parse(id);
return _getFullPath(p);
}
function _getFullPath(p) {
var protocolSeparator = p.protocol || p.href.slice(0,2) == '//' ? '//' : '';
return (p.protocol||'') + protocolSeparator + (p.host||'') + (p.path||'') + '#';
return URI.serialize(p).split('#')[0] + '#';
}
@ -225,7 +224,7 @@ function normalizeId(id) {
function resolveUrl(baseId, id) {
id = normalizeId(id);
return url.resolve(baseId, id);
return URI.resolve(baseId, id);
}
@ -246,7 +245,7 @@ function resolveIds(schema) {
fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
if (typeof id == 'string') {
id = baseId = normalizeId(baseId ? url.resolve(baseId, id) : id);
id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
var refVal = self._refs[id];
if (typeof refVal == 'string') refVal = self._refs[refVal];

View File

@ -1,6 +1,6 @@
'use strict';
var ruleModules = require('./_rules')
var ruleModules = require('../dotjs')
, toHash = require('./util').toHash;
module.exports = function rules() {
@ -11,17 +11,20 @@ module.exports = function rules() {
{ type: 'string',
rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
{ type: 'array',
rules: [ 'maxItems', 'minItems', 'uniqueItems', 'contains', 'items' ] },
rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
{ type: 'object',
rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
{ 'properties': ['additionalProperties', 'patternProperties'] } ] },
{ rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] }
{ rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
];
var ALL = [ 'type' ];
var ALL = [ 'type', '$comment' ];
var KEYWORDS = [
'additionalItems', '$schema', '$id', 'id', 'title',
'description', 'default', 'definitions'
'$schema', '$id', 'id', '$data', 'title',
'description', 'default', 'definitions',
'examples', 'readOnly', 'writeOnly',
'contentMediaType', 'contentEncoding',
'additionalItems', 'then', 'else'
];
var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
RULES.all = toHash(ALL);
@ -48,6 +51,11 @@ module.exports = function rules() {
return rule;
});
RULES.all.$comment = {
keyword: '$comment',
code: ruleModules.$comment
};
if (group.type) RULES.types[group.type] = group;
});

View File

@ -38,7 +38,7 @@ module.exports = function (metaSchema, keywordsJsonPointers) {
keywords[key] = {
anyOf: [
schema,
{ $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }
{ $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
]
};
}

View File

@ -50,6 +50,14 @@
)
|| {{=$data}} !== {{=$data}}) {
var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}=';
{{
if ($schema === undefined) {
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaValueExcl;
$isData = $isDataExcl;
}
}}
{{??}}
{{
var $exclIsNumber = typeof $schemaExcl == 'number'

9
appasar/canary/node_modules/ajv/lib/dot/comment.jst generated vendored Normal file
View File

@ -0,0 +1,9 @@
{{# def.definitions }}
{{# def.setupKeyword }}
{{ var $comment = it.util.toQuotedString($schema); }}
{{? it.opts.$comment === true }}
console.log({{=$comment}});
{{?? typeof it.opts.$comment == 'function' }}
self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema);
{{?}}

View File

@ -112,13 +112,13 @@ var {{=$valid}};
{{# def.storeDefOut:def_callRuleValidate }}
{{? $rDef.errors === false }}
{{=$valid}} = {{? $asyncKeyword }}{{=it.yieldAwait}}{{?}}{{= def_callRuleValidate }};
{{=$valid}} = {{? $asyncKeyword }}await {{?}}{{= def_callRuleValidate }};
{{??}}
{{? $asyncKeyword }}
{{ $ruleErrs = 'customErrors' + $lvl; }}
var {{=$ruleErrs}} = null;
try {
{{=$valid}} = {{=it.yieldAwait}}{{= def_callRuleValidate }};
{{=$valid}} = await {{= def_callRuleValidate }};
} catch (e) {
{{=$valid}} = false;
if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors;

View File

@ -1,5 +1,10 @@
{{## def.assignDefault:
if ({{=$passData}} === undefined)
if ({{=$passData}} === undefined
{{? it.opts.useDefaults == 'empty' }}
|| {{=$passData}} === null
|| {{=$passData}} === ''
{{?}}
)
{{=$passData}} = {{? it.opts.useDefaults == 'shared' }}
{{= it.useDefault($sch.default) }}
{{??}}

View File

@ -94,23 +94,23 @@
'false schema': "'boolean schema is false'",
$ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'",
additionalItems: "'should NOT have more than {{=$schema.length}} items'",
additionalProperties: "'should NOT have additional properties'",
additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'",
anyOf: "'should match some schema in anyOf'",
const: "'should be equal to constant'",
contains: "'should contain a valid item'",
dependencies: "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'",
'enum': "'should be equal to one of the allowed values'",
format: "'should match format \"{{#def.concatSchemaEQ}}\"'",
'if': "'should match \"' + {{=$ifClause}} + '\" schema'",
_limit: "'should be {{=$opStr}} {{#def.appendSchema}}",
_exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'",
_limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}less{{?}} than {{#def.concatSchema}} items'",
_limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'",
_limitLength: "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'",
_limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}less{{?}} than {{#def.concatSchema}} properties'",
_limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'",
multipleOf: "'should be multiple of {{#def.appendSchema}}",
not: "'should NOT be valid'",
oneOf: "'should match exactly one schema in oneOf'",
pattern: "'should match pattern \"{{#def.concatSchemaEQ}}\"'",
patternGroups: "'should NOT have {{=$moreOrLess}} than {{=$limit}} properties matching pattern \"{{=it.util.escapeQuotes($pgProperty)}}\"'",
propertyNames: "'property name \\'{{=$invalidName}}\\' is invalid'",
required: "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'",
type: "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'",
@ -137,6 +137,7 @@
dependencies: "validate.schema{{=$schemaPath}}",
'enum': "validate.schema{{=$schemaPath}}",
format: "{{#def.schemaRefOrQS}}",
'if': "validate.schema{{=$schemaPath}}",
_limit: "{{#def.schemaRefOrVal}}",
_exclusiveLimit: "validate.schema{{=$schemaPath}}",
_limitItems: "{{#def.schemaRefOrVal}}",
@ -146,7 +147,6 @@
not: "validate.schema{{=$schemaPath}}",
oneOf: "validate.schema{{=$schemaPath}}",
pattern: "{{#def.schemaRefOrQS}}",
patternGroups: "validate.schema{{=$schemaPath}}",
propertyNames: "validate.schema{{=$schemaPath}}",
required: "validate.schema{{=$schemaPath}}",
type: "validate.schema{{=$schemaPath}}",
@ -167,11 +167,12 @@
additionalItems: "{ limit: {{=$schema.length}} }",
additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }",
anyOf: "{}",
const: "{}",
const: "{ allowedValue: schema{{=$lvl}} }",
contains: "{}",
dependencies: "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }",
'enum': "{ allowedValues: schema{{=$lvl}} }",
format: "{ format: {{#def.schemaValueQS}} }",
'if': "{ failingKeyword: {{=$ifClause}} }",
_limit: "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }",
_exclusiveLimit: "{}",
_limitItems: "{ limit: {{=$schemaValue}} }",
@ -179,9 +180,8 @@
_limitProperties:"{ limit: {{=$schemaValue}} }",
multipleOf: "{ multipleOf: {{=$schemaValue}} }",
not: "{}",
oneOf: "{}",
oneOf: "{ passingSchemas: {{=$passingSchemas}} }",
pattern: "{ pattern: {{#def.schemaValueQS}} }",
patternGroups: "{ reason: '{{=$reason}}', limit: {{=$limit}}, pattern: '{{=it.util.escapeQuotes($pgProperty)}}' }",
propertyNames: "{ propertyName: '{{=$invalidName}}' }",
required: "{ missingProperty: '{{=$missingProperty}}' }",
type: "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }",

View File

@ -24,7 +24,7 @@
({{=$format}} && {{=$formatType}} == '{{=$ruleType}}'
&& !(typeof {{=$format}} == 'function'
? {{? it.async}}
(async{{=$lvl}} ? {{=it.yieldAwait}} {{=$format}}({{=$data}}) : {{=$format}}({{=$data}}))
(async{{=$lvl}} ? await {{=$format}}({{=$data}}) : {{=$format}}({{=$data}}))
{{??}}
{{=$format}}({{=$data}})
{{?}}
@ -97,7 +97,7 @@
if (!it.async) throw new Error('async format in sync schema');
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
}}
if (!({{=it.yieldAwait}} {{=$formatRef}}({{=$data}}))) {
if (!(await {{=$formatRef}}({{=$data}}))) {
{{??}}
if (!{{# def.checkFormat }}) {
{{?}}

75
appasar/canary/node_modules/ajv/lib/dot/if.jst generated vendored Normal file
View File

@ -0,0 +1,75 @@
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
{{## def.validateIfClause:_clause:
{{
$it.schema = it.schema['_clause'];
$it.schemaPath = it.schemaPath + '._clause';
$it.errSchemaPath = it.errSchemaPath + '/_clause';
}}
{{# def.insertSubschemaCode }}
{{=$valid}} = {{=$nextValid}};
{{? $thenPresent && $elsePresent }}
{{ $ifClause = 'ifClause' + $lvl; }}
var {{=$ifClause}} = '_clause';
{{??}}
{{ $ifClause = '\'_clause\''; }}
{{?}}
#}}
{{
var $thenSch = it.schema['then']
, $elseSch = it.schema['else']
, $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }}
, $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }}
, $currentBaseId = $it.baseId;
}}
{{? $thenPresent || $elsePresent }}
{{
var $ifClause;
$it.createErrors = false;
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
}}
var {{=$errs}} = errors;
var {{=$valid}} = true;
{{# def.setCompositeRule }}
{{# def.insertSubschemaCode }}
{{ $it.createErrors = true; }}
{{# def.resetErrors }}
{{# def.resetCompositeRule }}
{{? $thenPresent }}
if ({{=$nextValid}}) {
{{# def.validateIfClause:then }}
}
{{? $elsePresent }}
else {
{{?}}
{{??}}
if (!{{=$nextValid}}) {
{{?}}
{{? $elsePresent }}
{{# def.validateIfClause:else }}
}
{{?}}
if (!{{=$valid}}) {
{{# def.extraError:'if' }}
}
{{? $breakOnError }} else { {{?}}
{{# def.cleanUp }}
{{??}}
{{? $breakOnError }}
if (true) {
{{?}}
{{?}}

View File

@ -3,11 +3,17 @@
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
var {{=$errs}} = errors;
var prevValid{{=$lvl}} = false;
var {{=$valid}} = false;
{{
var $currentBaseId = $it.baseId
, $prevValid = 'prevValid' + $lvl
, $passingSchemas = 'passingSchemas' + $lvl;
}}
var {{=$errs}} = errors
, {{=$prevValid}} = false
, {{=$valid}} = false
, {{=$passingSchemas}} = null;
{{ var $currentBaseId = $it.baseId; }}
{{# def.setCompositeRule }}
{{~ $schema:$sch:$i }}
@ -24,13 +30,17 @@ var {{=$valid}} = false;
{{?}}
{{? $i }}
if ({{=$nextValid}} && prevValid{{=$lvl}})
if ({{=$nextValid}} && {{=$prevValid}}) {
{{=$valid}} = false;
else {
{{=$passingSchemas}} = [{{=$passingSchemas}}, {{=$i}}];
} else {
{{ $closingBraces += '}'; }}
{{?}}
if ({{=$nextValid}}) {{=$valid}} = prevValid{{=$lvl}} = true;
if ({{=$nextValid}}) {
{{=$valid}} = {{=$prevValid}} = true;
{{=$passingSchemas}} = {{=$i}};
}
{{~}}
{{# def.resetCompositeRule }}

View File

@ -42,13 +42,8 @@
, $currentBaseId = it.baseId;
var $required = it.schema.required;
if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired)
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired)
var $requiredHash = it.util.toHash($required);
if (it.opts.patternGroups) {
var $pgProperties = it.schema.patternGroups || {}
, $pgPropertyKeys = Object.keys($pgProperties);
}
}}
@ -63,8 +58,8 @@ var {{=$nextValid}} = true;
{{? $someProperties }}
var isAdditional{{=$lvl}} = !(false
{{? $schemaKeys.length }}
{{? $schemaKeys.length > 5 }}
|| validate.schema{{=$schemaPath}}[{{=$key}}]
{{? $schemaKeys.length > 8 }}
|| validate.schema{{=$schemaPath}}.hasOwnProperty({{=$key}})
{{??}}
{{~ $schemaKeys:$propertyKey }}
|| {{=$key}} == {{= it.util.toQuotedString($propertyKey) }}
@ -76,11 +71,6 @@ var {{=$nextValid}} = true;
|| {{= it.usePattern($pProperty) }}.test({{=$key}})
{{~}}
{{?}}
{{? it.opts.patternGroups && $pgPropertyKeys.length }}
{{~ $pgPropertyKeys:$pgProperty:$i }}
|| {{= it.usePattern($pgProperty) }}.test({{=$key}})
{{~}}
{{?}}
);
if (isAdditional{{=$lvl}}) {
@ -246,79 +236,6 @@ var {{=$nextValid}} = true;
{{?}}
{{? it.opts.patternGroups && $pgPropertyKeys.length }}
{{~ $pgPropertyKeys:$pgProperty }}
{{
var $pgSchema = $pgProperties[$pgProperty]
, $sch = $pgSchema.schema;
}}
{{? {{# def.nonEmptySchema:$sch}} }}
{{
$it.schema = $sch;
$it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema';
$it.errSchemaPath = it.errSchemaPath + '/patternGroups/'
+ it.util.escapeFragment($pgProperty)
+ '/schema';
}}
var pgPropCount{{=$lvl}} = 0;
{{# def.iterateProperties }}
if ({{= it.usePattern($pgProperty) }}.test({{=$key}})) {
pgPropCount{{=$lvl}}++;
{{
$it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
}}
{{# def.generateSubschemaCode }}
{{# def.optimizeValidate }}
{{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}}
}
{{? $breakOnError }} else {{=$nextValid}} = true; {{?}}
}
{{# def.ifResultValid }}
{{
var $pgMin = $pgSchema.minimum
, $pgMax = $pgSchema.maximum;
}}
{{? $pgMin !== undefined || $pgMax !== undefined }}
var {{=$valid}} = true;
{{ var $currErrSchemaPath = $errSchemaPath; }}
{{? $pgMin !== undefined }}
{{ var $limit = $pgMin, $reason = 'minimum', $moreOrLess = 'less'; }}
{{=$valid}} = pgPropCount{{=$lvl}} >= {{=$pgMin}};
{{ $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum'; }}
{{# def.checkError:'patternGroups' }}
{{? $pgMax !== undefined }}
else
{{?}}
{{?}}
{{? $pgMax !== undefined }}
{{ var $limit = $pgMax, $reason = 'maximum', $moreOrLess = 'more'; }}
{{=$valid}} = pgPropCount{{=$lvl}} <= {{=$pgMax}};
{{ $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum'; }}
{{# def.checkError:'patternGroups' }}
{{?}}
{{ $errSchemaPath = $currErrSchemaPath; }}
{{# def.ifValid }}
{{?}}
{{?}} {{ /* def.nonEmptySchema */ }}
{{~}}
{{?}}
{{? $breakOnError }}
{{= $closingBraces }}
if ({{=$errs}} == errors) {

View File

@ -3,6 +3,8 @@
{{# def.setupKeyword }}
{{# def.setupNextLevel }}
var {{=$errs}} = errors;
{{? {{# def.nonEmptySchema:$schema }} }}
{{
$it.schema = $schema;
@ -22,8 +24,6 @@
, $currentBaseId = it.baseId;
}}
var {{=$errs}} = errors;
{{? $ownProperties }}
var {{=$dataProperties}} = undefined;
{{?}}

View File

@ -50,7 +50,7 @@
{{?}}
{{??}}
{{
$async = $refVal.$async === true;
$async = $refVal.$async === true || (it.async && $refVal.$async !== false);
$refCode = $refVal.code;
}}
{{?}}
@ -65,7 +65,7 @@
{{ if (!it.async) throw new Error('async schema referenced by sync schema'); }}
{{? $breakOnError }} var {{=$valid}}; {{?}}
try {
{{=it.yieldAwait}} {{=__callValidate}};
await {{=__callValidate}};
{{? $breakOnError }} {{=$valid}} = true; {{?}}
} catch (e) {
if (!(e instanceof ValidationError)) throw e;

View File

@ -14,18 +14,42 @@
else {
{{?}}
var {{=$valid}} = true;
if ({{=$data}}.length > 1) {
var i = {{=$data}}.length, j;
outer:
for (;i--;) {
for (j = i; j--;) {
if (equal({{=$data}}[i], {{=$data}}[j])) {
{{=$valid}} = false;
break outer;
var i = {{=$data}}.length
, {{=$valid}} = true
, j;
if (i > 1) {
{{
var $itemType = it.schema.items && it.schema.items.type
, $typeIsArray = Array.isArray($itemType);
}}
{{? !$itemType || $itemType == 'object' || $itemType == 'array' ||
($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) }}
outer:
for (;i--;) {
for (j = i; j--;) {
if (equal({{=$data}}[i], {{=$data}}[j])) {
{{=$valid}} = false;
break outer;
}
}
}
}
{{??}}
var itemIndices = {}, item;
for (;i--;) {
var item = {{=$data}}[i];
{{ var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); }}
if ({{= it.util[$method]($itemType, 'item', true) }}) continue;
{{? $typeIsArray}}
if (typeof item == 'string') item = '"' + item;
{{?}}
if (typeof itemIndices[item] == 'number') {
{{=$valid}} = false;
j = itemIndices[item];
break;
}
itemIndices[item] = i;
}
{{?}}
}
{{? $isData }} } {{?}}

View File

@ -21,29 +21,11 @@
}}
{{? it.isTop }}
{{? $async }}
{{
it.async = true;
var $es7 = it.opts.async == 'es7';
it.yieldAwait = $es7 ? 'await' : 'yield';
}}
{{?}}
var validate =
{{? $async }}
{{? $es7 }}
(async function
{{??}}
{{? it.opts.async != '*'}}co.wrap{{?}}(function*
{{?}}
{{??}}
(function
var validate = {{?$async}}{{it.async = true;}}async {{?}}function(data, dataPath, parentData, parentDataProperty, rootData) {
'use strict';
{{? $id && (it.opts.sourceCode || it.opts.processCode) }}
{{= '/\*# sourceURL=' + $id + ' */' }}
{{?}}
(data, dataPath, parentData, parentDataProperty, rootData) {
'use strict';
{{? $id && (it.opts.sourceCode || it.opts.processCode) }}
{{= '/\*# sourceURL=' + $id + ' */' }}
{{?}}
{{?}}
{{? typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref) }}
@ -70,7 +52,7 @@
{{?}}
{{? it.isTop}}
});
};
return validate;
{{?}}
@ -118,6 +100,16 @@
var $typeSchema = it.schema.type
, $typeIsArray = Array.isArray($typeSchema);
if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
if ($typeIsArray) {
if ($typeSchema.indexOf('null') == -1)
$typeSchema = $typeSchema.concat('null');
} else if ($typeSchema != 'null') {
$typeSchema = [$typeSchema, 'null'];
$typeIsArray = true;
}
}
if ($typeIsArray && $typeSchema.length == 1) {
$typeSchema = $typeSchema[0];
$typeIsArray = false;
@ -145,6 +137,10 @@
{{?}}
{{?}}
{{? it.schema.$comment && it.opts.$comment }}
{{= it.RULES.all.$comment.code(it, '$comment') }}
{{?}}
{{? $typeSchema }}
{{? it.opts.coerceTypes }}
{{ var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); }}
@ -176,9 +172,6 @@
{{ $closingBraces2 += '}'; }}
{{?}}
{{??}}
{{? it.opts.v5 && it.schema.patternGroups }}
{{ it.logger.warn('keyword "patternGroups" is deprecated and disabled. Use option patternGroups: true to enable.'); }}
{{?}}
{{~ it.RULES:$rulesGroup }}
{{? $shouldUseGroup($rulesGroup) }}
{{? $rulesGroup.type }}
@ -237,7 +230,7 @@
validate.errors = vErrors; {{ /* don't edit, used in replace */ }}
return errors === 0; {{ /* don't edit, used in replace */ }}
{{?}}
});
};
return validate;
{{??}}

View File

@ -52,7 +52,8 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -65,7 +66,13 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
if ($schema === undefined) {
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaValueExcl;
$isData = $isDataExcl;
}
} else {
var $exclIsNumber = typeof $schemaExcl == 'number',
$opStr = $op;
@ -132,7 +139,8 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -34,7 +34,7 @@ module.exports = function generate__limitItems(it, $keyword, $ruleType) {
if ($keyword == 'maxItems') {
out += 'more';
} else {
out += 'less';
out += 'fewer';
}
out += ' than ';
if ($isData) {
@ -59,7 +59,8 @@ module.exports = function generate__limitItems(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -64,7 +64,8 @@ module.exports = function generate__limitLength(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -34,7 +34,7 @@ module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
if ($keyword == 'maxProperties') {
out += 'more';
} else {
out += 'less';
out += 'fewer';
}
out += ' than ';
if ($isData) {
@ -59,7 +59,8 @@ module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -52,7 +52,8 @@ module.exports = function generate_anyOf(it, $keyword, $ruleType) {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError(vErrors); ';
} else {

14
appasar/canary/node_modules/ajv/lib/dotjs/comment.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
'use strict';
module.exports = function generate_comment(it, $keyword, $ruleType) {
var out = ' ';
var $schema = it.schema[$keyword];
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $comment = it.util.toQuotedString($schema);
if (it.opts.$comment === true) {
out += ' console.log(' + ($comment) + ');';
} else if (typeof it.opts.$comment == 'function') {
out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
}
return out;
}

View File

@ -25,7 +25,7 @@ module.exports = function generate_const(it, $keyword, $ruleType) {
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be equal to constant\' ';
}
@ -38,7 +38,8 @@ module.exports = function generate_const(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -60,7 +60,8 @@ module.exports = function generate_contains(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -99,13 +99,13 @@ module.exports = function generate_custom(it, $keyword, $ruleType) {
if ($rDef.errors === false) {
out += ' ' + ($valid) + ' = ';
if ($asyncKeyword) {
out += '' + (it.yieldAwait);
out += 'await ';
}
out += '' + (def_callRuleValidate) + '; ';
} else {
if ($asyncKeyword) {
$ruleErrs = 'customErrors' + $lvl;
out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
} else {
out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
}
@ -153,7 +153,8 @@ module.exports = function generate_custom(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -199,7 +200,8 @@ module.exports = function generate_custom(it, $keyword, $ruleType) {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError(vErrors); ';
} else {

View File

@ -80,7 +80,8 @@ module.exports = function generate_dependencies(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -48,7 +48,8 @@ module.exports = function generate_enum(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -46,7 +46,7 @@ module.exports = function generate_format(it, $keyword, $ruleType) {
}
out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
if (it.async) {
out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
} else {
out += ' ' + ($format) + '(' + ($data) + ') ';
}
@ -84,7 +84,7 @@ module.exports = function generate_format(it, $keyword, $ruleType) {
if ($async) {
if (!it.async) throw new Error('async format in sync schema');
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { ';
out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
} else {
out += ' if (! ';
var $formatRef = 'formats' + it.util.getProperty($schema);
@ -132,7 +132,8 @@ module.exports = function generate_format(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

104
appasar/canary/node_modules/ajv/lib/dotjs/if.js generated vendored Normal file
View File

@ -0,0 +1,104 @@
'use strict';
module.exports = function generate_if(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
$it.level++;
var $nextValid = 'valid' + $it.level;
var $thenSch = it.schema['then'],
$elseSch = it.schema['else'],
$thenPresent = $thenSch !== undefined && it.util.schemaHasRules($thenSch, it.RULES.all),
$elsePresent = $elseSch !== undefined && it.util.schemaHasRules($elseSch, it.RULES.all),
$currentBaseId = $it.baseId;
if ($thenPresent || $elsePresent) {
var $ifClause;
$it.createErrors = false;
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
$it.createErrors = true;
out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
it.compositeRule = $it.compositeRule = $wasComposite;
if ($thenPresent) {
out += ' if (' + ($nextValid) + ') { ';
$it.schema = it.schema['then'];
$it.schemaPath = it.schemaPath + '.then';
$it.errSchemaPath = it.errSchemaPath + '/then';
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
if ($thenPresent && $elsePresent) {
$ifClause = 'ifClause' + $lvl;
out += ' var ' + ($ifClause) + ' = \'then\'; ';
} else {
$ifClause = '\'then\'';
}
out += ' } ';
if ($elsePresent) {
out += ' else { ';
}
} else {
out += ' if (!' + ($nextValid) + ') { ';
}
if ($elsePresent) {
$it.schema = it.schema['else'];
$it.schemaPath = it.schemaPath + '.else';
$it.errSchemaPath = it.errSchemaPath + '/else';
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
if ($thenPresent && $elsePresent) {
$ifClause = 'ifClause' + $lvl;
out += ' var ' + ($ifClause) + ' = \'else\'; ';
} else {
$ifClause = '\'else\'';
}
out += ' } ';
}
out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError(vErrors); ';
} else {
out += ' validate.errors = vErrors; return false; ';
}
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
out = it.util.cleanUpCode(out);
} else {
if ($breakOnError) {
out += ' if (true) { ';
}
}
return out;
}

33
appasar/canary/node_modules/ajv/lib/dotjs/index.js generated vendored Normal file
View File

@ -0,0 +1,33 @@
'use strict';
//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
'$ref': require('./ref'),
allOf: require('./allOf'),
anyOf: require('./anyOf'),
'$comment': require('./comment'),
const: require('./const'),
contains: require('./contains'),
dependencies: require('./dependencies'),
'enum': require('./enum'),
format: require('./format'),
'if': require('./if'),
items: require('./items'),
maximum: require('./_limit'),
minimum: require('./_limit'),
maxItems: require('./_limitItems'),
minItems: require('./_limitItems'),
maxLength: require('./_limitLength'),
minLength: require('./_limitLength'),
maxProperties: require('./_limitProperties'),
minProperties: require('./_limitProperties'),
multipleOf: require('./multipleOf'),
not: require('./not'),
oneOf: require('./oneOf'),
pattern: require('./pattern'),
properties: require('./properties'),
propertyNames: require('./propertyNames'),
required: require('./required'),
uniqueItems: require('./uniqueItems'),
validate: require('./validate')
};

View File

@ -43,7 +43,8 @@ module.exports = function generate_items(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -59,7 +59,8 @@ module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -47,7 +47,8 @@ module.exports = function generate_not(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -14,8 +14,10 @@ module.exports = function generate_oneOf(it, $keyword, $ruleType) {
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;';
var $currentBaseId = $it.baseId;
var $currentBaseId = $it.baseId,
$prevValid = 'prevValid' + $lvl,
$passingSchemas = 'passingSchemas' + $lvl;
out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var arr1 = $schema;
@ -34,16 +36,16 @@ module.exports = function generate_oneOf(it, $keyword, $ruleType) {
out += ' var ' + ($nextValid) + ' = true; ';
}
if ($i) {
out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { ';
out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
$closingBraces += '}';
}
out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;';
out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
}
}
it.compositeRule = $it.compositeRule = $wasComposite;
out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should match exactly one schema in oneOf\' ';
}
@ -55,7 +57,8 @@ module.exports = function generate_oneOf(it, $keyword, $ruleType) {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError(vErrors); ';
} else {

View File

@ -57,7 +57,8 @@ module.exports = function generate_pattern(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -8,7 +8,6 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
@ -31,11 +30,7 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
$ownProperties = it.opts.ownProperties,
$currentBaseId = it.baseId;
var $required = it.schema.required;
if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
if (it.opts.patternGroups) {
var $pgProperties = it.schema.patternGroups || {},
$pgPropertyKeys = Object.keys($pgProperties);
}
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
if ($ownProperties) {
out += ' var ' + ($dataProperties) + ' = undefined;';
@ -49,8 +44,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
if ($someProperties) {
out += ' var isAdditional' + ($lvl) + ' = !(false ';
if ($schemaKeys.length) {
if ($schemaKeys.length > 5) {
out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] ';
if ($schemaKeys.length > 8) {
out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
} else {
var arr1 = $schemaKeys;
if (arr1) {
@ -74,17 +69,6 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
}
}
}
if (it.opts.patternGroups && $pgPropertyKeys.length) {
var arr3 = $pgPropertyKeys;
if (arr3) {
var $pgProperty, $i = -1,
l3 = arr3.length - 1;
while ($i < l3) {
$pgProperty = arr3[$i += 1];
out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') ';
}
}
}
out += ' ); if (isAdditional' + ($lvl) + ') { ';
}
if ($removeAdditional == 'all') {
@ -108,7 +92,13 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have additional properties\' ';
out += ' , message: \'';
if (it.opts._errorDataPathProperty) {
out += 'is an invalid additional property';
} else {
out += 'should NOT have additional properties';
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
@ -119,7 +109,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -185,12 +176,12 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
}
var $useDefaults = it.opts.useDefaults && !it.compositeRule;
if ($schemaKeys.length) {
var arr4 = $schemaKeys;
if (arr4) {
var $propertyKey, i4 = -1,
l4 = arr4.length - 1;
while (i4 < l4) {
$propertyKey = arr4[i4 += 1];
var arr3 = $schemaKeys;
if (arr3) {
var $propertyKey, i3 = -1,
l3 = arr3.length - 1;
while (i3 < l3) {
$propertyKey = arr3[i3 += 1];
var $sch = $schema[$propertyKey];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
var $prop = it.util.getProperty($propertyKey),
@ -249,7 +240,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -287,12 +279,12 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
}
}
if ($pPropertyKeys.length) {
var arr5 = $pPropertyKeys;
if (arr5) {
var $pProperty, i5 = -1,
l5 = arr5.length - 1;
while (i5 < l5) {
$pProperty = arr5[i5 += 1];
var arr4 = $pPropertyKeys;
if (arr4) {
var $pProperty, i4 = -1,
l4 = arr4.length - 1;
while (i4 < l4) {
$pProperty = arr4[i4 += 1];
var $sch = $pProperties[$pProperty];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
$it.schema = $sch;
@ -330,136 +322,6 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
}
}
}
if (it.opts.patternGroups && $pgPropertyKeys.length) {
var arr6 = $pgPropertyKeys;
if (arr6) {
var $pgProperty, i6 = -1,
l6 = arr6.length - 1;
while (i6 < l6) {
$pgProperty = arr6[i6 += 1];
var $pgSchema = $pgProperties[$pgProperty],
$sch = $pgSchema.schema;
if (it.util.schemaHasRules($sch, it.RULES.all)) {
$it.schema = $sch;
$it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema';
$it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema';
out += ' var pgPropCount' + ($lvl) + ' = 0; ';
if ($ownProperties) {
out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
} else {
out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
}
out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
if ($breakOnError) {
out += ' if (!' + ($nextValid) + ') break; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else ' + ($nextValid) + ' = true; ';
}
out += ' } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
var $pgMin = $pgSchema.minimum,
$pgMax = $pgSchema.maximum;
if ($pgMin !== undefined || $pgMax !== undefined) {
out += ' var ' + ($valid) + ' = true; ';
var $currErrSchemaPath = $errSchemaPath;
if ($pgMin !== undefined) {
var $limit = $pgMin,
$reason = 'minimum',
$moreOrLess = 'less';
out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; ';
$errSchemaPath = it.errSchemaPath + '/patternGroups/minimum';
out += ' if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($pgMax !== undefined) {
out += ' else ';
}
}
if ($pgMax !== undefined) {
var $limit = $pgMax,
$reason = 'maximum',
$moreOrLess = 'more';
out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; ';
$errSchemaPath = it.errSchemaPath + '/patternGroups/maximum';
out += ' if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
}
$errSchemaPath = $currErrSchemaPath;
if ($breakOnError) {
out += ' if (' + ($valid) + ') { ';
$closingBraces += '}';
}
}
}
}
}
}
if ($breakOnError) {
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
}

View File

@ -13,6 +13,7 @@ module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
out += 'var ' + ($errs) + ' = errors;';
if (it.util.schemaHasRules($schema, it.RULES.all)) {
$it.schema = $schema;
$it.schemaPath = $schemaPath;
@ -26,7 +27,6 @@ module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
$dataProperties = 'dataProperties' + $lvl,
$ownProperties = it.opts.ownProperties,
$currentBaseId = it.baseId;
out += ' var ' + ($errs) + ' = errors; ';
if ($ownProperties) {
out += ' var ' + ($dataProperties) + ' = undefined; ';
}
@ -61,7 +61,8 @@ module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError(vErrors); ';
} else {

View File

@ -40,7 +40,8 @@ module.exports = function generate_ref(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -73,7 +74,7 @@ module.exports = function generate_ref(it, $keyword, $ruleType) {
out += ' if (' + ($nextValid) + ') { ';
}
} else {
$async = $refVal.$async === true;
$async = $refVal.$async === true || (it.async && $refVal.$async !== false);
$refCode = $refVal.code;
}
}
@ -100,7 +101,7 @@ module.exports = function generate_ref(it, $keyword, $ruleType) {
if ($breakOnError) {
out += ' var ' + ($valid) + '; ';
}
out += ' try { ' + (it.yieldAwait) + ' ' + (__callValidate) + '; ';
out += ' try { await ' + (__callValidate) + '; ';
if ($breakOnError) {
out += ' ' + ($valid) + ' = true; ';
}

View File

@ -89,7 +89,8 @@ module.exports = function generate_required(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -148,7 +149,8 @@ module.exports = function generate_required(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -21,7 +21,21 @@ module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
if ($isData) {
out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
}
out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } ';
out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
var $itemType = it.schema.items && it.schema.items.type,
$typeIsArray = Array.isArray($itemType);
if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
} else {
out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
out += ' if (' + (it.util[$method]($itemType, 'item', true)) + ') continue; ';
if ($typeIsArray) {
out += ' if (typeof item == \'string\') item = \'"\' + item; ';
}
out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
}
out += ' } ';
if ($isData) {
out += ' } ';
}
@ -49,7 +63,8 @@ module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {

View File

@ -5,25 +5,12 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
$refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
$id = it.self._getId(it.schema);
if (it.isTop) {
if ($async) {
it.async = true;
var $es7 = it.opts.async == 'es7';
it.yieldAwait = $es7 ? 'await' : 'yield';
}
out += ' var validate = ';
if ($async) {
if ($es7) {
out += ' (async function ';
} else {
if (it.opts.async != '*') {
out += 'co.wrap';
}
out += '(function* ';
}
} else {
out += ' (function ';
it.async = true;
out += 'async ';
}
out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
if ($id && (it.opts.sourceCode || it.opts.processCode)) {
out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
}
@ -62,7 +49,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -83,7 +71,7 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
}
}
if (it.isTop) {
out += ' }); return validate; ';
out += ' }; return validate; ';
}
return out;
}
@ -114,6 +102,14 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
var $errorKeyword;
var $typeSchema = it.schema.type,
$typeIsArray = Array.isArray($typeSchema);
if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
if ($typeIsArray) {
if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
} else if ($typeSchema != 'null') {
$typeSchema = [$typeSchema, 'null'];
$typeIsArray = true;
}
}
if ($typeIsArray && $typeSchema.length == 1) {
$typeSchema = $typeSchema[0];
$typeIsArray = false;
@ -126,6 +122,9 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
}
}
if (it.schema.$comment && it.opts.$comment) {
out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
}
if ($typeSchema) {
if (it.opts.coerceTypes) {
var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
@ -207,7 +206,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -254,7 +254,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -280,9 +281,6 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
$closingBraces2 += '}';
}
} else {
if (it.opts.v5 && it.schema.patternGroups) {
it.logger.warn('keyword "patternGroups" is deprecated and disabled. Use option patternGroups: true to enable.');
}
var arr2 = it.RULES;
if (arr2) {
var $rulesGroup, i2 = -1,
@ -306,7 +304,11 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
var $sch = $schema[$propertyKey];
if ($sch.default !== undefined) {
var $passData = $data + it.util.getProperty($propertyKey);
out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
out += ' if (' + ($passData) + ' === undefined ';
if (it.opts.useDefaults == 'empty') {
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
}
out += ' ) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' ';
} else {
@ -325,7 +327,11 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
$sch = arr4[$i += 1];
if ($sch.default !== undefined) {
var $passData = $data + '[' + $i + ']';
out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
out += ' if (' + ($passData) + ' === undefined ';
if (it.opts.useDefaults == 'empty') {
out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
}
out += ' ) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' ';
} else {
@ -393,7 +399,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
@ -430,7 +437,7 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
out += ' validate.errors = vErrors; ';
out += ' return errors === 0; ';
}
out += ' }); return validate;';
out += ' }; return validate;';
} else {
out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
}

View File

@ -51,7 +51,7 @@ function addKeyword(keyword, definition) {
metaSchema = {
anyOf: [
metaSchema,
{ '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }
{ '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
]
};
}

View File

@ -1,36 +0,0 @@
'use strict';
var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema';
module.exports = function (ajv) {
var defaultMeta = ajv._opts.defaultMeta;
var metaSchemaRef = typeof defaultMeta == 'string'
? { $ref: defaultMeta }
: ajv.getSchema(META_SCHEMA_ID)
? { $ref: META_SCHEMA_ID }
: {};
ajv.addKeyword('patternGroups', {
// implemented in properties.jst
metaSchema: {
type: 'object',
additionalProperties: {
type: 'object',
required: [ 'schema' ],
properties: {
maximum: {
type: 'integer',
minimum: 0
},
minimum: {
type: 'integer',
minimum: 0
},
schema: metaSchemaRef
},
additionalProperties: false
}
}
});
ajv.RULES.all.properties.implements.push('patternGroups');
};

View File

@ -1,7 +1,7 @@
{
"$schema": "http://json-schema.org/draft-06/schema#",
"$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#",
"description": "Meta-schema for $data reference (JSON-schema extension proposal)",
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#",
"description": "Meta-schema for $data reference (JSON Schema extension proposal)",
"type": "object",
"required": [ "$data" ],
"properties": {

View File

@ -28,12 +28,10 @@
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uri"
"type": "string"
},
"$schema": {
"type": "string",
"format": "uri"
"type": "string"
},
"title": {
"type": "string"
@ -137,6 +135,7 @@
}
]
},
"format": { "type": "string" },
"allOf": { "$ref": "#/definitions/schemaArray" },
"anyOf": { "$ref": "#/definitions/schemaArray" },
"oneOf": { "$ref": "#/definitions/schemaArray" },

View File

@ -0,0 +1,168 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://json-schema.org/draft-07/schema#",
"title": "Core schema meta-schema",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#" }
},
"nonNegativeInteger": {
"type": "integer",
"minimum": 0
},
"nonNegativeIntegerDefault0": {
"allOf": [
{ "$ref": "#/definitions/nonNegativeInteger" },
{ "default": 0 }
]
},
"simpleTypes": {
"enum": [
"array",
"boolean",
"integer",
"null",
"number",
"object",
"string"
]
},
"stringArray": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true,
"default": []
}
},
"type": ["object", "boolean"],
"properties": {
"$id": {
"type": "string",
"format": "uri-reference"
},
"$schema": {
"type": "string",
"format": "uri"
},
"$ref": {
"type": "string",
"format": "uri-reference"
},
"$comment": {
"type": "string"
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"default": true,
"readOnly": {
"type": "boolean",
"default": false
},
"examples": {
"type": "array",
"items": true
},
"multipleOf": {
"type": "number",
"exclusiveMinimum": 0
},
"maximum": {
"type": "number"
},
"exclusiveMaximum": {
"type": "number"
},
"minimum": {
"type": "number"
},
"exclusiveMinimum": {
"type": "number"
},
"maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
"minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
"pattern": {
"type": "string",
"format": "regex"
},
"additionalItems": { "$ref": "#" },
"items": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/schemaArray" }
],
"default": true
},
"maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
"minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
"uniqueItems": {
"type": "boolean",
"default": false
},
"contains": { "$ref": "#" },
"maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
"minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
"required": { "$ref": "#/definitions/stringArray" },
"additionalProperties": { "$ref": "#" },
"definitions": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"properties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"patternProperties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"propertyNames": { "format": "regex" },
"default": {}
},
"dependencies": {
"type": "object",
"additionalProperties": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/stringArray" }
]
}
},
"propertyNames": { "$ref": "#" },
"const": true,
"enum": {
"type": "array",
"items": true,
"minItems": 1,
"uniqueItems": true
},
"type": {
"anyOf": [
{ "$ref": "#/definitions/simpleTypes" },
{
"type": "array",
"items": { "$ref": "#/definitions/simpleTypes" },
"minItems": 1,
"uniqueItems": true
}
]
},
"format": { "type": "string" },
"contentMediaType": { "type": "string" },
"contentEncoding": { "type": "string" },
"if": {"$ref": "#"},
"then": {"$ref": "#"},
"else": {"$ref": "#"},
"allOf": { "$ref": "#/definitions/schemaArray" },
"anyOf": { "$ref": "#/definitions/schemaArray" },
"oneOf": { "$ref": "#/definitions/schemaArray" },
"not": { "$ref": "#" }
},
"default": true
}

View File

@ -0,0 +1,94 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-secure.json#",
"title": "Meta-schema for the security assessment of JSON Schemas",
"description": "If a JSON Schema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": {"$ref": "#"}
}
},
"dependencies": {
"patternProperties": {
"description": "prevent slow validation of large property names",
"required": ["propertyNames"],
"properties": {
"propertyNames": {
"required": ["maxLength"]
}
}
},
"uniqueItems": {
"description": "prevent slow validation of large non-scalar arrays",
"if": {
"properties": {
"uniqueItems": {"const": true},
"items": {
"properties": {
"type": {
"anyOf": [
{
"enum": ["object", "array"]
},
{
"type": "array",
"contains": {"enum": ["object", "array"]}
}
]
}
}
}
}
},
"then": {
"required": ["maxItems"]
}
},
"pattern": {
"description": "prevent slow pattern matching of large strings",
"required": ["maxLength"]
},
"format": {
"description": "prevent slow format validation of large strings",
"required": ["maxLength"]
}
},
"properties": {
"additionalItems": {"$ref": "#"},
"additionalProperties": {"$ref": "#"},
"dependencies": {
"additionalProperties": {
"anyOf": [
{"type": "array"},
{"$ref": "#"}
]
}
},
"items": {
"anyOf": [
{"$ref": "#"},
{"$ref": "#/definitions/schemaArray"}
]
},
"definitions": {
"additionalProperties": {"$ref": "#"}
},
"patternProperties": {
"additionalProperties": {"$ref": "#"}
},
"properties": {
"additionalProperties": {"$ref": "#"}
},
"if": {"$ref": "#"},
"then": {"$ref": "#"},
"else": {"$ref": "#"},
"allOf": {"$ref": "#/definitions/schemaArray"},
"anyOf": {"$ref": "#/definitions/schemaArray"},
"oneOf": {"$ref": "#/definitions/schemaArray"},
"not": {"$ref": "#"},
"contains": {"$ref": "#"},
"propertyNames": {"$ref": "#"}
}
}

View File

@ -1,250 +0,0 @@
{
"id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#",
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Core schema meta-schema (v5 proposals - deprecated)",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#" }
},
"positiveInteger": {
"type": "integer",
"minimum": 0
},
"positiveIntegerDefault0": {
"allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
},
"simpleTypes": {
"enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
},
"stringArray": {
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"uniqueItems": true
},
"$data": {
"type": "object",
"required": [ "$data" ],
"properties": {
"$data": {
"type": "string",
"anyOf": [
{ "format": "relative-json-pointer" },
{ "format": "json-pointer" }
]
}
},
"additionalProperties": false
}
},
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uri"
},
"$schema": {
"type": "string",
"format": "uri"
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"default": {},
"multipleOf": {
"anyOf": [
{
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
{ "$ref": "#/definitions/$data" }
]
},
"maximum": {
"anyOf": [
{ "type": "number" },
{ "$ref": "#/definitions/$data" }
]
},
"exclusiveMaximum": {
"anyOf": [
{
"type": "boolean",
"default": false
},
{ "$ref": "#/definitions/$data" }
]
},
"minimum": {
"anyOf": [
{ "type": "number" },
{ "$ref": "#/definitions/$data" }
]
},
"exclusiveMinimum": {
"anyOf": [
{
"type": "boolean",
"default": false
},
{ "$ref": "#/definitions/$data" }
]
},
"maxLength": {
"anyOf": [
{ "$ref": "#/definitions/positiveInteger" },
{ "$ref": "#/definitions/$data" }
]
},
"minLength": {
"anyOf": [
{ "$ref": "#/definitions/positiveIntegerDefault0" },
{ "$ref": "#/definitions/$data" }
]
},
"pattern": {
"anyOf": [
{
"type": "string",
"format": "regex"
},
{ "$ref": "#/definitions/$data" }
]
},
"additionalItems": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" },
{ "$ref": "#/definitions/$data" }
],
"default": {}
},
"items": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/schemaArray" }
],
"default": {}
},
"maxItems": {
"anyOf": [
{ "$ref": "#/definitions/positiveInteger" },
{ "$ref": "#/definitions/$data" }
]
},
"minItems": {
"anyOf": [
{ "$ref": "#/definitions/positiveIntegerDefault0" },
{ "$ref": "#/definitions/$data" }
]
},
"uniqueItems": {
"anyOf": [
{
"type": "boolean",
"default": false
},
{ "$ref": "#/definitions/$data" }
]
},
"maxProperties": {
"anyOf": [
{ "$ref": "#/definitions/positiveInteger" },
{ "$ref": "#/definitions/$data" }
]
},
"minProperties": {
"anyOf": [
{ "$ref": "#/definitions/positiveIntegerDefault0" },
{ "$ref": "#/definitions/$data" }
]
},
"required": {
"anyOf": [
{ "$ref": "#/definitions/stringArray" },
{ "$ref": "#/definitions/$data" }
]
},
"additionalProperties": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" },
{ "$ref": "#/definitions/$data" }
],
"default": {}
},
"definitions": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"properties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"patternProperties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"dependencies": {
"type": "object",
"additionalProperties": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/stringArray" }
]
}
},
"enum": {
"anyOf": [
{
"type": "array",
"minItems": 1,
"uniqueItems": true
},
{ "$ref": "#/definitions/$data" }
]
},
"type": {
"anyOf": [
{ "$ref": "#/definitions/simpleTypes" },
{
"type": "array",
"items": { "$ref": "#/definitions/simpleTypes" },
"minItems": 1,
"uniqueItems": true
}
]
},
"allOf": { "$ref": "#/definitions/schemaArray" },
"anyOf": { "$ref": "#/definitions/schemaArray" },
"oneOf": { "$ref": "#/definitions/schemaArray" },
"not": { "$ref": "#" },
"format": {
"anyOf": [
{ "type": "string" },
{ "$ref": "#/definitions/$data" }
]
},
"constant": {
"anyOf": [
{},
{ "$ref": "#/definitions/$data" }
]
},
"contains": { "$ref": "#" }
},
"dependencies": {
"exclusiveMaximum": [ "maximum" ],
"exclusiveMinimum": [ "minimum" ]
},
"default": {}
}

View File

@ -1,6 +1,6 @@
{
"name": "ajv",
"version": "5.5.2",
"version": "6.8.1",
"description": "Another JSON Schema Validator",
"main": "lib/ajv.js",
"typings": "lib/ajv.d.ts",
@ -12,23 +12,20 @@
".tonic_example.js"
],
"scripts": {
"eslint": "if-node-version \">=4\" eslint lib/*.js lib/compile/*.js spec/*.js scripts",
"eslint": "eslint lib/*.js lib/compile/*.js spec/*.js scripts",
"jshint": "jshint lib/*.js lib/**/*.js --exclude lib/dotjs/**/*",
"test-spec": "mocha spec/*.spec.js -R spec $(if-node-version 7 echo --harmony-async-await)",
"test-spec": "mocha spec/*.spec.js -R spec",
"test-fast": "AJV_FAST_TEST=true npm run test-spec",
"test-debug": "mocha spec/*.spec.js --debug-brk -R spec",
"test-cov": "nyc npm run test-spec",
"test-ts": "tsc --target ES5 --noImplicitAny lib/ajv.d.ts",
"bundle": "node ./scripts/bundle.js . Ajv pure_getters",
"bundle-regenerator": "node ./scripts/bundle.js regenerator",
"bundle-nodent": "node ./scripts/bundle.js nodent",
"bundle-all": "del-cli dist && npm run bundle && npm run bundle-regenerator && npm run bundle-nodent",
"test-ts": "tsc --target ES5 --noImplicitAny --noEmit spec/typescript/index.ts",
"bundle": "del-cli dist && node ./scripts/bundle.js . Ajv pure_getters",
"bundle-beautify": "node ./scripts/bundle.js js-beautify",
"build": "del-cli lib/dotjs/*.js && node scripts/compile-dots.js",
"test-karma": "karma start --single-run --browsers PhantomJS",
"test-browser": "del-cli .browser && npm run bundle-all && scripts/prepare-tests && npm run test-karma",
"test": "npm run jshint && npm run eslint && npm run test-ts && npm run build && npm run test-cov && if-node-version 4 npm run test-browser",
"prepublish": "npm run build && npm run bundle-all",
"build": "del-cli lib/dotjs/*.js '!lib/dotjs/index.js' && node scripts/compile-dots.js",
"test-karma": "karma start",
"test-browser": "del-cli .browser && npm run bundle && scripts/prepare-tests && npm run test-karma",
"test": "npm run jshint && npm run eslint && npm run test-ts && npm run build && npm run test-cov && if-node-version 8 npm run test-browser",
"prepublish": "npm run build && npm run bundle",
"watch": "watch 'npm run build' ./lib/dot"
},
"nyc": {
@ -63,41 +60,37 @@
"homepage": "https://github.com/epoberezkin/ajv",
"tonicExampleFilename": ".tonic_example.js",
"dependencies": {
"co": "^4.6.0",
"fast-deep-equal": "^1.0.0",
"fast-deep-equal": "^2.0.1",
"fast-json-stable-stringify": "^2.0.0",
"json-schema-traverse": "^0.3.0"
"json-schema-traverse": "^0.4.1",
"uri-js": "^4.2.2"
},
"devDependencies": {
"ajv-async": "^0.1.0",
"bluebird": "^3.1.5",
"brfs": "^1.4.3",
"browserify": "^14.1.0",
"ajv-async": "^1.0.0",
"bluebird": "^3.5.3",
"brfs": "^2.0.0",
"browserify": "^16.2.0",
"chai": "^4.0.1",
"coveralls": "^3.0.0",
"coveralls": "^3.0.1",
"del-cli": "^1.1.0",
"dot": "^1.0.3",
"eslint": "^4.1.0",
"gh-pages-generator": "^0.2.0",
"eslint": "^5.0.0",
"gh-pages-generator": "^0.2.3",
"glob": "^7.0.0",
"if-node-version": "^1.0.0",
"js-beautify": "^1.7.3",
"jshint": "^2.9.4",
"json-schema-test": "^2.0.0",
"karma": "^1.0.0",
"karma-chrome-launcher": "^2.0.0",
"karma": "^3.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.1.1",
"karma-phantomjs-launcher": "^1.0.0",
"karma-sauce-launcher": "^1.1.0",
"mocha": "^4.0.0",
"nodent": "^3.0.17",
"nyc": "^11.0.2",
"phantomjs-prebuilt": "^2.1.4",
"karma-sauce-launcher": "^2.0.0",
"mocha": "^5.1.1",
"nyc": "^12.0.1",
"pre-commit": "^1.1.1",
"regenerator": "^0.12.2",
"require-globify": "^1.3.0",
"typescript": "^2.6.2",
"uglify-js": "^3.1.5",
"typescript": "^2.8.3",
"uglify-js": "^3.3.24",
"watch": "^1.0.0"
}
}

View File

@ -0,0 +1,32 @@
#!/usr/bin/env bash
set -e
if [[ -n $TRAVIS_TAG && $TRAVIS_JOB_NUMBER =~ ".3" ]]; then
echo "About to publish $TRAVIS_TAG to ajv-dist..."
git config user.email "$GIT_USER_EMAIL"
git config user.name "$GIT_USER_NAME"
git clone https://${GITHUB_TOKEN}@github.com/epoberezkin/ajv-dist.git ../ajv-dist
rm -rf ../ajv-dist/dist
mkdir ../ajv-dist/dist
cp ./dist/ajv.* ../ajv-dist/dist
cat bower.json | sed 's/"name": "ajv"/"name": "ajv-dist"/' > ../ajv-dist/bower.json
cd ../ajv-dist
if [[ `git status --porcelain` ]]; then
echo "Changes detected. Updating master branch..."
git add -A
git commit -m "updated by travis build #$TRAVIS_BUILD_NUMBER"
git push --quiet origin master > /dev/null 2>&1
fi
echo "Publishing tag..."
git tag $TRAVIS_TAG
git push --tags > /dev/null 2>&1
echo "Done"
fi

View File

@ -1,4 +0,0 @@
test
examples
example.js
browser

View File

@ -1 +0,0 @@
62638

View File

@ -57,7 +57,7 @@ function RequestSigner(request, credentials) {
}
RequestSigner.prototype.matchHost = function(host) {
var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)
var hostParts = (match || []).slice(1, 3)
// ES's hostParts are sometimes the other way round, if the value that is expected
@ -233,8 +233,8 @@ RequestSigner.prototype.canonicalString = function() {
if (normalizePath && piece === '..') {
path.pop()
} else if (!normalizePath || piece !== '.') {
if (decodePath) piece = querystring.unescape(piece)
path.push(encodeRfc3986(querystring.escape(piece)))
if (decodePath) piece = decodeURIComponent(piece)
path.push(encodeRfc3986(encodeURIComponent(piece)))
}
return path
}, []).join('/')
@ -303,7 +303,7 @@ RequestSigner.prototype.parsePath = function() {
// So if there are non-reserved chars (and it's not already all % encoded), just encode them all
if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
path = path.split('/').map(function(piece) {
return querystring.escape(querystring.unescape(piece))
return encodeURIComponent(decodeURIComponent(piece))
}).join('/')
}

View File

@ -1,6 +1,6 @@
{
"name": "aws4",
"version": "1.6.0",
"version": "1.8.0",
"description": "Signs and prepares requests using AWS Signature Version 4",
"author": "Michael Hart <michael.hart.au@gmail.com> (http://github.com/mhart)",
"main": "aws4.js",

View File

@ -1,29 +0,0 @@
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/boom/graphs/contributors

View File

@ -1,760 +0,0 @@
![boom Logo](https://raw.github.com/hapijs/boom/master/images/boom.png)
HTTP-friendly error objects
[![Build Status](https://secure.travis-ci.org/hapijs/boom.svg)](http://travis-ci.org/hapijs/boom)
[![Current Version](https://img.shields.io/npm/v/boom.svg)](https://www.npmjs.com/package/boom)
Lead Maintainer: [Adam Bretz](https://github.com/arb)
<!-- toc -->
- [Boom](#boom)
- [Helper Methods](#helper-methods)
- [`wrap(error, [statusCode], [message])`](#wraperror-statuscode-message)
- [`create(statusCode, [message], [data])`](#createstatuscode-message-data)
- [HTTP 4xx Errors](#http-4xx-errors)
- [`Boom.badRequest([message], [data])`](#boombadrequestmessage-data)
- [`Boom.unauthorized([message], [scheme], [attributes])`](#boomunauthorizedmessage-scheme-attributes)
- [`Boom.paymentRequired([message], [data])`](#boompaymentrequiredmessage-data)
- [`Boom.forbidden([message], [data])`](#boomforbiddenmessage-data)
- [`Boom.notFound([message], [data])`](#boomnotfoundmessage-data)
- [`Boom.methodNotAllowed([message], [data], [allow])`](#boommethodnotallowedmessage-data-allow)
- [`Boom.notAcceptable([message], [data])`](#boomnotacceptablemessage-data)
- [`Boom.proxyAuthRequired([message], [data])`](#boomproxyauthrequiredmessage-data)
- [`Boom.clientTimeout([message], [data])`](#boomclienttimeoutmessage-data)
- [`Boom.conflict([message], [data])`](#boomconflictmessage-data)
- [`Boom.resourceGone([message], [data])`](#boomresourcegonemessage-data)
- [`Boom.lengthRequired([message], [data])`](#boomlengthrequiredmessage-data)
- [`Boom.preconditionFailed([message], [data])`](#boompreconditionfailedmessage-data)
- [`Boom.entityTooLarge([message], [data])`](#boomentitytoolargemessage-data)
- [`Boom.uriTooLong([message], [data])`](#boomuritoolongmessage-data)
- [`Boom.unsupportedMediaType([message], [data])`](#boomunsupportedmediatypemessage-data)
- [`Boom.rangeNotSatisfiable([message], [data])`](#boomrangenotsatisfiablemessage-data)
- [`Boom.expectationFailed([message], [data])`](#boomexpectationfailedmessage-data)
- [`Boom.teapot([message], [data])`](#boomteapotmessage-data)
- [`Boom.badData([message], [data])`](#boombaddatamessage-data)
- [`Boom.locked([message], [data])`](#boomlockedmessage-data)
- [`Boom.preconditionRequired([message], [data])`](#boompreconditionrequiredmessage-data)
- [`Boom.tooManyRequests([message], [data])`](#boomtoomanyrequestsmessage-data)
- [`Boom.illegal([message], [data])`](#boomillegalmessage-data)
- [HTTP 5xx Errors](#http-5xx-errors)
- [`Boom.badImplementation([message], [data])` - (*alias: `internal`*)](#boombadimplementationmessage-data---alias-internal)
- [`Boom.notImplemented([message], [data])`](#boomnotimplementedmessage-data)
- [`Boom.badGateway([message], [data])`](#boombadgatewaymessage-data)
- [`Boom.serverUnavailable([message], [data])`](#boomserverunavailablemessage-data)
- [`Boom.gatewayTimeout([message], [data])`](#boomgatewaytimeoutmessage-data)
- [F.A.Q.](#faq)
<!-- tocstop -->
# Boom
**boom** provides a set of utilities for returning HTTP errors. Each utility returns a `Boom` error response
object (instance of `Error`) which includes the following properties:
- `isBoom` - if `true`, indicates this is a `Boom` object instance.
- `isServer` - convenience bool indicating status code >= 500.
- `message` - the error message.
- `output` - the formatted response. Can be directly manipulated after object construction to return a custom
error response. Allowed root keys:
- `statusCode` - the HTTP status code (typically 4xx or 5xx).
- `headers` - an object containing any HTTP headers where each key is a header name and value is the header content.
- `payload` - the formatted object used as the response payload (stringified). Can be directly manipulated but any
changes will be lost
if `reformat()` is called. Any content allowed and by default includes the following content:
- `statusCode` - the HTTP status code, derived from `error.output.statusCode`.
- `error` - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from `statusCode`.
- `message` - the error message derived from `error.message`.
- inherited `Error` properties.
The `Boom` object also supports the following method:
- `reformat()` - rebuilds `error.output` using the other object properties.
## Helper Methods
### `wrap(error, [statusCode], [message])`
Decorates an error with the **boom** properties where:
- `error` - the error object to wrap. If `error` is already a **boom** object, returns back the same object.
- `statusCode` - optional HTTP status code. Defaults to `500`.
- `message` - optional message string. If the error already has a message, it adds the message as a prefix.
Defaults to no message.
```js
var error = new Error('Unexpected input');
Boom.wrap(error, 400);
```
### `create(statusCode, [message], [data])`
Generates an `Error` object with the **boom** decorations where:
- `statusCode` - an HTTP error code number. Must be greater or equal 400.
- `message` - optional message string.
- `data` - additional error data set to `error.data` property.
```js
var error = Boom.create(400, 'Bad request', { timestamp: Date.now() });
```
## HTTP 4xx Errors
### `Boom.badRequest([message], [data])`
Returns a 400 Bad Request error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.badRequest('invalid query');
```
Generates the following response payload:
```json
{
"statusCode": 400,
"error": "Bad Request",
"message": "invalid query"
}
```
### `Boom.unauthorized([message], [scheme], [attributes])`
Returns a 401 Unauthorized error where:
- `message` - optional message.
- `scheme` can be one of the following:
- an authentication scheme name
- an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header.
- `attributes` - an object of values to use while setting the 'WWW-Authenticate' header. This value is only used
when `scheme` is a string, otherwise it is ignored. Every key/value pair will be included in the
'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the `attributes` key. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null.
`null` and `undefined` will be replaced with an empty string. If `attributes` is set, `message` will be used as
the 'error' segment of the 'WWW-Authenticate' header. If `message` is unset, the 'error' segment of the header
will not be present and `isMissing` will be true on the error object.
If either `scheme` or `attributes` are set, the resultant `Boom` object will have the 'WWW-Authenticate' header set for the response.
```js
Boom.unauthorized('invalid password');
```
Generates the following response:
```json
"payload": {
"statusCode": 401,
"error": "Unauthorized",
"message": "invalid password"
},
"headers" {}
```
```js
Boom.unauthorized('invalid password', 'sample');
```
Generates the following response:
```json
"payload": {
"statusCode": 401,
"error": "Unauthorized",
"message": "invalid password",
"attributes": {
"error": "invalid password"
}
},
"headers" {
"WWW-Authenticate": "sample error=\"invalid password\""
}
```
```js
Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4=');
```
Generates the following response:
```json
"payload": {
"statusCode": 401,
"error": "Unauthorized",
"attributes": "VGhpcyBpcyBhIHRlc3QgdG9rZW4="
},
"headers" {
"WWW-Authenticate": "Negotiate VGhpcyBpcyBhIHRlc3QgdG9rZW4="
}
```
```js
Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' });
```
Generates the following response:
```json
"payload": {
"statusCode": 401,
"error": "Unauthorized",
"message": "invalid password",
"attributes": {
"error": "invalid password",
"ttl": 0,
"cache": "",
"foo": "bar"
}
},
"headers" {
"WWW-Authenticate": "sample ttl=\"0\", cache=\"\", foo=\"bar\", error=\"invalid password\""
}
```
### `Boom.paymentRequired([message], [data])`
Returns a 402 Payment Required error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.paymentRequired('bandwidth used');
```
Generates the following response payload:
```json
{
"statusCode": 402,
"error": "Payment Required",
"message": "bandwidth used"
}
```
### `Boom.forbidden([message], [data])`
Returns a 403 Forbidden error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.forbidden('try again some time');
```
Generates the following response payload:
```json
{
"statusCode": 403,
"error": "Forbidden",
"message": "try again some time"
}
```
### `Boom.notFound([message], [data])`
Returns a 404 Not Found error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.notFound('missing');
```
Generates the following response payload:
```json
{
"statusCode": 404,
"error": "Not Found",
"message": "missing"
}
```
### `Boom.methodNotAllowed([message], [data], [allow])`
Returns a 405 Method Not Allowed error where:
- `message` - optional message.
- `data` - optional additional error data.
- `allow` - optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header.
```js
Boom.methodNotAllowed('that method is not allowed');
```
Generates the following response payload:
```json
{
"statusCode": 405,
"error": "Method Not Allowed",
"message": "that method is not allowed"
}
```
### `Boom.notAcceptable([message], [data])`
Returns a 406 Not Acceptable error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.notAcceptable('unacceptable');
```
Generates the following response payload:
```json
{
"statusCode": 406,
"error": "Not Acceptable",
"message": "unacceptable"
}
```
### `Boom.proxyAuthRequired([message], [data])`
Returns a 407 Proxy Authentication Required error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.proxyAuthRequired('auth missing');
```
Generates the following response payload:
```json
{
"statusCode": 407,
"error": "Proxy Authentication Required",
"message": "auth missing"
}
```
### `Boom.clientTimeout([message], [data])`
Returns a 408 Request Time-out error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.clientTimeout('timed out');
```
Generates the following response payload:
```json
{
"statusCode": 408,
"error": "Request Time-out",
"message": "timed out"
}
```
### `Boom.conflict([message], [data])`
Returns a 409 Conflict error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.conflict('there was a conflict');
```
Generates the following response payload:
```json
{
"statusCode": 409,
"error": "Conflict",
"message": "there was a conflict"
}
```
### `Boom.resourceGone([message], [data])`
Returns a 410 Gone error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.resourceGone('it is gone');
```
Generates the following response payload:
```json
{
"statusCode": 410,
"error": "Gone",
"message": "it is gone"
}
```
### `Boom.lengthRequired([message], [data])`
Returns a 411 Length Required error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.lengthRequired('length needed');
```
Generates the following response payload:
```json
{
"statusCode": 411,
"error": "Length Required",
"message": "length needed"
}
```
### `Boom.preconditionFailed([message], [data])`
Returns a 412 Precondition Failed error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.preconditionFailed();
```
Generates the following response payload:
```json
{
"statusCode": 412,
"error": "Precondition Failed"
}
```
### `Boom.entityTooLarge([message], [data])`
Returns a 413 Request Entity Too Large error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.entityTooLarge('too big');
```
Generates the following response payload:
```json
{
"statusCode": 413,
"error": "Request Entity Too Large",
"message": "too big"
}
```
### `Boom.uriTooLong([message], [data])`
Returns a 414 Request-URI Too Large error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.uriTooLong('uri is too long');
```
Generates the following response payload:
```json
{
"statusCode": 414,
"error": "Request-URI Too Large",
"message": "uri is too long"
}
```
### `Boom.unsupportedMediaType([message], [data])`
Returns a 415 Unsupported Media Type error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.unsupportedMediaType('that media is not supported');
```
Generates the following response payload:
```json
{
"statusCode": 415,
"error": "Unsupported Media Type",
"message": "that media is not supported"
}
```
### `Boom.rangeNotSatisfiable([message], [data])`
Returns a 416 Requested Range Not Satisfiable error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.rangeNotSatisfiable();
```
Generates the following response payload:
```json
{
"statusCode": 416,
"error": "Requested Range Not Satisfiable"
}
```
### `Boom.expectationFailed([message], [data])`
Returns a 417 Expectation Failed error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.expectationFailed('expected this to work');
```
Generates the following response payload:
```json
{
"statusCode": 417,
"error": "Expectation Failed",
"message": "expected this to work"
}
```
### `Boom.teapot([message], [data])`
Returns a 418 I'm a Teapot error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.teapot('sorry, no coffee...');
```
Generates the following response payload:
```json
{
"statusCode": 418,
"error": "I'm a Teapot",
"message": "Sorry, no coffee..."
}
```
### `Boom.badData([message], [data])`
Returns a 422 Unprocessable Entity error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.badData('your data is bad and you should feel bad');
```
Generates the following response payload:
```json
{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "your data is bad and you should feel bad"
}
```
### `Boom.locked([message], [data])`
Returns a 423 Locked error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.locked('this resource has been locked');
```
Generates the following response payload:
```json
{
"statusCode": 423,
"error": "Locked",
"message": "this resource has been locked"
}
```
### `Boom.preconditionRequired([message], [data])`
Returns a 428 Precondition Required error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.preconditionRequired('you must supply an If-Match header');
```
Generates the following response payload:
```json
{
"statusCode": 428,
"error": "Precondition Required",
"message": "you must supply an If-Match header"
}
```
### `Boom.tooManyRequests([message], [data])`
Returns a 429 Too Many Requests error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.tooManyRequests('you have exceeded your request limit');
```
Generates the following response payload:
```json
{
"statusCode": 429,
"error": "Too Many Requests",
"message": "you have exceeded your request limit"
}
```
### `Boom.illegal([message], [data])`
Returns a 451 Unavailable For Legal Reasons error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.illegal('you are not permitted to view this resource for legal reasons');
```
Generates the following response payload:
```json
{
"statusCode": 451,
"error": "Unavailable For Legal Reasons",
"message": "you are not permitted to view this resource for legal reasons"
}
```
## HTTP 5xx Errors
All 500 errors hide your message from the end user. Your message is recorded in the server log.
### `Boom.badImplementation([message], [data])` - (*alias: `internal`*)
Returns a 500 Internal Server Error error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.badImplementation('terrible implementation');
```
Generates the following response payload:
```json
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "An internal server error occurred"
}
```
### `Boom.notImplemented([message], [data])`
Returns a 501 Not Implemented error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.notImplemented('method not implemented');
```
Generates the following response payload:
```json
{
"statusCode": 501,
"error": "Not Implemented",
"message": "method not implemented"
}
```
### `Boom.badGateway([message], [data])`
Returns a 502 Bad Gateway error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.badGateway('that is a bad gateway');
```
Generates the following response payload:
```json
{
"statusCode": 502,
"error": "Bad Gateway",
"message": "that is a bad gateway"
}
```
### `Boom.serverUnavailable([message], [data])`
Returns a 503 Service Unavailable error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.serverUnavailable('unavailable');
```
Generates the following response payload:
```json
{
"statusCode": 503,
"error": "Service Unavailable",
"message": "unavailable"
}
```
### `Boom.gatewayTimeout([message], [data])`
Returns a 504 Gateway Time-out error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.gatewayTimeout();
```
Generates the following response payload:
```json
{
"statusCode": 504,
"error": "Gateway Time-out"
}
```
## F.A.Q.
**Q** How do I include extra information in my responses? `output.payload` is missing `data`, what gives?
**A** There is a reason the values passed back in the response payloads are pretty locked down. It's mostly for security and to not leak any important information back to the client. This means you will need to put in a little more effort to include extra information about your custom error. Check out the ["Error transformation"](https://github.com/hapijs/hapi/blob/master/API.md#error-transformation) section in the hapi documentation.
---

View File

@ -1,433 +0,0 @@
'use strict';
// Load modules
const Hoek = require('hoek');
// Declare internals
const internals = {
STATUS_CODES: Object.setPrototypeOf({
'100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'205': 'Reset Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Moved Temporarily',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'307': 'Temporary Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Time-out',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Request Entity Too Large',
'414': 'Request-URI Too Large',
'415': 'Unsupported Media Type',
'416': 'Requested Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'425': 'Unordered Collection',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Time-out',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'509': 'Bandwidth Limit Exceeded',
'510': 'Not Extended',
'511': 'Network Authentication Required'
}, null)
};
exports.wrap = function (error, statusCode, message) {
Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object');
Hoek.assert(!error.isBoom || (!statusCode && !message), 'Cannot provide statusCode or message with boom error');
return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message));
};
exports.create = function (statusCode, message, data) {
return internals.create(statusCode, message, data, exports.create);
};
internals.create = function (statusCode, message, data, ctor) {
if (message instanceof Error) {
if (data) {
message.data = data;
}
return exports.wrap(message, statusCode);
}
const error = new Error(message ? message : undefined); // Avoids settings null message
Error.captureStackTrace(error, ctor); // Filter the stack to our external API
error.data = data || null;
internals.initialize(error, statusCode);
return error;
};
internals.initialize = function (error, statusCode, message) {
const numberCode = parseInt(statusCode, 10);
Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'First argument must be a number (400+):', statusCode);
error.isBoom = true;
error.isServer = numberCode >= 500;
if (!error.hasOwnProperty('data')) {
error.data = null;
}
error.output = {
statusCode: numberCode,
payload: {},
headers: {}
};
error.reformat = internals.reformat;
error.reformat();
if (!message &&
!error.message) {
message = error.output.payload.error;
}
if (message) {
error.message = (message + (error.message ? ': ' + error.message : ''));
}
return error;
};
internals.reformat = function () {
this.output.payload.statusCode = this.output.statusCode;
this.output.payload.error = internals.STATUS_CODES[this.output.statusCode] || 'Unknown';
if (this.output.statusCode === 500) {
this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user
}
else if (this.message) {
this.output.payload.message = this.message;
}
};
// 4xx Client Errors
exports.badRequest = function (message, data) {
return internals.create(400, message, data, exports.badRequest);
};
exports.unauthorized = function (message, scheme, attributes) { // Or function (message, wwwAuthenticate[])
const err = internals.create(401, message, undefined, exports.unauthorized);
if (!scheme) {
return err;
}
let wwwAuthenticate = '';
if (typeof scheme === 'string') {
// function (message, scheme, attributes)
wwwAuthenticate = scheme;
if (attributes || message) {
err.output.payload.attributes = {};
}
if (attributes) {
if (typeof attributes === 'string') {
wwwAuthenticate = wwwAuthenticate + ' ' + Hoek.escapeHeaderAttribute(attributes);
err.output.payload.attributes = attributes;
}
else {
const names = Object.keys(attributes);
for (let i = 0; i < names.length; ++i) {
const name = names[i];
if (i) {
wwwAuthenticate = wwwAuthenticate + ',';
}
let value = attributes[name];
if (value === null ||
value === undefined) { // Value can be zero
value = '';
}
wwwAuthenticate = wwwAuthenticate + ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"';
err.output.payload.attributes[name] = value;
}
}
}
if (message) {
if (attributes) {
wwwAuthenticate = wwwAuthenticate + ',';
}
wwwAuthenticate = wwwAuthenticate + ' error="' + Hoek.escapeHeaderAttribute(message) + '"';
err.output.payload.attributes.error = message;
}
else {
err.isMissing = true;
}
}
else {
// function (message, wwwAuthenticate[])
const wwwArray = scheme;
for (let i = 0; i < wwwArray.length; ++i) {
if (i) {
wwwAuthenticate = wwwAuthenticate + ', ';
}
wwwAuthenticate = wwwAuthenticate + wwwArray[i];
}
}
err.output.headers['WWW-Authenticate'] = wwwAuthenticate;
return err;
};
exports.paymentRequired = function (message, data) {
return internals.create(402, message, data, exports.paymentRequired);
};
exports.forbidden = function (message, data) {
return internals.create(403, message, data, exports.forbidden);
};
exports.notFound = function (message, data) {
return internals.create(404, message, data, exports.notFound);
};
exports.methodNotAllowed = function (message, data, allow) {
const err = internals.create(405, message, data, exports.methodNotAllowed);
if (typeof allow === 'string') {
allow = [allow];
}
if (Array.isArray(allow)) {
err.output.headers.Allow = allow.join(', ');
}
return err;
};
exports.notAcceptable = function (message, data) {
return internals.create(406, message, data, exports.notAcceptable);
};
exports.proxyAuthRequired = function (message, data) {
return internals.create(407, message, data, exports.proxyAuthRequired);
};
exports.clientTimeout = function (message, data) {
return internals.create(408, message, data, exports.clientTimeout);
};
exports.conflict = function (message, data) {
return internals.create(409, message, data, exports.conflict);
};
exports.resourceGone = function (message, data) {
return internals.create(410, message, data, exports.resourceGone);
};
exports.lengthRequired = function (message, data) {
return internals.create(411, message, data, exports.lengthRequired);
};
exports.preconditionFailed = function (message, data) {
return internals.create(412, message, data, exports.preconditionFailed);
};
exports.entityTooLarge = function (message, data) {
return internals.create(413, message, data, exports.entityTooLarge);
};
exports.uriTooLong = function (message, data) {
return internals.create(414, message, data, exports.uriTooLong);
};
exports.unsupportedMediaType = function (message, data) {
return internals.create(415, message, data, exports.unsupportedMediaType);
};
exports.rangeNotSatisfiable = function (message, data) {
return internals.create(416, message, data, exports.rangeNotSatisfiable);
};
exports.expectationFailed = function (message, data) {
return internals.create(417, message, data, exports.expectationFailed);
};
exports.teapot = function (message, data) {
return internals.create(418, message, data, exports.teapot);
};
exports.badData = function (message, data) {
return internals.create(422, message, data, exports.badData);
};
exports.locked = function (message, data) {
return internals.create(423, message, data, exports.locked);
};
exports.preconditionRequired = function (message, data) {
return internals.create(428, message, data, exports.preconditionRequired);
};
exports.tooManyRequests = function (message, data) {
return internals.create(429, message, data, exports.tooManyRequests);
};
exports.illegal = function (message, data) {
return internals.create(451, message, data, exports.illegal);
};
// 5xx Server Errors
exports.internal = function (message, data, statusCode) {
return internals.serverError(message, data, statusCode, exports.internal);
};
internals.serverError = function (message, data, statusCode, ctor) {
let error;
if (data instanceof Error) {
error = exports.wrap(data, statusCode, message);
}
else {
error = internals.create(statusCode || 500, message, undefined, ctor);
error.data = data;
}
return error;
};
exports.notImplemented = function (message, data) {
return internals.serverError(message, data, 501, exports.notImplemented);
};
exports.badGateway = function (message, data) {
return internals.serverError(message, data, 502, exports.badGateway);
};
exports.serverUnavailable = function (message, data) {
return internals.serverError(message, data, 503, exports.serverUnavailable);
};
exports.gatewayTimeout = function (message, data) {
return internals.serverError(message, data, 504, exports.gatewayTimeout);
};
exports.badImplementation = function (message, data) {
const err = internals.serverError(message, data, 500, exports.badImplementation);
err.isDeveloperError = true;
return err;
};

View File

@ -1,29 +0,0 @@
{
"name": "boom",
"description": "HTTP-friendly error objects",
"version": "4.3.1",
"repository": "git://github.com/hapijs/boom",
"main": "lib/index.js",
"keywords": [
"error",
"http"
],
"engines": {
"node": ">=4.0.0"
},
"dependencies": {
"hoek": "4.x.x"
},
"devDependencies": {
"code": "4.x.x",
"lab": "13.x.x",
"markdown-toc": "0.12.x"
},
"scripts": {
"test": "lab -a code -t 100 -L -v",
"test-cov-html": "lab -a code -r html -o coverage.html -L",
"toc": "node generate-toc.js",
"version": "npm run toc && git add README.md"
},
"license": "BSD-3-Clause"
}

View File

@ -1,172 +0,0 @@
4.6.0 / 2015-07-09
==================
* support passing the rest of the arguments to co into the generator
```js
function *gen(...args) { }
co(gen, ...args);
```
4.5.0 / 2015-03-17
==================
* support regular functions (that return promises)
4.4.0 / 2015-02-14
==================
* refactor `isGeneratorFunction`
* expose generator function from `co.wrap()`
* drop support for node < 0.12
4.3.0 / 2015-02-05
==================
* check for generator functions in a ES5-transpiler-friendly way
4.2.0 / 2015-01-20
==================
* support comparing generator functions with ES6 transpilers
4.1.0 / 2014-12-26
==================
* fix memory leak #180
4.0.2 / 2014-12-18
==================
* always return a global promise implementation
4.0.1 / 2014-11-30
==================
* friendlier ES6 module exports
4.0.0 / 2014-11-15
==================
* co now returns a promise and uses promises underneath
* `co.wrap()` for wrapping generator functions
3.1.0 / 2014-06-30
==================
* remove `setImmediate()` shim for node 0.8. semi-backwards breaking.
Users are expected to shim themselves. Also returns CommonJS browser support.
* added key order preservation for objects. thanks @greim
* replace `q` with `bluebird` in benchmarks and tests
3.0.6 / 2014-05-03
==================
* add `setImmediate()` fallback to `process.nextTick`
* remove duplicate code in toThunk
* update thunkify
3.0.5 / 2014-03-17
==================
* fix object/array test failure which tries to enumerate dates. Closes #98
* fix final callback error propagation. Closes #92
3.0.4 / 2014-02-17
==================
* fix toThunk object check regression. Closes #89
3.0.3 / 2014-02-08
==================
* refactor: arrayToThunk @AutoSponge #88
3.0.2 / 2014-01-01
==================
* fixed: nil arguments replaced with error fn
3.0.1 / 2013-12-19
==================
* fixed: callback passed as an argument to generators
3.0.0 / 2013-12-19
==================
* fixed: callback passed as an argument to generators
* change: `co(function *(){})` now returns a reusable thunk
* change: `this` must now be passed through the returned thunk, ex. `co(function *(){}).call(this)`
* fix "generator already finished" errors
2.3.0 / 2013-11-12
==================
* add `yield object` support
2.2.0 / 2013-11-05
==================
* change: make the `isGenerator()` function more generic
2.1.0 / 2013-10-21
==================
* add passing of arguments into the generator. closes #33.
2.0.0 / 2013-10-14
==================
* remove callback in favour of thunk-only co(). Closes #30 [breaking change]
* remove `co.wrap()` [breaking change]
1.5.2 / 2013-09-02
==================
* fix: preserve receiver with co.wrap()
1.5.1 / 2013-08-11
==================
* remove setImmediate() usage - ~110% perf increase. Closes #14
0.5.0 / 2013-08-10
==================
* add receiver propagation support
* examples: update streams.js example to use `http.get()` and streams2 API
1.4.1 / 2013-07-01
==================
* fix gen.next(val) for latest v8. Closes #8
1.4.0 / 2013-06-21
==================
* add promise support to joins
* add `yield generatorFunction` support
* add `yield generator` support
* add nested join support
1.3.0 / 2013-06-10
==================
* add passing of arguments
1.2.1 / 2013-06-08
==================
* fix join() of zero thunks
1.2.0 / 2013-06-08
==================
* add array yielding support. great suggestion by @domenic
1.1.0 / 2013-06-06
==================
* add promise support
* change nextTick to setImmediate

View File

@ -1,212 +0,0 @@
# co
[![Gitter][gitter-image]][gitter-url]
[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Downloads][downloads-image]][downloads-url]
Generator based control flow goodness for nodejs and the browser,
using promises, letting you write non-blocking code in a nice-ish way.
## Co v4
`co@4.0.0` has been released, which now relies on promises.
It is a stepping stone towards [ES7 async/await](https://github.com/lukehoban/ecmascript-asyncawait).
The primary API change is how `co()` is invoked.
Before, `co` returned a "thunk", which you then called with a callback and optional arguments.
Now, `co()` returns a promise.
```js
co(function* () {
var result = yield Promise.resolve(true);
return result;
}).then(function (value) {
console.log(value);
}, function (err) {
console.error(err.stack);
});
```
If you want to convert a `co`-generator-function into a regular function that returns a promise,
you now use `co.wrap(fn*)`.
```js
var fn = co.wrap(function* (val) {
return yield Promise.resolve(val);
});
fn(true).then(function (val) {
});
```
## Platform Compatibility
`co@4+` requires a `Promise` implementation.
For versions of node `< 0.11` and for many older browsers,
you should/must include your own `Promise` polyfill.
When using node 0.11.x or greater, you must use the `--harmony-generators`
flag or just `--harmony` to get access to generators.
When using node 0.10.x and lower or browsers without generator support,
you must use [gnode](https://github.com/TooTallNate/gnode) and/or [regenerator](http://facebook.github.io/regenerator/).
io.js is supported out of the box, you can use `co` without flags or polyfills.
## Installation
```
$ npm install co
```
## Associated libraries
Any library that returns promises work well with `co`.
- [mz](https://github.com/normalize/mz) - wrap all of node's code libraries as promises.
View the [wiki](https://github.com/visionmedia/co/wiki) for more libraries.
## Examples
```js
var co = require('co');
co(function *(){
// yield any promise
var result = yield Promise.resolve(true);
}).catch(onerror);
co(function *(){
// resolve multiple promises in parallel
var a = Promise.resolve(1);
var b = Promise.resolve(2);
var c = Promise.resolve(3);
var res = yield [a, b, c];
console.log(res);
// => [1, 2, 3]
}).catch(onerror);
// errors can be try/catched
co(function *(){
try {
yield Promise.reject(new Error('boom'));
} catch (err) {
console.error(err.message); // "boom"
}
}).catch(onerror);
function onerror(err) {
// log any uncaught errors
// co will not throw any errors you do not handle!!!
// HANDLE ALL YOUR ERRORS!!!
console.error(err.stack);
}
```
## Yieldables
The `yieldable` objects currently supported are:
- promises
- thunks (functions)
- array (parallel execution)
- objects (parallel execution)
- generators (delegation)
- generator functions (delegation)
Nested `yieldable` objects are supported, meaning you can nest
promises within objects within arrays, and so on!
### Promises
[Read more on promises!](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
### Thunks
Thunks are functions that only have a single argument, a callback.
Thunk support only remains for backwards compatibility and may
be removed in future versions of `co`.
### Arrays
`yield`ing an array will resolve all the `yieldables` in parallel.
```js
co(function* () {
var res = yield [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
];
console.log(res); // => [1, 2, 3]
}).catch(onerror);
```
### Objects
Just like arrays, objects resolve all `yieldable`s in parallel.
```js
co(function* () {
var res = yield {
1: Promise.resolve(1),
2: Promise.resolve(2),
};
console.log(res); // => { 1: 1, 2: 2 }
}).catch(onerror);
```
### Generators and Generator Functions
Any generator or generator function you can pass into `co`
can be yielded as well. This should generally be avoided
as we should be moving towards spec-compliant `Promise`s instead.
## API
### co(fn*).then( val => )
Returns a promise that resolves a generator, generator function,
or any function that returns a generator.
```js
co(function* () {
return yield Promise.resolve(true);
}).then(function (val) {
console.log(val);
}, function (err) {
console.error(err.stack);
});
```
### var fn = co.wrap(fn*)
Convert a generator into a regular function that returns a `Promise`.
```js
var fn = co.wrap(function* (val) {
return yield Promise.resolve(val);
});
fn(true).then(function (val) {
});
```
## License
MIT
[npm-image]: https://img.shields.io/npm/v/co.svg?style=flat-square
[npm-url]: https://npmjs.org/package/co
[travis-image]: https://img.shields.io/travis/tj/co.svg?style=flat-square
[travis-url]: https://travis-ci.org/tj/co
[coveralls-image]: https://img.shields.io/coveralls/tj/co.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/tj/co
[downloads-image]: http://img.shields.io/npm/dm/co.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/co
[gitter-image]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/tj/co?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge

View File

@ -1,237 +0,0 @@
/**
* slice() reference.
*/
var slice = Array.prototype.slice;
/**
* Expose `co`.
*/
module.exports = co['default'] = co.co = co;
/**
* Wrap the given generator `fn` into a
* function that returns a promise.
* This is a separate function so that
* every `co()` call doesn't create a new,
* unnecessary closure.
*
* @param {GeneratorFunction} fn
* @return {Function}
* @api public
*/
co.wrap = function (fn) {
createPromise.__generatorFunction__ = fn;
return createPromise;
function createPromise() {
return co.call(this, fn.apply(this, arguments));
}
};
/**
* Execute the generator function or a generator
* and return a promise.
*
* @param {Function} fn
* @return {Promise}
* @api public
*/
function co(gen) {
var ctx = this;
var args = slice.call(arguments, 1)
// we wrap everything in a promise to avoid promise chaining,
// which leads to memory leak errors.
// see https://github.com/tj/co/issues/180
return new Promise(function(resolve, reject) {
if (typeof gen === 'function') gen = gen.apply(ctx, args);
if (!gen || typeof gen.next !== 'function') return resolve(gen);
onFulfilled();
/**
* @param {Mixed} res
* @return {Promise}
* @api private
*/
function onFulfilled(res) {
var ret;
try {
ret = gen.next(res);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* @param {Error} err
* @return {Promise}
* @api private
*/
function onRejected(err) {
var ret;
try {
ret = gen.throw(err);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* Get the next value in the generator,
* return a promise.
*
* @param {Object} ret
* @return {Promise}
* @api private
*/
function next(ret) {
if (ret.done) return resolve(ret.value);
var value = toPromise.call(ctx, ret.value);
if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
+ 'but the following object was passed: "' + String(ret.value) + '"'));
}
});
}
/**
* Convert a `yield`ed value into a promise.
*
* @param {Mixed} obj
* @return {Promise}
* @api private
*/
function toPromise(obj) {
if (!obj) return obj;
if (isPromise(obj)) return obj;
if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj);
if ('function' == typeof obj) return thunkToPromise.call(this, obj);
if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
if (isObject(obj)) return objectToPromise.call(this, obj);
return obj;
}
/**
* Convert a thunk to a promise.
*
* @param {Function}
* @return {Promise}
* @api private
*/
function thunkToPromise(fn) {
var ctx = this;
return new Promise(function (resolve, reject) {
fn.call(ctx, function (err, res) {
if (err) return reject(err);
if (arguments.length > 2) res = slice.call(arguments, 1);
resolve(res);
});
});
}
/**
* Convert an array of "yieldables" to a promise.
* Uses `Promise.all()` internally.
*
* @param {Array} obj
* @return {Promise}
* @api private
*/
function arrayToPromise(obj) {
return Promise.all(obj.map(toPromise, this));
}
/**
* Convert an object of "yieldables" to a promise.
* Uses `Promise.all()` internally.
*
* @param {Object} obj
* @return {Promise}
* @api private
*/
function objectToPromise(obj){
var results = new obj.constructor();
var keys = Object.keys(obj);
var promises = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var promise = toPromise.call(this, obj[key]);
if (promise && isPromise(promise)) defer(promise, key);
else results[key] = obj[key];
}
return Promise.all(promises).then(function () {
return results;
});
function defer(promise, key) {
// predefine the key in the result
results[key] = undefined;
promises.push(promise.then(function (res) {
results[key] = res;
}));
}
}
/**
* Check if `obj` is a promise.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isPromise(obj) {
return 'function' == typeof obj.then;
}
/**
* Check if `obj` is a generator.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/
function isGenerator(obj) {
return 'function' == typeof obj.next && 'function' == typeof obj.throw;
}
/**
* Check if `obj` is a generator function.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/
function isGeneratorFunction(obj) {
var constructor = obj.constructor;
if (!constructor) return false;
if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
return isGenerator(constructor.prototype);
}
/**
* Check for plain object.
*
* @param {Mixed} val
* @return {Boolean}
* @api private
*/
function isObject(val) {
return Object == val.constructor;
}

View File

@ -1,34 +0,0 @@
{
"name": "co",
"version": "4.6.0",
"description": "generator async control flow goodness",
"keywords": [
"async",
"flow",
"generator",
"coro",
"coroutine"
],
"devDependencies": {
"browserify": "^10.0.0",
"istanbul-harmony": "0",
"mocha": "^2.0.0",
"mz": "^1.0.2"
},
"scripts": {
"test": "mocha --harmony",
"test-cov": "node --harmony node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --reporter dot",
"test-travis": "node --harmony node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha --report lcovonly -- --reporter dot",
"prepublish": "npm run browserify",
"browserify": "browserify index.js -o ./co-browser.js -s co"
},
"files": [
"index.js"
],
"license": "MIT",
"repository": "tj/co",
"engines": {
"iojs": ">= 1.0.0",
"node": ">= 0.12.0"
}
}

View File

@ -2,7 +2,7 @@
A stream that emits multiple other streams one after another.
**NB** Currently `combined-stream` works with streams vesrion 1 only. There is ongoing effort to switch this library to streams version 2. Any help is welcome. :) Meanwhile you can explore other libraries that provide streams2 support with more or less compatability with `combined-stream`.
**NB** Currently `combined-stream` works with streams version 1 only. There is ongoing effort to switch this library to streams version 2. Any help is welcome. :) Meanwhile you can explore other libraries that provide streams2 support with more or less compatibility with `combined-stream`.
- [combined-stream2](https://www.npmjs.com/package/combined-stream2): A drop-in streams2-compatible replacement for the combined-stream module.

View File

@ -1,6 +1,7 @@
var util = require('util');
var Stream = require('stream').Stream;
var DelayedStream = require('delayed-stream');
var defer = require('./defer.js');
module.exports = CombinedStream;
function CombinedStream() {
@ -88,7 +89,7 @@ CombinedStream.prototype._getNext = function() {
this._handleErrors(stream);
}
this._pipeNext(stream);
defer(this._pipeNext.bind(this, stream));
}.bind(this));
};

View File

@ -2,7 +2,7 @@
"author": "Felix Geisendörfer <felix@debuggable.com> (http://debuggable.com/)",
"name": "combined-stream",
"description": "A stream that emits multiple other streams one after another.",
"version": "1.0.5",
"version": "1.0.7",
"homepage": "https://github.com/felixge/node-combined-stream",
"repository": {
"type": "git",

View File

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

View File

@ -1,28 +0,0 @@
Copyright (c) 2014-2017, Eran Hammer and Project contributors
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/hueniverse/cryptiles/graphs/contributors

View File

@ -1,19 +0,0 @@
cryptiles
=========
General purpose crypto utilities
[![Build Status](https://secure.travis-ci.org/hapijs/cryptiles.png)](http://travis-ci.org/hapijs/cryptiles)
Lead Maintainer - [C J Silverio](https://github.com/ceejbot)
## Methods
### `randomString(<Number> size)`
Returns a cryptographically strong pseudo-random data string. Takes a size argument for the length of the string.
### `randomDigits(<Number> size)`
Returns a cryptographically strong pseudo-random data string consisting of only numerical digits (0-9). Takes a size argument for the length of the string.
### `fixedTimeComparison(<String> a, <String> b)`
Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match). Returns `true` if the strings match, `false` if they differ.

View File

@ -1,88 +0,0 @@
'use strict';
// Load modules
const Crypto = require('crypto');
const Boom = require('boom');
// Declare internals
const internals = {};
// Generate a cryptographically strong pseudo-random data
exports.randomString = function (size) {
const buffer = exports.randomBits((size + 1) * 6);
if (buffer instanceof Error) {
return buffer;
}
const string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
return string.slice(0, size);
};
// Return a random string of digits
exports.randomDigits = function (size) {
const buffer = exports.randomBits(size * 8);
if (buffer instanceof Error) {
return buffer;
}
const digits = [];
for (let i = 0; i < buffer.length; ++i) {
digits.push(Math.floor(buffer[i] / 25.6));
}
return digits.join('');
};
// Generate a buffer of random bits
exports.randomBits = function (bits) {
if (!bits ||
bits < 0) {
return Boom.internal('Invalid random bits count');
}
const bytes = Math.ceil(bits / 8);
try {
return Crypto.randomBytes(bytes);
}
catch (err) {
return Boom.internal('Failed generating random bits: ' + err.message);
}
};
// Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match)
exports.fixedTimeComparison = function (a, b) {
if (typeof a !== 'string' ||
typeof b !== 'string') {
return false;
}
let mismatch = (a.length === b.length ? 0 : 1);
if (mismatch) {
b = a;
}
for (let i = 0; i < a.length; ++i) {
const ac = a.charCodeAt(i);
const bc = b.charCodeAt(i);
mismatch |= (ac ^ bc);
}
return (mismatch === 0);
};

View File

@ -1,29 +0,0 @@
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/boom/graphs/contributors

View File

@ -1,784 +0,0 @@
![boom Logo](https://raw.github.com/hapijs/boom/master/images/boom.png)
HTTP-friendly error objects
[![Build Status](https://secure.travis-ci.org/hapijs/boom.svg)](http://travis-ci.org/hapijs/boom)
[![Current Version](https://img.shields.io/npm/v/boom.svg)](https://www.npmjs.com/package/boom)
Lead Maintainer: [Adam Bretz](https://github.com/arb)
<!-- toc -->
- [Boom](#boom)
- [Helper Methods](#helper-methods)
- [`boomify(error, [options])`](#boomifyerror-options)
- [`wrap(error, [statusCode], [message])`](#wraperror-statuscode-message)
- [`create(statusCode, [message], [data])`](#createstatuscode-message-data)
- [HTTP 4xx Errors](#http-4xx-errors)
- [`Boom.badRequest([message], [data])`](#boombadrequestmessage-data)
- [`Boom.unauthorized([message], [scheme], [attributes])`](#boomunauthorizedmessage-scheme-attributes)
- [`Boom.paymentRequired([message], [data])`](#boompaymentrequiredmessage-data)
- [`Boom.forbidden([message], [data])`](#boomforbiddenmessage-data)
- [`Boom.notFound([message], [data])`](#boomnotfoundmessage-data)
- [`Boom.methodNotAllowed([message], [data], [allow])`](#boommethodnotallowedmessage-data-allow)
- [`Boom.notAcceptable([message], [data])`](#boomnotacceptablemessage-data)
- [`Boom.proxyAuthRequired([message], [data])`](#boomproxyauthrequiredmessage-data)
- [`Boom.clientTimeout([message], [data])`](#boomclienttimeoutmessage-data)
- [`Boom.conflict([message], [data])`](#boomconflictmessage-data)
- [`Boom.resourceGone([message], [data])`](#boomresourcegonemessage-data)
- [`Boom.lengthRequired([message], [data])`](#boomlengthrequiredmessage-data)
- [`Boom.preconditionFailed([message], [data])`](#boompreconditionfailedmessage-data)
- [`Boom.entityTooLarge([message], [data])`](#boomentitytoolargemessage-data)
- [`Boom.uriTooLong([message], [data])`](#boomuritoolongmessage-data)
- [`Boom.unsupportedMediaType([message], [data])`](#boomunsupportedmediatypemessage-data)
- [`Boom.rangeNotSatisfiable([message], [data])`](#boomrangenotsatisfiablemessage-data)
- [`Boom.expectationFailed([message], [data])`](#boomexpectationfailedmessage-data)
- [`Boom.teapot([message], [data])`](#boomteapotmessage-data)
- [`Boom.badData([message], [data])`](#boombaddatamessage-data)
- [`Boom.locked([message], [data])`](#boomlockedmessage-data)
- [`Boom.preconditionRequired([message], [data])`](#boompreconditionrequiredmessage-data)
- [`Boom.tooManyRequests([message], [data])`](#boomtoomanyrequestsmessage-data)
- [`Boom.illegal([message], [data])`](#boomillegalmessage-data)
- [HTTP 5xx Errors](#http-5xx-errors)
- [`Boom.badImplementation([message], [data])` - (*alias: `internal`*)](#boombadimplementationmessage-data---alias-internal)
- [`Boom.notImplemented([message], [data])`](#boomnotimplementedmessage-data)
- [`Boom.badGateway([message], [data])`](#boombadgatewaymessage-data)
- [`Boom.serverUnavailable([message], [data])`](#boomserverunavailablemessage-data)
- [`Boom.gatewayTimeout([message], [data])`](#boomgatewaytimeoutmessage-data)
- [F.A.Q.](#faq)
<!-- tocstop -->
# Boom
**boom** provides a set of utilities for returning HTTP errors. Each utility returns a `Boom` error response
object (instance of `Error`) which includes the following properties:
- `isBoom` - if `true`, indicates this is a `Boom` object instance.
- `isServer` - convenience bool indicating status code >= 500.
- `message` - the error message.
- `typeof` - the contructor used to create the error (e.g. `Boom.badRequest`).
- `output` - the formatted response. Can be directly manipulated after object construction to return a custom
error response. Allowed root keys:
- `statusCode` - the HTTP status code (typically 4xx or 5xx).
- `headers` - an object containing any HTTP headers where each key is a header name and value is the header content.
- `payload` - the formatted object used as the response payload (stringified). Can be directly manipulated but any
changes will be lost
if `reformat()` is called. Any content allowed and by default includes the following content:
- `statusCode` - the HTTP status code, derived from `error.output.statusCode`.
- `error` - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from `statusCode`.
- `message` - the error message derived from `error.message`.
- inherited `Error` properties.
The `Boom` object also supports the following method:
- `reformat()` - rebuilds `error.output` using the other object properties.
## Helper Methods
### `boomify(error, [options])`
Decorates an error with the **boom** properties where:
- `error` - the `Error` object to decorate.
- `options` - optional object with the following optional settings:
- `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set.
- `message` - error message string. If the error already has a message, the provided `message` is added as a prefix.
Defaults to no message.
- `override` - if `false`, the `error` provided is a **boom** object, and a `statusCode` or `message` are provided,
the values are ignored. Defaults to `true` (apply the provided `statusCode` and `message` options to the error
regardless of its type, `Error` or **boom** object).
Note: This method replaces the [`wrap()`](#wraperror-statuscode-message) and changes the default behavior to override
existing **boom** objects with the provided status code and message.
```js
var error = new Error('Unexpected input');
Boom.boomify(error, { statusCode: 400 });
```
### `wrap(error, [statusCode], [message])`
Note: This method is deprecated.
Decorates an error with the **boom** properties where:
- `error` - the error object to wrap. If `error` is already a **boom** object, returns back the same object.
- `statusCode` - optional HTTP status code. Defaults to `500`.
- `message` - optional message string. If the error already has a message, it adds the message as a prefix.
Defaults to no message.
```js
var error = new Error('Unexpected input');
Boom.wrap(error, 400);
```
### `create(statusCode, [message], [data])`
Generates an `Error` object with the **boom** decorations where:
- `statusCode` - an HTTP error code number. Must be greater or equal 400.
- `message` - optional message string.
- `data` - additional error data set to `error.data` property.
```js
var error = Boom.create(400, 'Bad request', { timestamp: Date.now() });
```
## HTTP 4xx Errors
### `Boom.badRequest([message], [data])`
Returns a 400 Bad Request error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.badRequest('invalid query');
```
Generates the following response payload:
```json
{
"statusCode": 400,
"error": "Bad Request",
"message": "invalid query"
}
```
### `Boom.unauthorized([message], [scheme], [attributes])`
Returns a 401 Unauthorized error where:
- `message` - optional message.
- `scheme` can be one of the following:
- an authentication scheme name
- an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header.
- `attributes` - an object of values to use while setting the 'WWW-Authenticate' header. This value is only used
when `scheme` is a string, otherwise it is ignored. Every key/value pair will be included in the
'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the `attributes` key. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null.
`null` and `undefined` will be replaced with an empty string. If `attributes` is set, `message` will be used as
the 'error' segment of the 'WWW-Authenticate' header. If `message` is unset, the 'error' segment of the header
will not be present and `isMissing` will be true on the error object.
If either `scheme` or `attributes` are set, the resultant `Boom` object will have the 'WWW-Authenticate' header set for the response.
```js
Boom.unauthorized('invalid password');
```
Generates the following response:
```json
"payload": {
"statusCode": 401,
"error": "Unauthorized",
"message": "invalid password"
},
"headers" {}
```
```js
Boom.unauthorized('invalid password', 'sample');
```
Generates the following response:
```json
"payload": {
"statusCode": 401,
"error": "Unauthorized",
"message": "invalid password",
"attributes": {
"error": "invalid password"
}
},
"headers" {
"WWW-Authenticate": "sample error=\"invalid password\""
}
```
```js
Boom.unauthorized(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4=');
```
Generates the following response:
```json
"payload": {
"statusCode": 401,
"error": "Unauthorized",
"attributes": "VGhpcyBpcyBhIHRlc3QgdG9rZW4="
},
"headers" {
"WWW-Authenticate": "Negotiate VGhpcyBpcyBhIHRlc3QgdG9rZW4="
}
```
```js
Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' });
```
Generates the following response:
```json
"payload": {
"statusCode": 401,
"error": "Unauthorized",
"message": "invalid password",
"attributes": {
"error": "invalid password",
"ttl": 0,
"cache": "",
"foo": "bar"
}
},
"headers" {
"WWW-Authenticate": "sample ttl=\"0\", cache=\"\", foo=\"bar\", error=\"invalid password\""
}
```
### `Boom.paymentRequired([message], [data])`
Returns a 402 Payment Required error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.paymentRequired('bandwidth used');
```
Generates the following response payload:
```json
{
"statusCode": 402,
"error": "Payment Required",
"message": "bandwidth used"
}
```
### `Boom.forbidden([message], [data])`
Returns a 403 Forbidden error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.forbidden('try again some time');
```
Generates the following response payload:
```json
{
"statusCode": 403,
"error": "Forbidden",
"message": "try again some time"
}
```
### `Boom.notFound([message], [data])`
Returns a 404 Not Found error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.notFound('missing');
```
Generates the following response payload:
```json
{
"statusCode": 404,
"error": "Not Found",
"message": "missing"
}
```
### `Boom.methodNotAllowed([message], [data], [allow])`
Returns a 405 Method Not Allowed error where:
- `message` - optional message.
- `data` - optional additional error data.
- `allow` - optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header.
```js
Boom.methodNotAllowed('that method is not allowed');
```
Generates the following response payload:
```json
{
"statusCode": 405,
"error": "Method Not Allowed",
"message": "that method is not allowed"
}
```
### `Boom.notAcceptable([message], [data])`
Returns a 406 Not Acceptable error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.notAcceptable('unacceptable');
```
Generates the following response payload:
```json
{
"statusCode": 406,
"error": "Not Acceptable",
"message": "unacceptable"
}
```
### `Boom.proxyAuthRequired([message], [data])`
Returns a 407 Proxy Authentication Required error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.proxyAuthRequired('auth missing');
```
Generates the following response payload:
```json
{
"statusCode": 407,
"error": "Proxy Authentication Required",
"message": "auth missing"
}
```
### `Boom.clientTimeout([message], [data])`
Returns a 408 Request Time-out error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.clientTimeout('timed out');
```
Generates the following response payload:
```json
{
"statusCode": 408,
"error": "Request Time-out",
"message": "timed out"
}
```
### `Boom.conflict([message], [data])`
Returns a 409 Conflict error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.conflict('there was a conflict');
```
Generates the following response payload:
```json
{
"statusCode": 409,
"error": "Conflict",
"message": "there was a conflict"
}
```
### `Boom.resourceGone([message], [data])`
Returns a 410 Gone error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.resourceGone('it is gone');
```
Generates the following response payload:
```json
{
"statusCode": 410,
"error": "Gone",
"message": "it is gone"
}
```
### `Boom.lengthRequired([message], [data])`
Returns a 411 Length Required error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.lengthRequired('length needed');
```
Generates the following response payload:
```json
{
"statusCode": 411,
"error": "Length Required",
"message": "length needed"
}
```
### `Boom.preconditionFailed([message], [data])`
Returns a 412 Precondition Failed error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.preconditionFailed();
```
Generates the following response payload:
```json
{
"statusCode": 412,
"error": "Precondition Failed"
}
```
### `Boom.entityTooLarge([message], [data])`
Returns a 413 Request Entity Too Large error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.entityTooLarge('too big');
```
Generates the following response payload:
```json
{
"statusCode": 413,
"error": "Request Entity Too Large",
"message": "too big"
}
```
### `Boom.uriTooLong([message], [data])`
Returns a 414 Request-URI Too Large error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.uriTooLong('uri is too long');
```
Generates the following response payload:
```json
{
"statusCode": 414,
"error": "Request-URI Too Large",
"message": "uri is too long"
}
```
### `Boom.unsupportedMediaType([message], [data])`
Returns a 415 Unsupported Media Type error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.unsupportedMediaType('that media is not supported');
```
Generates the following response payload:
```json
{
"statusCode": 415,
"error": "Unsupported Media Type",
"message": "that media is not supported"
}
```
### `Boom.rangeNotSatisfiable([message], [data])`
Returns a 416 Requested Range Not Satisfiable error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.rangeNotSatisfiable();
```
Generates the following response payload:
```json
{
"statusCode": 416,
"error": "Requested Range Not Satisfiable"
}
```
### `Boom.expectationFailed([message], [data])`
Returns a 417 Expectation Failed error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.expectationFailed('expected this to work');
```
Generates the following response payload:
```json
{
"statusCode": 417,
"error": "Expectation Failed",
"message": "expected this to work"
}
```
### `Boom.teapot([message], [data])`
Returns a 418 I'm a Teapot error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.teapot('sorry, no coffee...');
```
Generates the following response payload:
```json
{
"statusCode": 418,
"error": "I'm a Teapot",
"message": "Sorry, no coffee..."
}
```
### `Boom.badData([message], [data])`
Returns a 422 Unprocessable Entity error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.badData('your data is bad and you should feel bad');
```
Generates the following response payload:
```json
{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "your data is bad and you should feel bad"
}
```
### `Boom.locked([message], [data])`
Returns a 423 Locked error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.locked('this resource has been locked');
```
Generates the following response payload:
```json
{
"statusCode": 423,
"error": "Locked",
"message": "this resource has been locked"
}
```
### `Boom.preconditionRequired([message], [data])`
Returns a 428 Precondition Required error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.preconditionRequired('you must supply an If-Match header');
```
Generates the following response payload:
```json
{
"statusCode": 428,
"error": "Precondition Required",
"message": "you must supply an If-Match header"
}
```
### `Boom.tooManyRequests([message], [data])`
Returns a 429 Too Many Requests error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.tooManyRequests('you have exceeded your request limit');
```
Generates the following response payload:
```json
{
"statusCode": 429,
"error": "Too Many Requests",
"message": "you have exceeded your request limit"
}
```
### `Boom.illegal([message], [data])`
Returns a 451 Unavailable For Legal Reasons error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.illegal('you are not permitted to view this resource for legal reasons');
```
Generates the following response payload:
```json
{
"statusCode": 451,
"error": "Unavailable For Legal Reasons",
"message": "you are not permitted to view this resource for legal reasons"
}
```
## HTTP 5xx Errors
All 500 errors hide your message from the end user. Your message is recorded in the server log.
### `Boom.badImplementation([message], [data])` - (*alias: `internal`*)
Returns a 500 Internal Server Error error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.badImplementation('terrible implementation');
```
Generates the following response payload:
```json
{
"statusCode": 500,
"error": "Internal Server Error",
"message": "An internal server error occurred"
}
```
### `Boom.notImplemented([message], [data])`
Returns a 501 Not Implemented error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.notImplemented('method not implemented');
```
Generates the following response payload:
```json
{
"statusCode": 501,
"error": "Not Implemented",
"message": "method not implemented"
}
```
### `Boom.badGateway([message], [data])`
Returns a 502 Bad Gateway error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.badGateway('that is a bad gateway');
```
Generates the following response payload:
```json
{
"statusCode": 502,
"error": "Bad Gateway",
"message": "that is a bad gateway"
}
```
### `Boom.serverUnavailable([message], [data])`
Returns a 503 Service Unavailable error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.serverUnavailable('unavailable');
```
Generates the following response payload:
```json
{
"statusCode": 503,
"error": "Service Unavailable",
"message": "unavailable"
}
```
### `Boom.gatewayTimeout([message], [data])`
Returns a 504 Gateway Time-out error where:
- `message` - optional message.
- `data` - optional additional error data.
```js
Boom.gatewayTimeout();
```
Generates the following response payload:
```json
{
"statusCode": 504,
"error": "Gateway Time-out"
}
```
## F.A.Q.
**Q** How do I include extra information in my responses? `output.payload` is missing `data`, what gives?
**A** There is a reason the values passed back in the response payloads are pretty locked down. It's mostly for security and to not leak any important information back to the client. This means you will need to put in a little more effort to include extra information about your custom error. Check out the ["Error transformation"](https://github.com/hapijs/hapi/blob/master/API.md#error-transformation) section in the hapi documentation.
---

View File

@ -1,457 +0,0 @@
'use strict';
// Load modules
const Hoek = require('hoek');
// Declare internals
const internals = {
STATUS_CODES: Object.setPrototypeOf({
'100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'205': 'Reset Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Moved Temporarily',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'307': 'Temporary Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Time-out',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Request Entity Too Large',
'414': 'Request-URI Too Large',
'415': 'Unsupported Media Type',
'416': 'Requested Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'425': 'Unordered Collection',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Time-out',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'509': 'Bandwidth Limit Exceeded',
'510': 'Not Extended',
'511': 'Network Authentication Required'
}, null)
};
exports.boomify = function (error, options) {
Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object');
options = options || {};
if (!error.isBoom) {
return internals.initialize(error, options.statusCode || 500, options.message);
}
if (options.override === false || // Defaults to true
(!options.statusCode && !options.message)) {
return error;
}
return internals.initialize(error, options.statusCode || error.output.statusCode, options.message);
};
exports.wrap = function (error, statusCode, message) {
Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object');
Hoek.assert(!error.isBoom || (!statusCode && !message), 'Cannot provide statusCode or message with boom error');
return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message));
};
exports.create = function (statusCode, message, data) {
return internals.create(statusCode, message, data, exports.create);
};
internals.create = function (statusCode, message, data, ctor) {
if (message instanceof Error) {
if (data) {
message.data = data;
}
return exports.wrap(message, statusCode);
}
const error = new Error(message ? message : undefined); // Avoids settings null message
Error.captureStackTrace(error, ctor); // Filter the stack to our external API
error.data = data || null;
internals.initialize(error, statusCode);
error.typeof = ctor;
return error;
};
internals.initialize = function (error, statusCode, message) {
const numberCode = parseInt(statusCode, 10);
Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'First argument must be a number (400+):', statusCode);
error.isBoom = true;
error.isServer = numberCode >= 500;
if (!error.hasOwnProperty('data')) {
error.data = null;
}
error.output = {
statusCode: numberCode,
payload: {},
headers: {}
};
error.reformat = internals.reformat;
if (!message &&
!error.message) {
error.reformat();
message = error.output.payload.error;
}
if (message) {
error.message = (message + (error.message ? ': ' + error.message : ''));
error.output.payload.message = error.message;
}
error.reformat();
return error;
};
internals.reformat = function () {
this.output.payload.statusCode = this.output.statusCode;
this.output.payload.error = internals.STATUS_CODES[this.output.statusCode] || 'Unknown';
if (this.output.statusCode === 500) {
this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user
}
else if (this.message) {
this.output.payload.message = this.message;
}
};
// 4xx Client Errors
exports.badRequest = function (message, data) {
return internals.create(400, message, data, exports.badRequest);
};
exports.unauthorized = function (message, scheme, attributes) { // Or function (message, wwwAuthenticate[])
const err = internals.create(401, message, undefined, exports.unauthorized);
if (!scheme) {
return err;
}
let wwwAuthenticate = '';
if (typeof scheme === 'string') {
// function (message, scheme, attributes)
wwwAuthenticate = scheme;
if (attributes || message) {
err.output.payload.attributes = {};
}
if (attributes) {
if (typeof attributes === 'string') {
wwwAuthenticate = wwwAuthenticate + ' ' + Hoek.escapeHeaderAttribute(attributes);
err.output.payload.attributes = attributes;
}
else {
const names = Object.keys(attributes);
for (let i = 0; i < names.length; ++i) {
const name = names[i];
if (i) {
wwwAuthenticate = wwwAuthenticate + ',';
}
let value = attributes[name];
if (value === null ||
value === undefined) { // Value can be zero
value = '';
}
wwwAuthenticate = wwwAuthenticate + ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"';
err.output.payload.attributes[name] = value;
}
}
}
if (message) {
if (attributes) {
wwwAuthenticate = wwwAuthenticate + ',';
}
wwwAuthenticate = wwwAuthenticate + ' error="' + Hoek.escapeHeaderAttribute(message) + '"';
err.output.payload.attributes.error = message;
}
else {
err.isMissing = true;
}
}
else {
// function (message, wwwAuthenticate[])
const wwwArray = scheme;
for (let i = 0; i < wwwArray.length; ++i) {
if (i) {
wwwAuthenticate = wwwAuthenticate + ', ';
}
wwwAuthenticate = wwwAuthenticate + wwwArray[i];
}
}
err.output.headers['WWW-Authenticate'] = wwwAuthenticate;
return err;
};
exports.paymentRequired = function (message, data) {
return internals.create(402, message, data, exports.paymentRequired);
};
exports.forbidden = function (message, data) {
return internals.create(403, message, data, exports.forbidden);
};
exports.notFound = function (message, data) {
return internals.create(404, message, data, exports.notFound);
};
exports.methodNotAllowed = function (message, data, allow) {
const err = internals.create(405, message, data, exports.methodNotAllowed);
if (typeof allow === 'string') {
allow = [allow];
}
if (Array.isArray(allow)) {
err.output.headers.Allow = allow.join(', ');
}
return err;
};
exports.notAcceptable = function (message, data) {
return internals.create(406, message, data, exports.notAcceptable);
};
exports.proxyAuthRequired = function (message, data) {
return internals.create(407, message, data, exports.proxyAuthRequired);
};
exports.clientTimeout = function (message, data) {
return internals.create(408, message, data, exports.clientTimeout);
};
exports.conflict = function (message, data) {
return internals.create(409, message, data, exports.conflict);
};
exports.resourceGone = function (message, data) {
return internals.create(410, message, data, exports.resourceGone);
};
exports.lengthRequired = function (message, data) {
return internals.create(411, message, data, exports.lengthRequired);
};
exports.preconditionFailed = function (message, data) {
return internals.create(412, message, data, exports.preconditionFailed);
};
exports.entityTooLarge = function (message, data) {
return internals.create(413, message, data, exports.entityTooLarge);
};
exports.uriTooLong = function (message, data) {
return internals.create(414, message, data, exports.uriTooLong);
};
exports.unsupportedMediaType = function (message, data) {
return internals.create(415, message, data, exports.unsupportedMediaType);
};
exports.rangeNotSatisfiable = function (message, data) {
return internals.create(416, message, data, exports.rangeNotSatisfiable);
};
exports.expectationFailed = function (message, data) {
return internals.create(417, message, data, exports.expectationFailed);
};
exports.teapot = function (message, data) {
return internals.create(418, message, data, exports.teapot);
};
exports.badData = function (message, data) {
return internals.create(422, message, data, exports.badData);
};
exports.locked = function (message, data) {
return internals.create(423, message, data, exports.locked);
};
exports.preconditionRequired = function (message, data) {
return internals.create(428, message, data, exports.preconditionRequired);
};
exports.tooManyRequests = function (message, data) {
return internals.create(429, message, data, exports.tooManyRequests);
};
exports.illegal = function (message, data) {
return internals.create(451, message, data, exports.illegal);
};
// 5xx Server Errors
exports.internal = function (message, data, statusCode) {
return internals.serverError(message, data, statusCode, exports.internal);
};
internals.serverError = function (message, data, statusCode, ctor) {
if (data instanceof Error &&
!data.isBoom) {
return exports.wrap(data, statusCode, message);
}
const error = internals.create(statusCode || 500, message, undefined, ctor);
error.data = data;
return error;
};
exports.notImplemented = function (message, data) {
return internals.serverError(message, data, 501, exports.notImplemented);
};
exports.badGateway = function (message, data) {
return internals.serverError(message, data, 502, exports.badGateway);
};
exports.serverUnavailable = function (message, data) {
return internals.serverError(message, data, 503, exports.serverUnavailable);
};
exports.gatewayTimeout = function (message, data) {
return internals.serverError(message, data, 504, exports.gatewayTimeout);
};
exports.badImplementation = function (message, data) {
const err = internals.serverError(message, data, 500, exports.badImplementation);
err.isDeveloperError = true;
return err;
};

View File

@ -1,29 +0,0 @@
{
"name": "boom",
"description": "HTTP-friendly error objects",
"version": "5.2.0",
"repository": "git://github.com/hapijs/boom",
"main": "lib/index.js",
"keywords": [
"error",
"http"
],
"engines": {
"node": ">=4.0.0"
},
"dependencies": {
"hoek": "4.x.x"
},
"devDependencies": {
"code": "4.x.x",
"lab": "14.x.x",
"markdown-toc": "0.12.x"
},
"scripts": {
"test": "lab -a code -t 100 -L -v",
"test-cov-html": "lab -a code -r html -o coverage.html -L",
"toc": "node generate-toc.js",
"version": "npm run toc && git add README.md"
},
"license": "BSD-3-Clause"
}

View File

@ -1,27 +0,0 @@
{
"name": "cryptiles",
"description": "General purpose crypto utilities",
"version": "3.1.2",
"repository": "git://github.com/hapijs/cryptiles",
"main": "lib/index.js",
"keywords": [
"cryptography",
"security",
"utilites"
],
"engines": {
"node": ">=4.0.0"
},
"dependencies": {
"boom": "5.x.x"
},
"devDependencies": {
"code": "4.x.x",
"lab": "13.x.x"
},
"scripts": {
"test": "lab -a code -t 100 -L",
"test-cov-html": "lab -a code -r html -o coverage.html"
},
"license": "BSD-3-Clause"
}

20
appasar/canary/node_modules/extend/.editorconfig generated vendored Normal file
View File

@ -0,0 +1,20 @@
root = true
[*]
indent_style = tab
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 150
[CHANGELOG.md]
indent_style = space
indent_size = 2
[*.json]
max_line_length = off
[Makefile]
max_line_length = off

View File

@ -4,7 +4,7 @@
"extends": "@ljharb",
"rules": {
"complexity": [2, 15],
"complexity": [2, 20],
"eqeqeq": [2, "allow-null"],
"func-name-matching": [1],
"max-depth": [1, 4],

View File

@ -157,14 +157,14 @@
"requireImportAlphabetized": false,
"requireSpaceBeforeObjectValues": true,
"requireSpaceBeforeDestructuredValues": true,
"requireSpaceBeforeObjectValues": true,
"requireSpaceBeforeDestructuredValues": true,
"disallowSpacesInsideTemplateStringPlaceholders": true,
"disallowArrayDestructuringReturn": false,
"disallowArrayDestructuringReturn": false,
"requireNewlineBeforeSingleStatementsInIf": false,
"requireNewlineBeforeSingleStatementsInIf": false,
"disallowUnusedVariables": true,

View File

@ -1 +0,0 @@
test

View File

@ -2,10 +2,13 @@ language: node_js
os:
- linux
node_js:
- "7.9"
- "6.10"
- "10.7"
- "9.11"
- "8.11"
- "7.10"
- "6.14"
- "5.12"
- "4.8"
- "4.9"
- "iojs-v3.3"
- "iojs-v2.5"
- "iojs-v1.8"
@ -13,10 +16,10 @@ node_js:
- "0.10"
- "0.8"
before_install:
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi'
- 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then npm install -g npm; fi'
- 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac'
- 'nvm install-latest-npm'
install:
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then nvm install 0.8 && npm install -g npm@1.3 && npm install -g npm@1.4.28 && npm install -g npm@2 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;'
- 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;'
script:
- 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi'
- 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi'
@ -28,10 +31,72 @@ env:
matrix:
fast_finish: true
include:
- node_js: "node"
- node_js: "lts/*"
env: PRETEST=true
- node_js: "node"
- node_js: "lts/*"
env: POSTTEST=true
- node_js: "4"
env: COVERAGE=true
- node_js: "10.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "10.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "9.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.6"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.5"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.4"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.3"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.2"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.1"
env: TEST=true ALLOW_FAILURE=true
- node_js: "8.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.7"
@ -50,6 +115,14 @@ matrix:
env: TEST=true ALLOW_FAILURE=true
- node_js: "7.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.13"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.12"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.11"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.10"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.9"
env: TEST=true ALLOW_FAILURE=true
- node_js: "6.8"
@ -94,6 +167,8 @@ matrix:
env: TEST=true ALLOW_FAILURE=true
- node_js: "5.0"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.8"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.7"
env: TEST=true ALLOW_FAILURE=true
- node_js: "4.6"
@ -150,30 +225,6 @@ matrix:
env: TEST=true ALLOW_FAILURE=true
- node_js: "0.4"
env: TEST=true ALLOW_FAILURE=true
##- node_js: "7"
#env: TEST=true
#os: osx
#- node_js: "6"
#env: TEST=true
#os: osx
#- node_js: "5"
#env: TEST=true
#os: osx
#- node_js: "4"
#env: TEST=true
#os: osx
#- node_js: "iojs"
#env: TEST=true
#os: osx
#- node_js: "0.12"
#env: TEST=true
#os: osx
#- node_js: "0.10"
#env: TEST=true
#os: osx
#- node_js: "0.8"
#env: TEST=true
#os: osx
allow_failures:
- os: osx
- env: TEST=true ALLOW_FAILURE=true

View File

@ -1,3 +1,9 @@
3.0.2 / 2018-07-19
==================
* [Fix] Prevent merging `__proto__` property (#48)
* [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`
* [Tests] up to `node` `v10.7`, `v9.11`, `v8.11`, `v7.10`, `v6.14`, `v4.9`; use `nvm install-latest-npm`
3.0.1 / 2017-04-27
==================
* [Fix] deep extending should work with a non-object (#46)

View File

@ -2,6 +2,8 @@
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var defineProperty = Object.defineProperty;
var gOPD = Object.getOwnPropertyDescriptor;
var isArray = function isArray(arr) {
if (typeof Array.isArray === 'function') {
@ -31,6 +33,35 @@ var isPlainObject = function isPlainObject(obj) {
return typeof key === 'undefined' || hasOwn.call(obj, key);
};
// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
var setProperty = function setProperty(target, options) {
if (defineProperty && options.name === '__proto__') {
defineProperty(target, options.name, {
enumerable: true,
configurable: true,
value: options.newValue,
writable: true
});
} else {
target[options.name] = options.newValue;
}
};
// Return undefined instead of __proto__ if '__proto__' is not an own property
var getProperty = function getProperty(obj, name) {
if (name === '__proto__') {
if (!hasOwn.call(obj, name)) {
return void 0;
} else if (gOPD) {
// In early versions of node, obj['__proto__'] is buggy when obj has
// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
return gOPD(obj, name).value;
}
}
return obj[name];
};
module.exports = function extend() {
var options, name, src, copy, copyIsArray, clone;
var target = arguments[0];
@ -55,8 +86,8 @@ module.exports = function extend() {
if (options != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
src = getProperty(target, name);
copy = getProperty(options, name);
// Prevent never-ending loop
if (target !== copy) {
@ -70,11 +101,11 @@ module.exports = function extend() {
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
// Don't bring in undefined values
} else if (typeof copy !== 'undefined') {
target[name] = copy;
setProperty(target, { name: name, newValue: copy });
}
}
}

View File

@ -1,7 +1,7 @@
{
"name": "extend",
"author": "Stefan Thomas <justmoon@members.fsf.org> (http://www.justmoon.net)",
"version": "3.0.1",
"version": "3.0.2",
"description": "Port of jQuery.extend for node.js and the browser",
"main": "index",
"scripts": {
@ -32,12 +32,11 @@
},
"dependencies": {},
"devDependencies": {
"tape": "^4.6.3",
"@ljharb/eslint-config": "^12.2.1",
"covert": "^1.1.0",
"eslint": "^4.19.1",
"jscs": "^3.0.7",
"eslint": "^3.19.0",
"@ljharb/eslint-config": "^11.0.0"
"tape": "^4.9.1"
},
"license": "MIT"
}

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