Changes of Linux stable v0.0.9

This commit is contained in:
root 2019-03-12 18:01:00 +01:00
parent 855c96e2ef
commit ceb9fdeb15
332 changed files with 32118 additions and 14594 deletions

View File

@ -4,28 +4,25 @@
// after startup, these constants will be merged into core module constants // after startup, these constants will be merged into core module constants
// since they are used in both locations (see app/Constants.js) // since they are used in both locations (see app/Constants.js)
var _require = require('./buildInfo'), const { releaseChannel } = require('./buildInfo');
releaseChannel = _require.releaseChannel; const { getSettings } = require('./appSettings');
var _require2 = require('./appSettings'), const settings = getSettings();
getSettings = _require2.getSettings;
var settings = getSettings();
function capitalizeFirstLetter(s) { function capitalizeFirstLetter(s) {
return s.charAt(0).toUpperCase() + s.slice(1); return s.charAt(0).toUpperCase() + s.slice(1);
} }
var APP_NAME = 'Discord' + (releaseChannel === 'stable' ? '' : capitalizeFirstLetter(releaseChannel)); const APP_NAME = 'Discord' + (releaseChannel === 'stable' ? '' : capitalizeFirstLetter(releaseChannel));
var APP_ID_BASE = 'com.squirrel'; const APP_ID_BASE = 'com.squirrel';
var APP_ID = APP_ID_BASE + '.' + APP_NAME + '.' + APP_NAME; const APP_ID = `${APP_ID_BASE}.${APP_NAME}.${APP_NAME}`;
var API_ENDPOINT = settings.get('API_ENDPOINT') || 'https://discordapp.com/api'; const API_ENDPOINT = settings.get('API_ENDPOINT') || 'https://discordapp.com/api';
var UPDATE_ENDPOINT = settings.get('UPDATE_ENDPOINT') || API_ENDPOINT; const UPDATE_ENDPOINT = settings.get('UPDATE_ENDPOINT') || API_ENDPOINT;
module.exports = { module.exports = {
APP_NAME: APP_NAME, APP_NAME,
APP_ID: APP_ID, APP_ID,
API_ENDPOINT: API_ENDPOINT, API_ENDPOINT,
UPDATE_ENDPOINT: UPDATE_ENDPOINT UPDATE_ENDPOINT
}; };

View File

@ -11,28 +11,7 @@
exports.replace = function (GPUSettings) { exports.replace = function (GPUSettings) {
// replacing module.exports directly would have no effect, since requires are cached // replacing module.exports directly would have no effect, since requires are cached
// so we mutate the existing object // so we mutate the existing object
var _iteratorNormalCompletion = true; for (const name of Object.keys(GPUSettings)) {
var _didIteratorError = false; exports[name] = GPUSettings[name];
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(GPUSettings)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var name = _step.value;
exports[name] = GPUSettings[name];
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
} }
}; };

View File

@ -18,7 +18,7 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var settings = void 0; let settings;
function init() { function init() {
settings = new _Settings2.default(paths.getUserData()); settings = new _Settings2.default(paths.getUserData());

View File

@ -27,7 +27,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function update(startMinimized, doneCallback, showCallback) { function update(startMinimized, doneCallback, showCallback) {
var settings = (0, _appSettings.getSettings)(); const settings = (0, _appSettings.getSettings)();
moduleUpdater.init(_Constants.UPDATE_ENDPOINT, settings, _buildInfo2.default); moduleUpdater.init(_Constants.UPDATE_ENDPOINT, settings, _buildInfo2.default);
splashScreen.initSplash(startMinimized); splashScreen.initSplash(startMinimized);

View File

@ -26,13 +26,22 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
// TODO: We should use Constant's APP_NAME, but only once // TODO: We should use Constant's APP_NAME, but only once
// we set up backwards compat with this. // we set up backwards compat with this.
var appName = _path2.default.basename(process.execPath, '.exe'); const appName = _path2.default.basename(process.execPath, '.exe');
var exePath = _electron.app.getPath('exe'); const exePath = _electron.app.getPath('exe');
var exeDir = _path2.default.dirname(exePath); const exeDir = _path2.default.dirname(exePath);
var iconPath = _path2.default.join(exeDir, 'discord.png'); const iconPath = _path2.default.join(exeDir, 'discord.png');
var autostartDir = _path2.default.join(_electron.app.getPath('appData'), 'autostart'); const autostartDir = _path2.default.join(_electron.app.getPath('appData'), 'autostart');
var autostartFileName = _path2.default.join(autostartDir, _electron.app.getName() + '-' + _buildInfo2.default.releaseChannel + '.desktop'); const autostartFileName = _path2.default.join(autostartDir, _electron.app.getName() + '-' + _buildInfo2.default.releaseChannel + '.desktop');
var desktopFile = '[Desktop Entry]\nType=Application\nExec=' + exePath + '\nHidden=false\nNoDisplay=false\nName=' + appName + '\nIcon=' + iconPath + '\nComment=Text and voice chat for gamers.\nX-GNOME-Autostart-enabled=true\n'; const desktopFile = `[Desktop Entry]
Type=Application
Exec=${exePath}
Hidden=false
NoDisplay=false
Name=${appName}
Icon=${iconPath}
Comment=Text and voice chat for gamers.
X-GNOME-Autostart-enabled=true
`;
function ensureDir() { function ensureDir() {
try { try {
@ -62,7 +71,7 @@ function update(callback) {
function isInstalled(callback) { function isInstalled(callback) {
try { try {
_fs2.default.stat(autostartFileName, function (err, stats) { _fs2.default.stat(autostartFileName, (err, stats) => {
if (err) { if (err) {
return callback(false); return callback(false);
} }

View File

@ -22,27 +22,25 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var settings = (0, _appSettings.getSettings)(); const settings = (0, _appSettings.getSettings)();
// TODO: We should use Constant's APP_NAME, but only once // TODO: We should use Constant's APP_NAME, but only once
// we set up backwards compat with this. // we set up backwards compat with this.
var appName = _path2.default.basename(process.execPath, '.exe'); const appName = _path2.default.basename(process.execPath, '.exe');
function install(callback) { function install(callback) {
var startMinimized = settings.get('START_MINIMIZED', false); const startMinimized = settings.get('START_MINIMIZED', false);
var _process = process, let { execPath } = process;
execPath = _process.execPath;
if (startMinimized) { if (startMinimized) {
execPath = execPath + ' --start-minimized'; execPath = `${execPath} --start-minimized`;
} }
var queue = [['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName, '/d', execPath]]; const queue = [['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName, '/d', execPath]];
windowsUtils.addToRegistry(queue, callback); windowsUtils.addToRegistry(queue, callback);
} }
function update(callback) { function update(callback) {
isInstalled(function (installed) { isInstalled(installed => {
if (installed) { if (installed) {
install(callback); install(callback);
} else { } else {
@ -52,18 +50,18 @@ function update(callback) {
} }
function isInstalled(callback) { function isInstalled(callback) {
var queryValue = ['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName]; const queryValue = ['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName];
queryValue.unshift('query'); queryValue.unshift('query');
windowsUtils.spawnReg(queryValue, function (error, stdout) { windowsUtils.spawnReg(queryValue, (error, stdout) => {
var doesOldKeyExist = stdout.indexOf(appName) >= 0; const doesOldKeyExist = stdout.indexOf(appName) >= 0;
callback(doesOldKeyExist); callback(doesOldKeyExist);
}); });
} }
function uninstall(callback) { function uninstall(callback) {
var queryValue = ['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName, '/f']; const queryValue = ['HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', appName, '/f'];
queryValue.unshift('delete'); queryValue.unshift('delete');
windowsUtils.spawnReg(queryValue, function (error, stdout) { windowsUtils.spawnReg(queryValue, (error, stdout) => {
callback(); callback();
}); });
} }

View File

@ -13,31 +13,29 @@ if (process.platform === 'linux') {
} }
} }
var _require = require('electron'), const { app, Menu } = require('electron');
app = _require.app,
Menu = _require.Menu;
var buildInfo = require('./buildInfo'); const buildInfo = require('./buildInfo');
app.setVersion(buildInfo.version); app.setVersion(buildInfo.version);
// expose releaseChannel to a global, since it's used by splash screen // expose releaseChannel to a global, since it's used by splash screen
global.releaseChannel = buildInfo.releaseChannel; global.releaseChannel = buildInfo.releaseChannel;
var errorHandler = require('./errorHandler'); const errorHandler = require('./errorHandler');
errorHandler.init(); errorHandler.init();
var paths = require('../common/paths'); const paths = require('../common/paths');
paths.init(buildInfo); paths.init(buildInfo);
global.modulePath = paths.getModulePath(); global.modulePath = paths.getModulePath();
var appSettings = require('./appSettings'); const appSettings = require('./appSettings');
appSettings.init(); appSettings.init();
var Constants = require('./Constants'); const Constants = require('./Constants');
var GPUSettings = require('./GPUSettings'); const GPUSettings = require('./GPUSettings');
var settings = appSettings.getSettings(); const settings = appSettings.getSettings();
// TODO: this is a copy of gpuSettings.getEnableHardwareAcceleration // TODO: this is a copy of gpuSettings.getEnableHardwareAcceleration
if (!settings.get('enableHardwareAcceleration', true)) { if (!settings.get('enableHardwareAcceleration', true)) {
app.disableHardwareAcceleration(); app.disableHardwareAcceleration();
@ -53,20 +51,17 @@ function hasArgvFlag(flag) {
return (process.argv || []).slice(1).includes(flag); return (process.argv || []).slice(1).includes(flag);
} }
console.log(Constants.APP_NAME + ' ' + app.getVersion()); console.log(`${Constants.APP_NAME} ${app.getVersion()}`);
var preventStartup = false; let preventStartup = false;
if (process.platform === 'win32') { if (process.platform === 'win32') {
// this tells Windows (in particular Windows 10) which icon to associate your app with, important for correctly // this tells Windows (in particular Windows 10) which icon to associate your app with, important for correctly
// pinning app to task bar. // pinning app to task bar.
app.setAppUserModelId(Constants.APP_ID); app.setAppUserModelId(Constants.APP_ID);
var _require2 = require('./squirrelUpdate'), const { handleStartupEvent } = require('./squirrelUpdate');
handleStartupEvent = _require2.handleStartupEvent;
// TODO: Isn't using argv[1] fragile? // TODO: Isn't using argv[1] fragile?
const squirrelCommand = process.argv[1];
var squirrelCommand = process.argv[1];
// TODO: Should `Discord` be a constant in this case? It's a protocol. // TODO: Should `Discord` be a constant in this case? It's a protocol.
// TODO: Is protocol case sensitive? // TODO: Is protocol case sensitive?
if (handleStartupEvent('Discord', app, squirrelCommand)) { if (handleStartupEvent('Discord', app, squirrelCommand)) {
@ -74,49 +69,51 @@ if (process.platform === 'win32') {
} }
} }
var singleInstance = require('./singleInstance'); const singleInstance = require('./singleInstance');
var appUpdater = require('./appUpdater'); const appUpdater = require('./appUpdater');
var moduleUpdater = require('../common/moduleUpdater'); const moduleUpdater = require('../common/moduleUpdater');
var splashScreen = require('./splashScreen'); const splashScreen = require('./splashScreen');
var autoStart = require('./autoStart'); const autoStart = require('./autoStart');
var requireNative = require('./requireNative'); const requireNative = require('./requireNative');
var coreModule = void 0; let coreModule;
function startUpdate() { function startUpdate() {
var startMinimized = hasArgvFlag('--start-minimized'); console.log('Starting updater.');
const startMinimized = hasArgvFlag('--start-minimized');
appUpdater.update(startMinimized, function () { appUpdater.update(startMinimized, () => {
try { try {
coreModule = requireNative('discord_desktop_core'); coreModule = requireNative('discord_desktop_core');
coreModule.startup({ coreModule.startup({
paths: paths, paths,
splashScreen: splashScreen, splashScreen,
moduleUpdater: moduleUpdater, moduleUpdater,
autoStart: autoStart, autoStart,
buildInfo: buildInfo, buildInfo,
appSettings: appSettings, appSettings,
Constants: Constants, Constants,
GPUSettings: GPUSettings GPUSettings
}); });
} catch (err) { } catch (err) {
return errorHandler.fatal(err); return errorHandler.fatal(err);
} }
}, function () { }, () => {
coreModule.setMainWindowVisible(!startMinimized); coreModule.setMainWindowVisible(!startMinimized);
}); });
} }
function startApp() { function startApp() {
console.log('Starting app.');
paths.cleanOldVersions(buildInfo); paths.cleanOldVersions(buildInfo);
var startupMenu = require('./startupMenu'); const startupMenu = require('./startupMenu');
Menu.setApplicationMenu(startupMenu); Menu.setApplicationMenu(startupMenu);
var multiInstance = hasArgvFlag('--multi-instance'); const multiInstance = hasArgvFlag('--multi-instance');
if (multiInstance) { if (multiInstance) {
startUpdate(); startUpdate();
} else { } else {
singleInstance.create(startUpdate, function (args) { singleInstance.create(startUpdate, args => {
// TODO: isn't relying on index 0 awfully fragile? // TODO: isn't relying on index 0 awfully fragile?
if (args != null && args.length > 0 && args[0] === '--squirrel-uninstall') { if (args != null && args.length > 0 && args[0] === '--squirrel-uninstall') {
app.quit(); app.quit();
@ -136,7 +133,6 @@ if (preventStartup) {
console.log('Startup prevented.'); console.log('Startup prevented.');
// TODO: shouldn't we exit out? // TODO: shouldn't we exit out?
} else { } else {
console.log('Starting updater.');
if (app.isReady()) { if (app.isReady()) {
startApp(); startApp();
} else { } else {

View File

@ -10,7 +10,7 @@ var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var buildInfo = require(_path2.default.join(process.resourcesPath, 'build_info.json')); const buildInfo = require(_path2.default.join(process.resourcesPath, 'build_info.json'));
exports.default = buildInfo; exports.default = buildInfo;
module.exports = exports['default']; module.exports = exports['default'];

View File

@ -1,15 +1,14 @@
[ [
"Leeeeeeroy jenkins!", "Upsorbing the Contents",
"Readying the felines.", "Additive Parsing the Load",
"Ensuring dankest memes.", "Commence Monosaturated Goodening",
"Recruiting robot hamsters.", "Kick Off the Multi-Core Widening",
"Getting dunked.", "Bastening the Game Turkey",
"Summoning unnecessarily dramatic encounters.", "Abstracting the Rummage Disc",
"Procedurally generating buttons.", "Undecerealenizing the Process",
"Preparing for a team fight.", "Postrefragmenting the Widget Layer",
"Buffing before the raid.", "Satisfying the Constraints",
"Top decking lethal.", "Abnoramalzing Some of the Matrices",
"Reloading the R8.", "Optimizing the People",
"Constructing additional pylons.", "Proclaigerizing the Network"
"Unbenching the Kench."
] ]

View File

@ -14,9 +14,9 @@ function isErrorSafeToSuppress(error) {
} }
function init() { function init() {
process.on('uncaughtException', function (error) { process.on('uncaughtException', error => {
var stack = error.stack ? error.stack : String(error); const stack = error.stack ? error.stack : String(error);
var message = 'Uncaught exception:\n ' + stack; const message = `Uncaught exception:\n ${stack}`;
console.warn(message); console.warn(message);
if (!isErrorSafeToSuppress(error)) { if (!isErrorSafeToSuppress(error)) {
@ -32,7 +32,7 @@ function fatal(err) {
type: 'error', type: 'error',
message: 'A fatal Javascript error occured', message: 'A fatal Javascript error occured',
detail: err && err.stack ? err.stack : String(err) detail: err && err.stack ? err.stack : String(err)
}, function () { }, () => {
_electron.app.quit(); _electron.app.quit();
}); });
} }

View File

@ -4,8 +4,6 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _events = require('events'); var _events = require('events');
var _squirrelUpdate = require('./squirrelUpdate'); var _squirrelUpdate = require('./squirrelUpdate');
@ -22,23 +20,15 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function versionParse(verString) { function versionParse(verString) {
return verString.split('.').map(function (i) { return verString.split('.').map(i => parseInt(i));
return parseInt(i);
});
} }
function versionNewer(verA, verB) { function versionNewer(verA, verB) {
var i = 0; let i = 0;
while (true) { while (true) {
var a = verA[i]; const a = verA[i];
var b = verB[i]; const b = verB[i];
i++; i++;
if (a === undefined) { if (a === undefined) {
return false; return false;
@ -53,168 +43,131 @@ function versionNewer(verA, verB) {
} }
} }
var AutoUpdaterWin32 = function (_EventEmitter) { class AutoUpdaterWin32 extends _events.EventEmitter {
_inherits(AutoUpdaterWin32, _EventEmitter); constructor() {
super();
function AutoUpdaterWin32() { this.updateUrl = null;
_classCallCheck(this, AutoUpdaterWin32); this.updateVersion = null;
var _this = _possibleConstructorReturn(this, (AutoUpdaterWin32.__proto__ || Object.getPrototypeOf(AutoUpdaterWin32)).call(this));
_this.updateUrl = null;
_this.updateVersion = null;
return _this;
} }
_createClass(AutoUpdaterWin32, [{ setFeedURL(updateUrl) {
key: 'setFeedURL', this.updateUrl = updateUrl;
value: function setFeedURL(updateUrl) { }
this.updateUrl = updateUrl;
quitAndInstall() {
if (squirrelUpdate.updateExistsSync()) {
squirrelUpdate.restart(_electron.app, this.updateVersion || _electron.app.getVersion());
} else {
require('auto-updater').quitAndInstall();
} }
}, { }
key: 'quitAndInstall',
value: function quitAndInstall() { downloadAndInstallUpdate(callback) {
if (squirrelUpdate.updateExistsSync()) { squirrelUpdate.spawnUpdateInstall(this.updateUrl, progress => {
squirrelUpdate.restart(_electron.app, this.updateVersion || _electron.app.getVersion()); this.emit('update-progress', progress);
} else { }).catch(err => callback(err)).then(() => callback());
require('auto-updater').quitAndInstall(); }
}
checkForUpdates() {
if (this.updateUrl == null) {
throw new Error('Update URL is not set');
} }
}, {
key: 'downloadAndInstallUpdate',
value: function downloadAndInstallUpdate(callback) {
var _this2 = this;
squirrelUpdate.spawnUpdateInstall(this.updateUrl, function (progress) { this.emit('checking-for-update');
_this2.emit('update-progress', progress);
}).catch(function (err) { if (!squirrelUpdate.updateExistsSync()) {
return callback(err); this.emit('update-not-available');
}).then(function () { return;
return callback();
});
} }
}, {
key: 'checkForUpdates',
value: function checkForUpdates() {
var _this3 = this;
if (this.updateUrl == null) { squirrelUpdate.spawnUpdate(['--check', this.updateUrl], (error, stdout) => {
throw new Error('Update URL is not set'); if (error != null) {
} this.emit('error', error);
this.emit('checking-for-update');
if (!squirrelUpdate.updateExistsSync()) {
this.emit('update-not-available');
return; return;
} }
squirrelUpdate.spawnUpdate(['--check', this.updateUrl], function (error, stdout) { try {
if (error != null) { // Last line of the output is JSON details about the releases
_this3.emit('error', error); const json = stdout.trim().split('\n').pop();
const releasesFound = JSON.parse(json).releasesToApply;
if (releasesFound == null || releasesFound.length == 0) {
this.emit('update-not-available');
return; return;
} }
try { const update = releasesFound.pop();
// Last line of the output is JSON details about the releases this.emit('update-available');
var json = stdout.trim().split('\n').pop(); this.downloadAndInstallUpdate(error => {
var releasesFound = JSON.parse(json).releasesToApply; if (error != null) {
if (releasesFound == null || releasesFound.length == 0) { this.emit('error', error);
_this3.emit('update-not-available');
return; return;
} }
var update = releasesFound.pop(); this.updateVersion = update.version;
_this3.emit('update-available');
_this3.downloadAndInstallUpdate(function (error) {
if (error != null) {
_this3.emit('error', error);
return;
}
_this3.updateVersion = update.version; this.emit('update-downloaded', {}, update.release, update.version, new Date(), this.updateUrl, this.quitAndInstall.bind(this));
});
_this3.emit('update-downloaded', {}, update.release, update.version, new Date(), _this3.updateUrl, _this3.quitAndInstall.bind(_this3)); } catch (error) {
}); error.stdout = stdout;
} catch (error) { this.emit('error', error);
error.stdout = stdout; }
_this3.emit('error', error); });
} }
}); }
}
}]);
return AutoUpdaterWin32;
}(_events.EventEmitter);
// todo // todo
class AutoUpdaterLinux extends _events.EventEmitter {
constructor() {
var AutoUpdaterLinux = function (_EventEmitter2) { super();
_inherits(AutoUpdaterLinux, _EventEmitter2); this.updateUrl = null;
function AutoUpdaterLinux() {
_classCallCheck(this, AutoUpdaterLinux);
var _this4 = _possibleConstructorReturn(this, (AutoUpdaterLinux.__proto__ || Object.getPrototypeOf(AutoUpdaterLinux)).call(this));
_this4.updateUrl = null;
return _this4;
} }
_createClass(AutoUpdaterLinux, [{ setFeedURL(url) {
key: 'setFeedURL', this.updateUrl = url;
value: function setFeedURL(url) { }
this.updateUrl = url;
}
}, {
key: 'checkForUpdates',
value: function checkForUpdates() {
var _this5 = this;
var currVersion = versionParse(_electron.app.getVersion()); checkForUpdates() {
this.emit('checking-for-update'); const currVersion = versionParse(_electron.app.getVersion());
this.emit('checking-for-update');
_request2.default.get({ url: this.updateUrl, encoding: null }, function (error, response, body) { _request2.default.get({ url: this.updateUrl, encoding: null }, (error, response, body) => {
if (error) { if (error) {
console.error('[Updates] Error fetching ' + _this5.updateUrl + ': ' + error); console.error('[Updates] Error fetching ' + this.updateUrl + ': ' + error);
_this5.emit('error', error); this.emit('error', error);
return; return;
} }
if (response.statusCode === 204) { if (response.statusCode === 204) {
// you are up to date // you are up to date
_this5.emit('update-not-available'); this.emit('update-not-available');
} else if (response.statusCode === 200) { } else if (response.statusCode === 200) {
var latestVerStr = ''; let latestVerStr = '';
var latestVersion = []; let latestVersion = [];
try { try {
var latestMetadata = JSON.parse(body); const latestMetadata = JSON.parse(body);
latestVerStr = latestMetadata.name; latestVerStr = latestMetadata.name;
latestVersion = versionParse(latestVerStr); latestVersion = versionParse(latestVerStr);
} catch (e) {} } catch (e) {}
if (versionNewer(latestVersion, currVersion)) { if (versionNewer(latestVersion, currVersion)) {
console.log('[Updates] You are out of date!'); console.log('[Updates] You are out of date!');
// you need to update // you need to update
_this5.emit('update-manually', latestVerStr); this.emit('update-manually', latestVerStr);
} else {
console.log('[Updates] You are living in the future!');
_this5.emit('update-not-available');
}
} else { } else {
// something is wrong console.log('[Updates] You are living in the future!');
console.error('[Updates] Error: fetch returned: ' + response.statusCode); this.emit('update-not-available');
_this5.emit('update-not-available');
} }
}); } else {
} // something is wrong
}]); console.error(`[Updates] Error: fetch returned: ${response.statusCode}`);
this.emit('update-not-available');
}
});
}
}
return AutoUpdaterLinux; let autoUpdater;
}(_events.EventEmitter);
var autoUpdater = void 0;
// TODO // TODO
// events: checking-for-update, update-available, update-not-available, update-manually, update-downloaded, error // events: checking-for-update, update-available, update-not-available, update-manually, update-downloaded, error

View File

@ -1,11 +1,11 @@
'use strict'; 'use strict';
var buildInfo = require('./buildInfo'); const buildInfo = require('./buildInfo');
var paths = require('../common/paths'); const paths = require('../common/paths');
paths.init(buildInfo); paths.init(buildInfo);
var moduleUpdater = require('../common/moduleUpdater'); const moduleUpdater = require('../common/moduleUpdater');
moduleUpdater.initPathsOnly(buildInfo); moduleUpdater.initPathsOnly(buildInfo);
var requireNative = require('./requireNative'); const requireNative = require('./requireNative');
function getAppMode() { function getAppMode() {
if (process.argv && process.argv.includes('--overlay-host')) { if (process.argv && process.argv.includes('--overlay-host')) {
@ -15,7 +15,7 @@ function getAppMode() {
return 'app'; return 'app';
} }
var mode = getAppMode(); const mode = getAppMode();
if (mode === 'app') { if (mode === 'app') {
require('./bootstrap'); require('./bootstrap');
} else if (mode === 'overlay-host') { } else if (mode === 'overlay-host') {

View File

@ -7,11 +7,11 @@ Object.defineProperty(exports, "__esModule", {
// require('electron').remote.require('./installDevTools')() // require('electron').remote.require('./installDevTools')()
function installDevTools() { function installDevTools() {
console.log('Installing Devtron'); console.log(`Installing Devtron`);
var devtron = require('devtron'); const devtron = require('devtron');
devtron.uninstall(); devtron.uninstall();
devtron.install(); devtron.install();
console.log('Installed Devtron'); console.log(`Installed Devtron`);
} }
exports.default = installDevTools; exports.default = installDevTools;

View File

@ -7,11 +7,7 @@ Object.defineProperty(exports, "__esModule", {
var _electron = require('electron'); var _electron = require('electron');
exports.default = { exports.default = {
on: function on(event, callback) { on: (event, callback) => _electron.ipcMain.on(`DISCORD_${event}`, callback),
return _electron.ipcMain.on('DISCORD_' + event, callback); removeListener: (event, callback) => _electron.ipcMain.removeListener(`DISCORD_${event}`, callback)
},
removeListener: function removeListener(event, callback) {
return _electron.ipcMain.removeListener('DISCORD_' + event, callback);
}
}; };
module.exports = exports['default']; module.exports = exports['default'];

View File

@ -27,88 +27,75 @@ function _log(_msg) {
} }
function requestWithMethod(method, origOpts, origCallback) { function requestWithMethod(method, origOpts, origCallback) {
var _this = this;
if (typeof origOpts == 'string') { if (typeof origOpts == 'string') {
origOpts = { url: origOpts }; origOpts = { url: origOpts };
} }
var opts = _extends({}, origOpts, { method: method }); const opts = _extends({}, origOpts, { method });
var callback = void 0; let callback;
if (origCallback || opts.callback) { if (origCallback || opts.callback) {
var origOptsCallback = opts.callback; const origOptsCallback = opts.callback;
delete opts.callback; delete opts.callback;
callback = function callback() { callback = (...args) => {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (origCallback) { if (origCallback) {
origCallback.apply(_this, args); origCallback.apply(this, args);
} }
if (origOptsCallback) { if (origOptsCallback) {
origOptsCallback.apply(_this, args); origOptsCallback.apply(this, args);
} }
}; };
} }
var strictOpts = _extends({}, opts, { strictSSL: true }); const strictOpts = _extends({}, opts, { strictSSL: true });
var laxOpts = _extends({}, opts, { strictSSL: false }); const laxOpts = _extends({}, opts, { strictSSL: false });
var rv = new _events2.default(); const rv = new _events2.default();
if (callback) { if (callback) {
_log('have callback, so wrapping'); _log('have callback, so wrapping');
rv.on('response', function (response) { rv.on('response', response => {
var chunks = []; const chunks = [];
response.on('data', function (chunk) { response.on('data', chunk => chunks.push(chunk));
return chunks.push(chunk); response.on('end', () => {
});
response.on('end', function () {
callback(null, response, Buffer.concat(chunks)); callback(null, response, Buffer.concat(chunks));
}); });
}); });
rv.on('error', function (error) { rv.on('error', error => callback(error));
return callback(error);
});
} }
var requestTypes = [{ const requestTypes = [{
factory: function factory() { factory: function () {
return (0, _request2.default)(strictOpts); return (0, _request2.default)(strictOpts);
}, },
method: 'node_request_strict' method: 'node_request_strict'
}, { }, {
factory: function factory() { factory: function () {
var qs = _querystring2.default.stringify(strictOpts.qs); const qs = _querystring2.default.stringify(strictOpts.qs);
var nr = _electron.net.request(_extends({}, strictOpts, { url: strictOpts.url + '?' + qs })); const nr = _electron.net.request(_extends({}, strictOpts, { url: `${strictOpts.url}?${qs}` }));
nr.end(); nr.end();
return nr; return nr;
}, },
method: 'electron_net_request_strict' method: 'electron_net_request_strict'
}, { }, {
factory: function factory() { factory: function () {
return (0, _request2.default)(laxOpts); return (0, _request2.default)(laxOpts);
}, },
method: 'node_request_lax' method: 'node_request_lax'
}]; }];
function attempt(index) { function attempt(index) {
var _requestTypes$index = requestTypes[index], const { factory, method } = requestTypes[index];
factory = _requestTypes$index.factory, _log(`Attempt #${index + 1}: ${method}`);
method = _requestTypes$index.method; factory().on('response', response => {
_log(`${method} success! emitting response ${response}`);
_log('Attempt #' + (index + 1) + ': ' + method);
factory().on('response', function (response) {
_log(method + ' success! emitting response ' + response);
rv.emit('response', response); rv.emit('response', response);
}).on('error', function (error) { }).on('error', error => {
if (index + 1 < requestTypes.length) { if (index + 1 < requestTypes.length) {
_log(method + ' failure, trying next option'); _log(`${method} failure, trying next option`);
attempt(index + 1); attempt(index + 1);
} else { } else {
_log(method + ' failure, out of options'); _log(`${method} failure, out of options`);
rv.emit('error', error); rv.emit('error', error);
} }
}); });
@ -121,9 +108,7 @@ function requestWithMethod(method, origOpts, origCallback) {
// only supports get for now, since retrying is non-idempotent and // only supports get for now, since retrying is non-idempotent and
// we'd want to grovel the errors to make sure it's safe to retry // we'd want to grovel the errors to make sure it's safe to retry
var _arr = ['get']; for (const method of ['get']) {
for (var _i = 0; _i < _arr.length; _i++) {
var method = _arr[_i];
requestWithMethod[method] = requestWithMethod.bind(null, method); requestWithMethod[method] = requestWithMethod.bind(null, method);
} }

View File

@ -59,16 +59,14 @@ function deleteSocketFile(socketPath) {
function listenForArgumentsFromNewProcess(socketPath, callback) { function listenForArgumentsFromNewProcess(socketPath, callback) {
deleteSocketFile(socketPath); deleteSocketFile(socketPath);
var server = _net2.default.createServer(function (connection) { const server = _net2.default.createServer(connection => {
connection.on('data', function (data) { connection.on('data', data => {
var args = JSON.parse(data); const args = JSON.parse(data);
callback(args); callback(args);
}); });
}); });
server.listen(socketPath); server.listen(socketPath);
server.on('error', function (error) { server.on('error', error => console.error('Application server failed', error));
return console.error('Application server failed', error);
});
return server; return server;
} }
@ -82,8 +80,8 @@ function tryStart(socketPath, callback, otherAppFound) {
return; return;
} }
var client = _net2.default.connect({ path: socketPath }, function () { const client = _net2.default.connect({ path: socketPath }, () => {
client.write(JSON.stringify(process.argv.slice(1)), function () { client.write(JSON.stringify(process.argv.slice(1)), () => {
client.end(); client.end();
otherAppFound(); otherAppFound();
}); });
@ -92,7 +90,7 @@ function tryStart(socketPath, callback, otherAppFound) {
} }
function makeSocketPath() { function makeSocketPath() {
var name = _electron.app.getName(); let name = _electron.app.getName();
if (_buildInfo2.default.releaseChannel !== 'stable') { if (_buildInfo2.default.releaseChannel !== 'stable') {
name = _electron.app.getName() + _buildInfo2.default.releaseChannel; name = _electron.app.getName() + _buildInfo2.default.releaseChannel;
} }
@ -105,23 +103,24 @@ function makeSocketPath() {
} }
function create(startCallback, newProcessCallback) { function create(startCallback, newProcessCallback) {
var socketPath = makeSocketPath(); const socketPath = makeSocketPath();
tryStart(socketPath, function () { tryStart(socketPath, () => {
var server = listenForArgumentsFromNewProcess(socketPath, newProcessCallback); const server = listenForArgumentsFromNewProcess(socketPath, newProcessCallback);
_electron.app.on('will-quit', function () { _electron.app.on('will-quit', () => {
server.close(); server.close();
deleteSocketFile(socketPath); deleteSocketFile(socketPath);
}); });
_electron.app.on('will-exit', function () { _electron.app.on('will-exit', () => {
server.close(); server.close();
deleteSocketFile(socketPath); deleteSocketFile(socketPath);
}); });
startCallback(); startCallback();
}, function () { }, () => {
console.log('Another instance exists. Quitting.');
_electron.app.exit(0); _electron.app.exit(0);
}); });
} }

View File

@ -22507,44 +22507,38 @@ var _Progress2 = _interopRequireDefault(_Progress);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var VIDEO_REF = 'video'; const VIDEO_REF = 'video';
var DOWNLOAD_OPTIONS = [{ value: 'deb', label: 'Ubuntu (deb)' }, { value: 'tar.gz', label: 'Linux (tar.gz)' }, { value: 'nope', label: 'I\'ll figure it out' }]; const DOWNLOAD_OPTIONS = [{ value: 'deb', label: `Ubuntu (deb)` }, { value: 'tar.gz', label: `Linux (tar.gz)` }, { value: 'nope', label: `I'll figure it out` }];
var RELEASE_CHANNEL = _electron.remote.getGlobal('releaseChannel'); const RELEASE_CHANNEL = _electron.remote.getGlobal('releaseChannel');
var LINUX_DOWNLOAD_URL_BASE = 'https://discordapp.com/api/download/' + RELEASE_CHANNEL + '?platform=linux&format='; const LINUX_DOWNLOAD_URL_BASE = `https://discordapp.com/api/download/${RELEASE_CHANNEL}?platform=linux&format=`;
var ipcRenderer = { const ipcRenderer = {
send: function send(event) { send: (event, ...args) => _electron.ipcRenderer.send(`DISCORD_${event}`, ...args),
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { on: (event, callback) => _electron.ipcRenderer.on(`DISCORD_${event}`, callback),
args[_key - 1] = arguments[_key]; removeListener: (event, callback) => _electron.ipcRenderer.removeListener(`DISCORD_${event}`, callback)
}
return _electron.ipcRenderer.send.apply(_electron.ipcRenderer, ['DISCORD_' + event].concat(args));
},
on: function on(event, callback) {
return _electron.ipcRenderer.on('DISCORD_' + event, callback);
},
removeListener: function removeListener(event, callback) {
return _electron.ipcRenderer.removeListener('DISCORD_' + event, callback);
}
}; };
var Splash = _react2.default.createClass({ const Splash = _react2.default.createClass({
displayName: 'Splash', displayName: 'Splash',
setInterval: function setInterval(interval, callback) {
setInterval(interval, callback) {
this.clearInterval(); this.clearInterval();
this._interval = window.setInterval(callback, interval); this._interval = window.setInterval(callback, interval);
}, },
clearInterval: function clearInterval() {
clearInterval() {
if (this._interval) { if (this._interval) {
window.clearInterval(this._interval); window.clearInterval(this._interval);
this._interval = null; this._interval = null;
} }
}, },
componentWillUnmount: function componentWillUnmount() {
componentWillUnmount() {
this.clearInterval(); this.clearInterval();
}, },
getInitialState: function getInitialState() {
getInitialState() {
return { return {
quote: _quotes_copy2.default[Math.floor(Math.random() * _quotes_copy2.default.length)], quote: _quotes_copy2.default[Math.floor(Math.random() * _quotes_copy2.default.length)],
videoLoaded: false, videoLoaded: false,
@ -22553,39 +22547,46 @@ var Splash = _react2.default.createClass({
selectedDownload: 'deb' selectedDownload: 'deb'
}; };
}, },
componentDidMount: function componentDidMount() {
var _this = this;
componentDidMount() {
_reactDom2.default.findDOMNode(this.refs[VIDEO_REF]).addEventListener('loadeddata', this.handleVideoLoaded); _reactDom2.default.findDOMNode(this.refs[VIDEO_REF]).addEventListener('loadeddata', this.handleVideoLoaded);
this.setInterval(1000, this.updateCountdownSeconds); this.setInterval(1000, this.updateCountdownSeconds);
ipcRenderer.on('SPLASH_UPDATE_STATE', function (_e, state) { ipcRenderer.on('SPLASH_UPDATE_STATE', (_e, state) => {
_this.setState({ update: state }); this.setState({ update: state });
});
ipcRenderer.on('SPLASH_SCREEN_QUOTE', (_e, quote) => {
this.setState({ quote });
}); });
ipcRenderer.send('SPLASH_SCREEN_READY'); ipcRenderer.send('SPLASH_SCREEN_READY');
}, },
updateCountdownSeconds: function updateCountdownSeconds() {
updateCountdownSeconds() {
if (this.state.update.seconds > 0) { if (this.state.update.seconds > 0) {
var newUpdateState = this.state.update; const newUpdateState = this.state.update;
newUpdateState.seconds -= 1; newUpdateState.seconds -= 1;
this.setState({ update: newUpdateState }); this.setState({ update: newUpdateState });
} }
}, },
handleVideoLoaded: function handleVideoLoaded() {
handleVideoLoaded() {
this.setState({ videoLoaded: true }); this.setState({ videoLoaded: true });
}, },
handleDownloadChanged: function handleDownloadChanged(selection) {
handleDownloadChanged(selection) {
this.setState({ selectedDownload: selection.value }); this.setState({ selectedDownload: selection.value });
}, },
handleDownload: function handleDownload() {
handleDownload() {
if (this.state.selectedDownload != 'nope') { if (this.state.selectedDownload != 'nope') {
var url = LINUX_DOWNLOAD_URL_BASE + this.state.selectedDownload; const url = LINUX_DOWNLOAD_URL_BASE + this.state.selectedDownload;
_electron.shell.openExternal(url, { activate: true }); _electron.shell.openExternal(url, { activate: true });
} }
_electron.remote.app.quit(); _electron.remote.app.quit();
}, },
render: function render() {
var statusText = void 0; render() {
var progress = _react2.default.createElement( let statusText;
let progress = _react2.default.createElement(
'div', 'div',
{ className: 'progress-placeholder' }, { className: 'progress-placeholder' },
'\xA0' '\xA0'
@ -22634,7 +22635,7 @@ var Splash = _react2.default.createClass({
); );
break; break;
case 'update-manually': case 'update-manually':
var buttonText = this.state.selectedDownload != 'nope' ? 'Download' : 'Okay'; const buttonText = this.state.selectedDownload != 'nope' ? 'Download' : 'Okay';
return _react2.default.createElement( return _react2.default.createElement(
'div', 'div',
{ id: 'splash' }, { id: 'splash' },
@ -25705,7 +25706,7 @@ module.exports = require("electron");
/* 199 */ /* 199 */
/***/ (function(module, exports) { /***/ (function(module, exports) {
module.exports = ["Leeeeeeroy jenkins!","Readying the felines.","Ensuring dankest memes.","Recruiting robot hamsters.","Getting dunked.","Summoning unnecessarily dramatic encounters.","Procedurally generating buttons.","Preparing for a team fight.","Buffing before the raid.","Top decking lethal.","Reloading the R8.","Constructing additional pylons.","Unbenching the Kench."] module.exports = ["Upsorbing the Contents","Additive Parsing the Load","Commence Monosaturated Goodening","Kick Off the Multi-Core Widening","Bastening the Game Turkey","Abstracting the Rummage Disc","Undecerealenizing the Process","Postrefragmenting the Widget Layer","Satisfying the Constraints","Abnoramalzing Some of the Matrices","Optimizing the People","Proclaigerizing the Network"]
/***/ }), /***/ }),
/* 200 */ /* 200 */
@ -25724,19 +25725,15 @@ var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Progress = function Progress(_ref) { const Progress = ({ percent = 0 }) => _react2.default.createElement(
var _ref$percent = _ref.percent, "div",
percent = _ref$percent === undefined ? 0 : _ref$percent; { className: "progress" },
return _react2.default.createElement( _react2.default.createElement(
"div", "div",
{ className: "progress" }, { className: "progress-bar" },
_react2.default.createElement( _react2.default.createElement("div", { className: "complete", style: { width: `${percent}%` } })
"div", )
{ className: "progress-bar" }, );
_react2.default.createElement("div", { className: "complete", style: { width: percent + "%" } })
)
);
};
exports.default = Progress; exports.default = Progress;
module.exports = exports["default"]; module.exports = exports["default"];

View File

@ -31,73 +31,74 @@ var _ipcMain = require('./ipcMain');
var _ipcMain2 = _interopRequireDefault(_ipcMain); var _ipcMain2 = _interopRequireDefault(_ipcMain);
var _paths = require('../common/paths');
var paths = _interopRequireWildcard(_paths);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var UPDATE_TIMEOUT_WAIT = 10000; const UPDATE_TIMEOUT_WAIT = 10000;
var RETRY_CAP_SECONDS = 60; const RETRY_CAP_SECONDS = 60;
// citron note: atom seems to add about 50px height to the frame on mac but not windows // citron note: atom seems to add about 50px height to the frame on mac but not windows
// TODO: see if we can eliminate fudge by using useContentSize BrowserWindow option // TODO: see if we can eliminate fudge by using useContentSize BrowserWindow option
var LOADING_WINDOW_WIDTH = 300; const LOADING_WINDOW_WIDTH = 300;
var LOADING_WINDOW_HEIGHT = process.platform == 'darwin' ? 300 : 350; const LOADING_WINDOW_HEIGHT = process.platform == 'darwin' ? 300 : 350;
// TODO: addModulesListener events should use Module's constants // TODO: addModulesListener events should use Module's constants
var CHECKING_FOR_UPDATES = 'checking-for-updates'; const CHECKING_FOR_UPDATES = 'checking-for-updates';
var UPDATE_CHECK_FINISHED = 'update-check-finished'; const UPDATE_CHECK_FINISHED = 'update-check-finished';
var UPDATE_FAILURE = 'update-failure'; const UPDATE_FAILURE = 'update-failure';
var LAUNCHING = 'launching'; const LAUNCHING = 'launching';
var DOWNLOADING_MODULE = 'downloading-module'; const DOWNLOADING_MODULE = 'downloading-module';
var DOWNLOADING_UPDATES = 'downloading-updates'; const DOWNLOADING_UPDATES = 'downloading-updates';
var DOWNLOADING_MODULES_FINISHED = 'downloading-modules-finished'; const DOWNLOADING_MODULES_FINISHED = 'downloading-modules-finished';
var DOWNLOADING_MODULE_PROGRESS = 'downloading-module-progress'; const DOWNLOADING_MODULE_PROGRESS = 'downloading-module-progress';
var DOWNLOADED_MODULE = 'downloaded-module'; const DOWNLOADED_MODULE = 'downloaded-module';
var NO_PENDING_UPDATES = 'no-pending-updates'; const NO_PENDING_UPDATES = 'no-pending-updates';
var INSTALLING_MODULE = 'installing-module'; const INSTALLING_MODULE = 'installing-module';
var INSTALLING_UPDATES = 'installing-updates'; const INSTALLING_UPDATES = 'installing-updates';
var INSTALLED_MODULE = 'installed-module'; const INSTALLED_MODULE = 'installed-module';
var INSTALLING_MODULE_PROGRESS = 'installing-module-progress'; const INSTALLING_MODULE_PROGRESS = 'installing-module-progress';
var INSTALLING_MODULES_FINISHED = 'installing-modules-finished'; const INSTALLING_MODULES_FINISHED = 'installing-modules-finished';
var UPDATE_MANUALLY = 'update-manually'; const UPDATE_MANUALLY = 'update-manually';
var APP_SHOULD_LAUNCH = exports.APP_SHOULD_LAUNCH = 'APP_SHOULD_LAUNCH'; const APP_SHOULD_LAUNCH = exports.APP_SHOULD_LAUNCH = 'APP_SHOULD_LAUNCH';
var APP_SHOULD_SHOW = exports.APP_SHOULD_SHOW = 'APP_SHOULD_SHOW'; const APP_SHOULD_SHOW = exports.APP_SHOULD_SHOW = 'APP_SHOULD_SHOW';
var events = exports.events = new _events.EventEmitter(); const events = exports.events = new _events.EventEmitter();
function webContentsSend(win, event) { function webContentsSend(win, event, ...args) {
if (win != null && win.webContents != null) { if (win != null && win.webContents != null) {
var _win$webContents; win.webContents.send(`DISCORD_${event}`, ...args);
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
(_win$webContents = win.webContents).send.apply(_win$webContents, ['DISCORD_' + event].concat(args));
} }
} }
var splashWindow = void 0; let splashWindow;
var modulesListeners = void 0; let modulesListeners;
var updateTimeout = void 0; let updateTimeout;
var updateAttempt = void 0; let updateAttempt;
var splashState = void 0; let splashState;
var launchedMainWindow = void 0; let launchedMainWindow;
let quoteCachePath;
function initSplash() {
var startMinimized = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
function initSplash(startMinimized = false) {
modulesListeners = {}; modulesListeners = {};
splashState = {}; splashState = {};
launchedMainWindow = false; launchedMainWindow = false;
updateAttempt = 0; updateAttempt = 0;
addModulesListener(CHECKING_FOR_UPDATES, function () { addModulesListener(CHECKING_FOR_UPDATES, () => {
startUpdateTimeout(); startUpdateTimeout();
updateSplashState(CHECKING_FOR_UPDATES); updateSplashState(CHECKING_FOR_UPDATES);
}); });
addModulesListener(UPDATE_CHECK_FINISHED, function (succeeded, updateCount, manualRequired) { addModulesListener(UPDATE_CHECK_FINISHED, (succeeded, updateCount, manualRequired) => {
stopUpdateTimeout(); stopUpdateTimeout();
if (!succeeded) { if (!succeeded) {
scheduleUpdateCheck(); scheduleUpdateCheck();
@ -108,60 +109,53 @@ function initSplash() {
} }
}); });
addModulesListener(DOWNLOADING_MODULE, function (name, current, total) { addModulesListener(DOWNLOADING_MODULE, (name, current, total) => {
stopUpdateTimeout(); stopUpdateTimeout();
splashState = { current: current, total: total }; splashState = { current, total };
updateSplashState(DOWNLOADING_UPDATES); updateSplashState(DOWNLOADING_UPDATES);
}); });
addModulesListener(DOWNLOADING_MODULE_PROGRESS, function (name, progress) { addModulesListener(DOWNLOADING_MODULE_PROGRESS, (name, progress) => {
splashState.progress = progress; splashState.progress = progress;
updateSplashState(DOWNLOADING_UPDATES); updateSplashState(DOWNLOADING_UPDATES);
}); });
addModulesListener(DOWNLOADED_MODULE, function (name, current, total, succeeded) { addModulesListener(DOWNLOADED_MODULE, (name, current, total, succeeded) => delete splashState.progress);
return delete splashState.progress;
});
addModulesListener(DOWNLOADING_MODULES_FINISHED, function (succeeded, failed) { addModulesListener(DOWNLOADING_MODULES_FINISHED, (succeeded, failed) => {
if (failed > 0) { if (failed > 0) {
scheduleUpdateCheck(); scheduleUpdateCheck();
updateSplashState(UPDATE_FAILURE); updateSplashState(UPDATE_FAILURE);
} else { } else {
process.nextTick(function () { process.nextTick(() => moduleUpdater.quitAndInstallUpdates());
return moduleUpdater.quitAndInstallUpdates();
});
} }
}); });
addModulesListener(NO_PENDING_UPDATES, function () { addModulesListener(NO_PENDING_UPDATES, () => moduleUpdater.checkForUpdates());
return moduleUpdater.checkForUpdates();
});
addModulesListener(INSTALLING_MODULE, function (name, current, total) { addModulesListener(INSTALLING_MODULE, (name, current, total) => {
splashState = { current: current, total: total }; splashState = { current, total };
updateSplashState(INSTALLING_UPDATES); updateSplashState(INSTALLING_UPDATES);
}); });
addModulesListener(INSTALLED_MODULE, function (name, current, total, succeeded) { addModulesListener(INSTALLED_MODULE, (name, current, total, succeeded) => delete splashState.progress);
return delete splashState.progress;
});
addModulesListener(INSTALLING_MODULE_PROGRESS, function (name, progress) { addModulesListener(INSTALLING_MODULE_PROGRESS, (name, progress) => {
splashState.progress = progress; splashState.progress = progress;
updateSplashState(INSTALLING_UPDATES); updateSplashState(INSTALLING_UPDATES);
}); });
addModulesListener(INSTALLING_MODULES_FINISHED, function (succeeded, failed) { addModulesListener(INSTALLING_MODULES_FINISHED, (succeeded, failed) => moduleUpdater.checkForUpdates());
return moduleUpdater.checkForUpdates();
});
addModulesListener(UPDATE_MANUALLY, function (newVersion) { addModulesListener(UPDATE_MANUALLY, newVersion => {
splashState.newVersion = newVersion; splashState.newVersion = newVersion;
updateSplashState(UPDATE_MANUALLY); updateSplashState(UPDATE_MANUALLY);
}); });
launchSplashWindow(startMinimized); launchSplashWindow(startMinimized);
quoteCachePath = _path2.default.join(paths.getUserData(), 'quotes.json');
_ipcMain2.default.on('UPDATED_QUOTES', (_event, quotes) => cacheLatestQuotes(quotes));
} }
function destroySplash() { function destroySplash() {
@ -171,7 +165,7 @@ function destroySplash() {
if (splashWindow) { if (splashWindow) {
splashWindow.setSkipTaskbar(true); splashWindow.setSkipTaskbar(true);
// defer the window hiding for a short moment so it gets covered by the main window // defer the window hiding for a short moment so it gets covered by the main window
var _nukeWindow = function _nukeWindow() { const _nukeWindow = () => {
splashWindow.hide(); splashWindow.hide();
splashWindow.close(); splashWindow.close();
splashWindow = null; splashWindow = null;
@ -186,37 +180,14 @@ function addModulesListener(event, listener) {
} }
function removeModulesListeners() { function removeModulesListeners() {
var _iteratorNormalCompletion = true; for (const event of Object.keys(modulesListeners)) {
var _didIteratorError = false; moduleUpdater.events.removeListener(event, modulesListeners[event]);
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(modulesListeners)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var event = _step.value;
moduleUpdater.events.removeListener(event, modulesListeners[event]);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
} }
} }
function startUpdateTimeout() { function startUpdateTimeout() {
if (!updateTimeout) { if (!updateTimeout) {
updateTimeout = setTimeout(function () { updateTimeout = setTimeout(() => scheduleUpdateCheck(), UPDATE_TIMEOUT_WAIT);
return scheduleUpdateCheck();
}, UPDATE_TIMEOUT_WAIT);
} }
} }
@ -234,24 +205,25 @@ function updateSplashState(event) {
} }
function launchSplashWindow(startMinimized) { function launchSplashWindow(startMinimized) {
var windowConfig = { const windowConfig = {
width: LOADING_WINDOW_WIDTH, width: LOADING_WINDOW_WIDTH,
height: LOADING_WINDOW_HEIGHT, height: LOADING_WINDOW_HEIGHT,
transparent: false, transparent: false,
frame: false, frame: false,
resizable: false, resizable: false,
center: true, center: true,
show: false show: false,
webPreferences: {
nodeIntegration: true
}
}; };
splashWindow = new _electron.BrowserWindow(windowConfig); splashWindow = new _electron.BrowserWindow(windowConfig);
// prevent users from dropping links to navigate in splash window // prevent users from dropping links to navigate in splash window
splashWindow.webContents.on('will-navigate', function (e) { splashWindow.webContents.on('will-navigate', e => e.preventDefault());
return e.preventDefault();
});
splashWindow.webContents.on('new-window', function (e, windowURL) { splashWindow.webContents.on('new-window', (e, windowURL) => {
e.preventDefault(); e.preventDefault();
_electron.shell.openExternal(windowURL); _electron.shell.openExternal(windowURL);
// exit, but delay half a second because openExternal is about to fire // exit, but delay half a second because openExternal is about to fire
@ -261,7 +233,7 @@ function launchSplashWindow(startMinimized) {
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
// citron note: this causes a crash on quit while the window is open on osx // citron note: this causes a crash on quit while the window is open on osx
splashWindow.on('closed', function () { splashWindow.on('closed', () => {
splashWindow = null; splashWindow = null;
if (!launchedMainWindow) { if (!launchedMainWindow) {
// user has closed this window before we launched the app, so let's quit // user has closed this window before we launched the app, so let's quit
@ -270,7 +242,12 @@ function launchSplashWindow(startMinimized) {
}); });
} }
_ipcMain2.default.on('SPLASH_SCREEN_READY', function () { _ipcMain2.default.on('SPLASH_SCREEN_READY', () => {
let cachedQuote = chooseCachedQuote();
if (cachedQuote) {
webContentsSend(splashWindow, 'SPLASH_SCREEN_QUOTE', cachedQuote);
}
if (splashWindow && !startMinimized) { if (splashWindow && !startMinimized) {
splashWindow.show(); splashWindow.show();
} }
@ -278,7 +255,7 @@ function launchSplashWindow(startMinimized) {
moduleUpdater.installPendingUpdates(); moduleUpdater.installPendingUpdates();
}); });
var splashUrl = _url2.default.format({ const splashUrl = _url2.default.format({
protocol: 'file', protocol: 'file',
slashes: true, slashes: true,
pathname: _path2.default.join(__dirname, 'splash', 'index.html') pathname: _path2.default.join(__dirname, 'splash', 'index.html')
@ -297,11 +274,9 @@ function launchMainWindow() {
function scheduleUpdateCheck() { function scheduleUpdateCheck() {
// TODO: can we use backoff here? // TODO: can we use backoff here?
updateAttempt += 1; updateAttempt += 1;
var retryInSeconds = Math.min(updateAttempt * 10, RETRY_CAP_SECONDS); const retryInSeconds = Math.min(updateAttempt * 10, RETRY_CAP_SECONDS);
splashState.seconds = retryInSeconds; splashState.seconds = retryInSeconds;
setTimeout(function () { setTimeout(() => moduleUpdater.checkForUpdates(), retryInSeconds * 1000);
return moduleUpdater.checkForUpdates();
}, retryInSeconds * 1000);
} }
function focusWindow() { function focusWindow() {
@ -312,7 +287,22 @@ function focusWindow() {
function pageReady() { function pageReady() {
destroySplash(); destroySplash();
process.nextTick(function () { process.nextTick(() => events.emit(APP_SHOULD_SHOW));
return events.emit(APP_SHOULD_SHOW); }
function cacheLatestQuotes(quotes) {
_fs2.default.writeFile(quoteCachePath, JSON.stringify(quotes), e => {
if (e) {
console.warn('Failed updating quote cache with error: ', e);
}
}); });
}
function chooseCachedQuote() {
let cachedQuote = null;
try {
const cachedQuotes = JSON.parse(_fs2.default.readFileSync(quoteCachePath));
cachedQuote = cachedQuotes[Math.floor(Math.random() * cachedQuotes.length)];
} catch (_err) {}
return cachedQuote;
} }

View File

@ -38,68 +38,46 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// citron note: this assumes the execPath is in the format Discord/someVersion/Discord.exe // citron note: this assumes the execPath is in the format Discord/someVersion/Discord.exe
var appFolder = _path2.default.resolve(process.execPath, '..'); const appFolder = _path2.default.resolve(process.execPath, '..');
var rootFolder = _path2.default.resolve(appFolder, '..'); const rootFolder = _path2.default.resolve(appFolder, '..');
var exeName = _path2.default.basename(process.execPath); const exeName = _path2.default.basename(process.execPath);
var updateExe = _path2.default.join(rootFolder, 'Update.exe'); const updateExe = _path2.default.join(rootFolder, 'Update.exe');
// Specialized spawn function specifically used for spawning the updater in // Specialized spawn function specifically used for spawning the updater in
// update mode. Calls back with progress percentages. // update mode. Calls back with progress percentages.
// Returns Promise. // Returns Promise.
function spawnUpdateInstall(updateUrl, progressCallback) { function spawnUpdateInstall(updateUrl, progressCallback) {
return new Promise(function (resolve, reject) { return new Promise((resolve, reject) => {
var proc = _child_process2.default.spawn(updateExe, ['--update', updateUrl]); const proc = _child_process2.default.spawn(updateExe, ['--update', updateUrl]);
proc.on('error', reject); proc.on('error', reject);
proc.on('exit', function (code) { proc.on('exit', code => {
if (code !== 0) { if (code !== 0) {
return reject(new Error('Update failed with exit code ' + code)); return reject(new Error(`Update failed with exit code ${code}`));
} }
return resolve(); return resolve();
}); });
var lastProgress = -1; let lastProgress = -1;
function parseProgress() { function parseProgress() {
var lines = stdout.split(/\r?\n/); const lines = stdout.split(/\r?\n/);
if (lines.length === 1) return; if (lines.length === 1) return;
// return the last (possibly incomplete) line to stdout for parsing again // return the last (possibly incomplete) line to stdout for parsing again
stdout = lines.pop(); stdout = lines.pop();
var currentProgress = void 0; let currentProgress;
var _iteratorNormalCompletion = true; for (const line of lines) {
var _didIteratorError = false; if (!/^\d\d?$/.test(line)) continue;
var _iteratorError = undefined; const progress = Number(line);
// make sure that this number is steadily increasing
try { if (lastProgress > progress) continue;
for (var _iterator = lines[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { currentProgress = progress;
var line = _step.value;
if (!/^\d\d?$/.test(line)) continue;
var progress = Number(line);
// make sure that this number is steadily increasing
if (lastProgress > progress) continue;
currentProgress = progress;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
} }
if (currentProgress == null) return; if (currentProgress == null) return;
lastProgress = currentProgress; lastProgress = currentProgress;
progressCallback(Math.min(currentProgress, 100)); progressCallback(Math.min(currentProgress, 100));
} }
var stdout = ''; let stdout = '';
proc.stdout.on('data', function (chunk) { proc.stdout.on('data', chunk => {
stdout += String(chunk); stdout += String(chunk);
parseProgress(); parseProgress();
}); });
@ -116,17 +94,17 @@ function spawnUpdate(args, callback) {
// provided by Squirrel's Update.exe // provided by Squirrel's Update.exe
function createShortcuts(callback, updateOnly) { function createShortcuts(callback, updateOnly) {
// move icon out to a more stable location, to keep shortcuts from breaking as much // move icon out to a more stable location, to keep shortcuts from breaking as much
var icoSrc = _path2.default.join(appFolder, 'app.ico'); const icoSrc = _path2.default.join(appFolder, 'app.ico');
var icoDest = _path2.default.join(rootFolder, 'app.ico'); const icoDest = _path2.default.join(rootFolder, 'app.ico');
var icoForTarget = icoDest; let icoForTarget = icoDest;
try { try {
var ico = _fs2.default.readFileSync(icoSrc); const ico = _fs2.default.readFileSync(icoSrc);
_fs2.default.writeFileSync(icoDest, ico); _fs2.default.writeFileSync(icoDest, ico);
} catch (e) { } catch (e) {
// if we can't write there for some reason, just use the source. // if we can't write there for some reason, just use the source.
icoForTarget = icoSrc; icoForTarget = icoSrc;
} }
var createShortcutArgs = ['--createShortcut', exeName, '--setupIcon', icoForTarget]; const createShortcutArgs = ['--createShortcut', exeName, '--setupIcon', icoForTarget];
if (updateOnly) { if (updateOnly) {
createShortcutArgs.push('--updateOnly'); createShortcutArgs.push('--updateOnly');
} }
@ -135,7 +113,7 @@ function createShortcuts(callback, updateOnly) {
// Add a protocol registration for this application. // Add a protocol registration for this application.
function installProtocol(protocol, callback) { function installProtocol(protocol, callback) {
var queue = [['HKCU\\Software\\Classes\\' + protocol, '/ve', '/d', 'URL:' + protocol + ' Protocol'], ['HKCU\\Software\\Classes\\' + protocol, '/v', 'URL Protocol'], ['HKCU\\Software\\Classes\\' + protocol + '\\DefaultIcon', '/ve', '/d', '"' + process.execPath + '",-1'], ['HKCU\\Software\\Classes\\' + protocol + '\\shell\\open\\command', '/ve', '/d', '"' + process.execPath + '" --url -- "%1"']]; const queue = [['HKCU\\Software\\Classes\\' + protocol, '/ve', '/d', `URL:${protocol} Protocol`], ['HKCU\\Software\\Classes\\' + protocol, '/v', 'URL Protocol'], ['HKCU\\Software\\Classes\\' + protocol + '\\DefaultIcon', '/ve', '/d', '"' + process.execPath + '",-1'], ['HKCU\\Software\\Classes\\' + protocol + '\\shell\\open\\command', '/ve', '/d', `"${process.execPath}" --url -- "%1"`]];
windowsUtils.addToRegistry(queue, callback); windowsUtils.addToRegistry(queue, callback);
} }
@ -167,9 +145,9 @@ function uninstallProtocol(protocol, callback) {
function handleStartupEvent(protocol, app, squirrelCommand) { function handleStartupEvent(protocol, app, squirrelCommand) {
switch (squirrelCommand) { switch (squirrelCommand) {
case '--squirrel-install': case '--squirrel-install':
createShortcuts(function () { createShortcuts(() => {
autoStart.install(function () { autoStart.install(() => {
installProtocol(protocol, function () { installProtocol(protocol, () => {
terminate(app); terminate(app);
}); });
}); });
@ -177,9 +155,9 @@ function handleStartupEvent(protocol, app, squirrelCommand) {
return true; return true;
case '--squirrel-updated': case '--squirrel-updated':
updateShortcuts(function () { updateShortcuts(() => {
autoStart.update(function () { autoStart.update(() => {
installProtocol(protocol, function () { installProtocol(protocol, () => {
terminate(app); terminate(app);
}); });
}); });
@ -187,14 +165,10 @@ function handleStartupEvent(protocol, app, squirrelCommand) {
return true; return true;
case '--squirrel-uninstall': case '--squirrel-uninstall':
removeShortcuts(function () { removeShortcuts(() => {
autoStart.uninstall(function () { autoStart.uninstall(() => {
uninstallProtocol(protocol, function () { uninstallProtocol(protocol, () => {
singleInstance.pipeCommandLineArgs(function () { singleInstance.pipeCommandLineArgs(() => terminate(app), () => terminate(app));
return terminate(app);
}, function () {
return terminate(app);
});
}); });
}); });
}); });
@ -216,8 +190,8 @@ function updateExistsSync() {
// Restart app as the new version // Restart app as the new version
function restart(app, newVersion) { function restart(app, newVersion) {
app.once('will-quit', function () { app.once('will-quit', () => {
var execPath = _path2.default.resolve(rootFolder, 'app-' + newVersion + '/' + exeName); const execPath = _path2.default.resolve(rootFolder, `app-${newVersion}/${exeName}`);
_child_process2.default.spawn(execPath, [], { detached: true }); _child_process2.default.spawn(execPath, [], { detached: true });
}); });
app.quit(); app.quit();

View File

@ -10,9 +10,7 @@ exports.default = [{
label: 'Discord', label: 'Discord',
submenu: [{ submenu: [{
label: 'Quit', label: 'Quit',
click: function click() { click: () => _electron.app.quit(),
return _electron.app.quit();
},
accelerator: 'Command+Q' accelerator: 'Command+Q'
}] }]
}]; }];

View File

@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", {
var _electron = require('electron'); var _electron = require('electron');
var menu = require('./' + process.platform); const menu = require('./' + process.platform);
exports.default = _electron.Menu.buildFromTemplate(menu); exports.default = _electron.Menu.buildFromTemplate(menu);
module.exports = exports['default']; module.exports = exports['default'];

View File

@ -10,9 +10,7 @@ exports.default = [{
label: '&File', label: '&File',
submenu: [{ submenu: [{
label: '&Exit', label: '&Exit',
click: function click() { click: () => _electron.app.quit(),
return _electron.app.quit();
},
accelerator: 'Control+Q' accelerator: 'Control+Q'
}] }]
}]; }];

View File

@ -10,9 +10,7 @@ exports.default = [{
label: '&File', label: '&File',
submenu: [{ submenu: [{
label: '&Exit', label: '&Exit',
click: function click() { click: () => _electron.app.quit(),
return _electron.app.quit();
},
accelerator: 'Alt+F4' accelerator: 'Alt+F4'
}] }]
}]; }];

View File

@ -17,20 +17,20 @@ var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var regExe = process.env.SystemRoot ? _path2.default.join(process.env.SystemRoot, 'System32', 'reg.exe') : 'reg.exe'; const regExe = process.env.SystemRoot ? _path2.default.join(process.env.SystemRoot, 'System32', 'reg.exe') : 'reg.exe';
// Spawn a command and invoke the callback when it completes with an error // Spawn a command and invoke the callback when it completes with an error
// and the output from standard out. // and the output from standard out.
function spawn(command, args, callback) { function spawn(command, args, callback) {
var stdout = ''; let stdout = '';
var spawnedProcess = void 0; let spawnedProcess;
try { try {
// TODO: contrary to below, it should not throw any error // TODO: contrary to below, it should not throw any error
spawnedProcess = _child_process2.default.spawn(command, args); spawnedProcess = _child_process2.default.spawn(command, args);
} catch (err) { } catch (err) {
// Spawn can throw an error // Spawn can throw an error
process.nextTick(function () { process.nextTick(() => {
if (callback != null) { if (callback != null) {
callback(err, stdout); callback(err, stdout);
} }
@ -39,14 +39,14 @@ function spawn(command, args, callback) {
} }
// TODO: we need to specify the encoding for the data if we're going to concat it as a string // TODO: we need to specify the encoding for the data if we're going to concat it as a string
spawnedProcess.stdout.on('data', function (data) { spawnedProcess.stdout.on('data', data => {
stdout += data; stdout += data;
}); });
var err = null; let err = null;
// TODO: close event might not get called, we should // TODO: close event might not get called, we should
// callback on error https://nodejs.org/api/child_process.html#child_process_event_error // callback on error https://nodejs.org/api/child_process.html#child_process_event_error
spawnedProcess.on('error', function (err) { spawnedProcess.on('error', err => {
// TODO: there should always be an error // TODO: there should always be an error
if (err != null) { if (err != null) {
err = err; err = err;
@ -54,7 +54,7 @@ function spawn(command, args, callback) {
}); });
// TODO: don't listen to close, but listen to exit instead // TODO: don't listen to close, but listen to exit instead
spawnedProcess.on('close', function (code, signal) { spawnedProcess.on('close', (code, signal) => {
if (err === null && code !== 0) { if (err === null && code !== 0) {
err = new Error('Command failed: ' + (signal || code)); err = new Error('Command failed: ' + (signal || code));
} }
@ -80,10 +80,8 @@ function addToRegistry(queue, callback) {
return callback && callback(); return callback && callback();
} }
var args = queue.shift(); const args = queue.shift();
args.unshift('add'); args.unshift('add');
args.push('/f'); args.push('/f');
return spawnReg(args, function () { return spawnReg(args, () => addToRegistry(queue, callback));
return addToRegistry(queue, callback);
});
} }

View File

@ -4,24 +4,15 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// copied from discord_app/lib because including from there is broken. // copied from discord_app/lib because including from there is broken.
var Backoff = function () { class Backoff {
/** /**
* Create a backoff instance can automatically backoff retries. * Create a backoff instance can automatically backoff retries.
*/ */
function Backoff() { constructor(min = 500, max = null, jitter = true) {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 500;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var jitter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
_classCallCheck(this, Backoff);
this.min = min; this.min = min;
this.max = max != null ? max : min * 10; this.max = max != null ? max : min * 10;
this.jitter = jitter; this.jitter = jitter;
@ -34,94 +25,69 @@ var Backoff = function () {
/** /**
* Return the number of failures. * Return the number of failures.
*/ */
get fails() {
return this._fails;
}
/**
* Current backoff value in milliseconds.
*/
get current() {
return this._current;
}
_createClass(Backoff, [{ /**
key: 'succeed', * A callback is going to fire.
*/
get pending() {
return this._timeoutId != null;
}
/**
* Clear any pending callbacks and reset the backoff.
*/
succeed() {
this.cancel();
this._fails = 0;
this._current = this.min;
}
/** /**
* Clear any pending callbacks and reset the backoff. * Increment the backoff and schedule a callback if provided.
*/ */
value: function succeed() { fail(callback) {
this.cancel(); this._fails += 1;
this._fails = 0; let delay = this._current * 2;
this._current = this.min; if (this.jitter) {
delay *= Math.random();
} }
this._current = Math.min(this._current + delay, this.max);
/** if (callback != null) {
* Increment the backoff and schedule a callback if provided.
*/
}, {
key: 'fail',
value: function fail(callback) {
var _this = this;
this._fails += 1;
var delay = this._current * 2;
if (this.jitter) {
delay *= Math.random();
}
this._current = Math.min(this._current + delay, this.max);
if (callback != null) {
if (this._timeoutId != null) {
throw new Error('callback already pending');
}
this._timeoutId = setTimeout(function () {
try {
if (callback != null) {
callback();
}
} finally {
_this._timeoutId = null;
}
}, this._current);
}
return this._current;
}
/**
* Clear any pending callbacks.
*/
}, {
key: 'cancel',
value: function cancel() {
if (this._timeoutId != null) { if (this._timeoutId != null) {
clearTimeout(this._timeoutId); throw new Error('callback already pending');
this._timeoutId = null;
} }
this._timeoutId = setTimeout(() => {
try {
if (callback != null) {
callback();
}
} finally {
this._timeoutId = null;
}
}, this._current);
} }
}, { return this._current;
key: 'fails', }
get: function get() {
return this._fails; /**
* Clear any pending callbacks.
*/
cancel() {
if (this._timeoutId != null) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
} }
}
/** }
* Current backoff value in milliseconds.
*/
}, {
key: 'current',
get: function get() {
return this._current;
}
/**
* A callback is going to fire.
*/
}, {
key: 'pending',
get: function get() {
return this._timeoutId != null;
}
}]);
return Backoff;
}();
exports.default = Backoff; exports.default = Backoff;
module.exports = exports['default']; module.exports = exports['default'];

View File

@ -3,42 +3,27 @@
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
class FeatureFlags {
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); constructor() {
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var FeatureFlags = function () {
function FeatureFlags() {
_classCallCheck(this, FeatureFlags);
this.flags = new Set(); this.flags = new Set();
} }
_createClass(FeatureFlags, [{ getSupported() {
key: 'getSupported', return Array.from(this.flags);
value: function getSupported() { }
return Array.from(this.flags);
}
}, {
key: 'supports',
value: function supports(feature) {
return this.flags.has(feature);
}
}, {
key: 'declareSupported',
value: function declareSupported(feature) {
if (this.supports(feature)) {
console.error('Feature redeclared; is this a duplicate flag? ', feature);
return;
}
this.flags.add(feature); supports(feature) {
return this.flags.has(feature);
}
declareSupported(feature) {
if (this.supports(feature)) {
console.error('Feature redeclared; is this a duplicate flag? ', feature);
return;
} }
}]);
return FeatureFlags;
}();
this.flags.add(feature);
}
}
exports.default = FeatureFlags; exports.default = FeatureFlags;
module.exports = exports['default']; module.exports = exports['default'];

View File

@ -4,8 +4,6 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _fs = require('fs'); var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs); var _fs2 = _interopRequireDefault(_fs);
@ -16,14 +14,10 @@ var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// TODO: sync fs operations could cause slowdown and/or freezes, depending on usage // TODO: sync fs operations could cause slowdown and/or freezes, depending on usage
// if this is fine, remove this todo // if this is fine, remove this todo
var Settings = function () { class Settings {
function Settings(root) { constructor(root) {
_classCallCheck(this, Settings);
this.path = _path2.default.join(root, 'settings.json'); this.path = _path2.default.join(root, 'settings.json');
try { try {
this.lastSaved = _fs2.default.readFileSync(this.path); this.lastSaved = _fs2.default.readFileSync(this.path);
@ -35,54 +29,43 @@ var Settings = function () {
this.lastModified = this._lastModified(); this.lastModified = this._lastModified();
} }
_createClass(Settings, [{ _lastModified() {
key: '_lastModified', try {
value: function _lastModified() { return _fs2.default.statSync(this.path).mtime.getTime();
try { } catch (e) {
return _fs2.default.statSync(this.path).mtime.getTime(); return 0;
} catch (e) {
return 0;
}
} }
}, { }
key: 'get',
value: function get(key) {
var defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (this.settings.hasOwnProperty(key)) { get(key, defaultValue = false) {
return this.settings[key]; if (this.settings.hasOwnProperty(key)) {
} return this.settings[key];
return defaultValue;
} }
}, {
key: 'set', return defaultValue;
value: function set(key, value) { }
this.settings[key] = value;
set(key, value) {
this.settings[key] = value;
}
save() {
if (this.lastModified && this.lastModified !== this._lastModified()) {
console.warn('Not saving settings, it has been externally modified.');
return;
} }
}, {
key: 'save',
value: function save() {
if (this.lastModified && this.lastModified !== this._lastModified()) {
console.warn('Not saving settings, it has been externally modified.');
return;
}
try { try {
var toSave = JSON.stringify(this.settings, null, 2); const toSave = JSON.stringify(this.settings, null, 2);
if (this.lastSaved != toSave) { if (this.lastSaved != toSave) {
this.lastSaved = toSave; this.lastSaved = toSave;
_fs2.default.writeFileSync(this.path, toSave); _fs2.default.writeFileSync(this.path, toSave);
this.lastModified = this._lastModified(); this.lastModified = this._lastModified();
}
} catch (err) {
console.warn('Failed saving settings with error: ', err);
} }
} catch (err) {
console.warn('Failed saving settings with error: ', err);
} }
}]); }
}
return Settings;
}();
exports.default = Settings; exports.default = Settings;
module.exports = exports['default']; module.exports = exports['default'];

View File

@ -5,11 +5,11 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.events = exports.NO_PENDING_UPDATES = exports.INSTALLING_MODULE_PROGRESS = exports.INSTALLING_MODULE = exports.INSTALLING_MODULES_FINISHED = exports.DOWNLOADED_MODULE = exports.UPDATE_MANUALLY = exports.DOWNLOADING_MODULES_FINISHED = exports.DOWNLOADING_MODULE_PROGRESS = exports.DOWNLOADING_MODULE = exports.UPDATE_CHECK_FINISHED = exports.INSTALLED_MODULE = exports.CHECKING_FOR_UPDATES = undefined; exports.events = exports.NO_PENDING_UPDATES = exports.INSTALLING_MODULE_PROGRESS = exports.INSTALLING_MODULE = exports.INSTALLING_MODULES_FINISHED = exports.DOWNLOADED_MODULE = exports.UPDATE_MANUALLY = exports.DOWNLOADING_MODULES_FINISHED = exports.DOWNLOADING_MODULE_PROGRESS = exports.DOWNLOADING_MODULE = exports.UPDATE_CHECK_FINISHED = exports.INSTALLED_MODULE = exports.CHECKING_FOR_UPDATES = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; // Manages additional module installation and management.
// We add the module folder path to require() lookup paths here.
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // undocumented node API
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
exports.initPathsOnly = initPathsOnly; exports.initPathsOnly = initPathsOnly;
exports.init = init; exports.init = init;
@ -54,129 +54,88 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } const originalFs = require('original-fs');
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } class Events extends _events.EventEmitter {
emit(...args) {
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // Manages additional module installation and management. process.nextTick(() => super.emit.apply(this, args));
// We add the module folder path to require() lookup paths here.
// undocumented node API
var originalFs = require('original-fs');
var Events = function (_EventEmitter) {
_inherits(Events, _EventEmitter);
function Events() {
_classCallCheck(this, Events);
return _possibleConstructorReturn(this, (Events.__proto__ || Object.getPrototypeOf(Events)).apply(this, arguments));
} }
}
_createClass(Events, [{ class LogStream {
key: 'emit', constructor(logPath) {
value: function emit() {
var _this2 = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
process.nextTick(function () {
return _get(Events.prototype.__proto__ || Object.getPrototypeOf(Events.prototype), 'emit', _this2).apply(_this2, args);
});
}
}]);
return Events;
}(_events.EventEmitter);
var LogStream = function () {
function LogStream(logPath) {
_classCallCheck(this, LogStream);
try { try {
this.logStream = _fs2.default.createWriteStream(logPath, { flags: 'a' }); this.logStream = _fs2.default.createWriteStream(logPath, { flags: 'a' });
} catch (e) { } catch (e) {
console.error('Failed to create ' + logPath + ': ' + String(e)); console.error(`Failed to create ${logPath}: ${String(e)}`);
} }
} }
_createClass(LogStream, [{ log(message) {
key: 'log', message = `[Modules] ${message}`;
value: function log(message) { console.log(message);
message = '[Modules] ' + message; if (this.logStream) {
console.log(message); this.logStream.write(message);
if (this.logStream) { this.logStream.write('\r\n');
this.logStream.write(message);
this.logStream.write('\r\n');
}
} }
}, { }
key: 'end',
value: function end() {
if (this.logStream) {
this.logStream.end();
this.logStream = null;
}
}
}]);
return LogStream; end() {
}(); if (this.logStream) {
this.logStream.end();
this.logStream = null;
}
}
}
// events // events
const CHECKING_FOR_UPDATES = exports.CHECKING_FOR_UPDATES = 'checking-for-updates';
const INSTALLED_MODULE = exports.INSTALLED_MODULE = 'installed-module';
var CHECKING_FOR_UPDATES = exports.CHECKING_FOR_UPDATES = 'checking-for-updates'; const UPDATE_CHECK_FINISHED = exports.UPDATE_CHECK_FINISHED = 'update-check-finished';
var INSTALLED_MODULE = exports.INSTALLED_MODULE = 'installed-module'; const DOWNLOADING_MODULE = exports.DOWNLOADING_MODULE = 'downloading-module';
var UPDATE_CHECK_FINISHED = exports.UPDATE_CHECK_FINISHED = 'update-check-finished'; const DOWNLOADING_MODULE_PROGRESS = exports.DOWNLOADING_MODULE_PROGRESS = 'downloading-module-progress';
var DOWNLOADING_MODULE = exports.DOWNLOADING_MODULE = 'downloading-module'; const DOWNLOADING_MODULES_FINISHED = exports.DOWNLOADING_MODULES_FINISHED = 'downloading-modules-finished';
var DOWNLOADING_MODULE_PROGRESS = exports.DOWNLOADING_MODULE_PROGRESS = 'downloading-module-progress'; const UPDATE_MANUALLY = exports.UPDATE_MANUALLY = 'update-manually';
var DOWNLOADING_MODULES_FINISHED = exports.DOWNLOADING_MODULES_FINISHED = 'downloading-modules-finished'; const DOWNLOADED_MODULE = exports.DOWNLOADED_MODULE = 'downloaded-module';
var UPDATE_MANUALLY = exports.UPDATE_MANUALLY = 'update-manually'; const INSTALLING_MODULES_FINISHED = exports.INSTALLING_MODULES_FINISHED = 'installing-modules-finished';
var DOWNLOADED_MODULE = exports.DOWNLOADED_MODULE = 'downloaded-module'; const INSTALLING_MODULE = exports.INSTALLING_MODULE = 'installing-module';
var INSTALLING_MODULES_FINISHED = exports.INSTALLING_MODULES_FINISHED = 'installing-modules-finished'; const INSTALLING_MODULE_PROGRESS = exports.INSTALLING_MODULE_PROGRESS = 'installing-module-progress';
var INSTALLING_MODULE = exports.INSTALLING_MODULE = 'installing-module'; const NO_PENDING_UPDATES = exports.NO_PENDING_UPDATES = 'no-pending-updates';
var INSTALLING_MODULE_PROGRESS = exports.INSTALLING_MODULE_PROGRESS = 'installing-module-progress';
var NO_PENDING_UPDATES = exports.NO_PENDING_UPDATES = 'no-pending-updates';
// settings // settings
var ALWAYS_ALLOW_UPDATES = 'ALWAYS_ALLOW_UPDATES'; const ALWAYS_ALLOW_UPDATES = 'ALWAYS_ALLOW_UPDATES';
var SKIP_HOST_UPDATE = 'SKIP_HOST_UPDATE'; const SKIP_HOST_UPDATE = 'SKIP_HOST_UPDATE';
var SKIP_MODULE_UPDATE = 'SKIP_MODULE_UPDATE'; const SKIP_MODULE_UPDATE = 'SKIP_MODULE_UPDATE';
var ALWAYS_BOOTSTRAP_MODULES = 'ALWAYS_BOOTSTRAP_MODULES'; const ALWAYS_BOOTSTRAP_MODULES = 'ALWAYS_BOOTSTRAP_MODULES';
var USE_LOCAL_MODULE_VERSIONS = 'USE_LOCAL_MODULE_VERSIONS'; const USE_LOCAL_MODULE_VERSIONS = 'USE_LOCAL_MODULE_VERSIONS';
var request = require('../app_bootstrap/request'); const request = require('../app_bootstrap/request');
var REQUEST_TIMEOUT = 15000; const REQUEST_TIMEOUT = 15000;
var backoff = new _Backoff2.default(1000, 20000); const backoff = new _Backoff2.default(1000, 20000);
var events = exports.events = new Events(); const events = exports.events = new Events();
var logger = void 0; let logger;
var locallyInstalledModules = void 0; let locallyInstalledModules;
var moduleInstallPath = void 0; let moduleInstallPath;
var installedModulesFilePath = void 0; let installedModulesFilePath;
var moduleDownloadPath = void 0; let moduleDownloadPath;
var bootstrapping = void 0; let bootstrapping;
var hostUpdater = void 0; let hostUpdater;
var hostUpdateAvailable = void 0; let hostUpdateAvailable;
var skipHostUpdate = void 0; let skipHostUpdate;
var skipModuleUpdate = void 0; let skipModuleUpdate;
var checkingForUpdates = void 0; let checkingForUpdates;
var remoteBaseURL = void 0; let remoteBaseURL;
var remoteQuery = void 0; let remoteQuery;
var settings = void 0; let settings;
var remoteModuleVersions = void 0; let remoteModuleVersions;
var installedModules = void 0; let installedModules;
var download = void 0; let download;
var unzip = void 0; let unzip;
var newInstallInProgress = void 0; let newInstallInProgress;
var localModuleVersionsFilePath = void 0; let localModuleVersionsFilePath;
var updatable = void 0; let updatable;
var bootstrapManifestFilePath = void 0; let bootstrapManifestFilePath;
function initPathsOnly(_buildInfo) { function initPathsOnly(_buildInfo) {
if (locallyInstalledModules || moduleInstallPath) { if (locallyInstalledModules || moduleInstallPath) {
@ -201,9 +160,9 @@ function initPathsOnly(_buildInfo) {
} }
function init(_endpoint, _settings, _buildInfo) { function init(_endpoint, _settings, _buildInfo) {
var endpoint = _endpoint; const endpoint = _endpoint;
settings = _settings; settings = _settings;
var buildInfo = _buildInfo; const buildInfo = _buildInfo;
updatable = buildInfo.version != '0.0.0' && !buildInfo.debug || settings.get(ALWAYS_ALLOW_UPDATES); updatable = buildInfo.version != '0.0.0' && !buildInfo.debug || settings.get(ALWAYS_ALLOW_UPDATES);
initPathsOnly(buildInfo); initPathsOnly(buildInfo);
@ -242,21 +201,21 @@ function init(_endpoint, _settings, _buildInfo) {
failures: 0 failures: 0
}; };
logger.log('Modules initializing'); logger.log(`Modules initializing`);
logger.log('Distribution: ' + (locallyInstalledModules ? 'local' : 'remote')); logger.log(`Distribution: ${locallyInstalledModules ? 'local' : 'remote'}`);
logger.log('Host updates: ' + (skipHostUpdate ? 'disabled' : 'enabled')); logger.log(`Host updates: ${skipHostUpdate ? 'disabled' : 'enabled'}`);
logger.log('Module updates: ' + (skipModuleUpdate ? 'disabled' : 'enabled')); logger.log(`Module updates: ${skipModuleUpdate ? 'disabled' : 'enabled'}`);
if (!locallyInstalledModules) { if (!locallyInstalledModules) {
installedModulesFilePath = _path2.default.join(moduleInstallPath, 'installed.json'); installedModulesFilePath = _path2.default.join(moduleInstallPath, 'installed.json');
moduleDownloadPath = _path2.default.join(moduleInstallPath, 'pending'); moduleDownloadPath = _path2.default.join(moduleInstallPath, 'pending');
_mkdirp2.default.sync(moduleDownloadPath); _mkdirp2.default.sync(moduleDownloadPath);
logger.log('Module install path: ' + moduleInstallPath); logger.log(`Module install path: ${moduleInstallPath}`);
logger.log('Module installed file path: ' + installedModulesFilePath); logger.log(`Module installed file path: ${installedModulesFilePath}`);
logger.log('Module download path: ' + moduleDownloadPath); logger.log(`Module download path: ${moduleDownloadPath}`);
var failedLoadingInstalledModules = false; let failedLoadingInstalledModules = false;
try { try {
installedModules = JSON.parse(_fs2.default.readFileSync(installedModulesFilePath)); installedModules = JSON.parse(_fs2.default.readFileSync(installedModulesFilePath));
} catch (err) { } catch (err) {
@ -270,46 +229,32 @@ function init(_endpoint, _settings, _buildInfo) {
hostUpdater = require('../app_bootstrap/hostUpdater'); hostUpdater = require('../app_bootstrap/hostUpdater');
// TODO: hostUpdater constants // TODO: hostUpdater constants
hostUpdater.on('checking-for-update', function () { hostUpdater.on('checking-for-update', () => events.emit(CHECKING_FOR_UPDATES));
return events.emit(CHECKING_FOR_UPDATES); hostUpdater.on('update-available', () => hostOnUpdateAvailable());
}); hostUpdater.on('update-progress', progress => hostOnUpdateProgress(progress));
hostUpdater.on('update-available', function () { hostUpdater.on('update-not-available', () => hostOnUpdateNotAvailable());
return hostOnUpdateAvailable(); hostUpdater.on('update-manually', newVersion => hostOnUpdateManually(newVersion));
}); hostUpdater.on('update-downloaded', () => hostOnUpdateDownloaded());
hostUpdater.on('update-progress', function (progress) { hostUpdater.on('error', err => hostOnError(err));
return hostOnUpdateProgress(progress); let setFeedURL = hostUpdater.setFeedURL.bind(hostUpdater);
});
hostUpdater.on('update-not-available', function () {
return hostOnUpdateNotAvailable();
});
hostUpdater.on('update-manually', function (newVersion) {
return hostOnUpdateManually(newVersion);
});
hostUpdater.on('update-downloaded', function () {
return hostOnUpdateDownloaded();
});
hostUpdater.on('error', function (err) {
return hostOnError(err);
});
var setFeedURL = hostUpdater.setFeedURL.bind(hostUpdater);
remoteBaseURL = endpoint + '/modules/' + buildInfo.releaseChannel; remoteBaseURL = `${endpoint}/modules/${buildInfo.releaseChannel}`;
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
remoteQuery = { host_version: buildInfo.version }; remoteQuery = { host_version: buildInfo.version };
switch (process.platform) { switch (process.platform) {
case 'darwin': case 'darwin':
setFeedURL(endpoint + '/updates/' + buildInfo.releaseChannel + '?platform=osx&version=' + buildInfo.version); setFeedURL(`${endpoint}/updates/${buildInfo.releaseChannel}?platform=osx&version=${buildInfo.version}`);
remoteQuery.platform = 'osx'; remoteQuery.platform = 'osx';
break; break;
case 'win32': case 'win32':
// Squirrel for Windows can't handle query params // Squirrel for Windows can't handle query params
// https://github.com/Squirrel/Squirrel.Windows/issues/132 // https://github.com/Squirrel/Squirrel.Windows/issues/132
setFeedURL(endpoint + '/updates/' + buildInfo.releaseChannel); setFeedURL(`${endpoint}/updates/${buildInfo.releaseChannel}`);
remoteQuery.platform = 'win'; remoteQuery.platform = 'win';
break; break;
case 'linux': case 'linux':
setFeedURL(endpoint + '/updates/' + buildInfo.releaseChannel + '?platform=linux&version=' + buildInfo.version); setFeedURL(`${endpoint}/updates/${buildInfo.releaseChannel}?platform=linux&version=${buildInfo.version}`);
remoteQuery.platform = 'linux'; remoteQuery.platform = 'linux';
break; break;
} }
@ -317,35 +262,14 @@ function init(_endpoint, _settings, _buildInfo) {
function cleanDownloadedModules(installedModules) { function cleanDownloadedModules(installedModules) {
try { try {
var entries = _fs2.default.readdirSync(moduleDownloadPath) || []; const entries = _fs2.default.readdirSync(moduleDownloadPath) || [];
entries.forEach(function (entry) { entries.forEach(entry => {
var entryPath = _path2.default.join(moduleDownloadPath, entry); const entryPath = _path2.default.join(moduleDownloadPath, entry);
var isStale = true; let isStale = true;
var _iteratorNormalCompletion = true; for (const moduleName of Object.keys(installedModules)) {
var _didIteratorError = false; if (entryPath === installedModules[moduleName].updateZipfile) {
var _iteratorError = undefined; isStale = false;
break;
try {
for (var _iterator = Object.keys(installedModules)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var moduleName = _step.value;
if (entryPath === installedModules[moduleName].updateZipfile) {
isStale = false;
break;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
} }
} }
@ -360,19 +284,19 @@ function cleanDownloadedModules(installedModules) {
} }
function hostOnUpdateAvailable() { function hostOnUpdateAvailable() {
logger.log('Host update is available.'); logger.log(`Host update is available.`);
hostUpdateAvailable = true; hostUpdateAvailable = true;
events.emit(UPDATE_CHECK_FINISHED, true, 1, false); events.emit(UPDATE_CHECK_FINISHED, true, 1, false);
events.emit(DOWNLOADING_MODULE, 'host', 1, 1); events.emit(DOWNLOADING_MODULE, 'host', 1, 1);
} }
function hostOnUpdateProgress(progress) { function hostOnUpdateProgress(progress) {
logger.log('Host update progress: ' + progress + '%'); logger.log(`Host update progress: ${progress}%`);
events.emit(DOWNLOADING_MODULE_PROGRESS, 'host', progress); events.emit(DOWNLOADING_MODULE_PROGRESS, 'host', progress);
} }
function hostOnUpdateNotAvailable() { function hostOnUpdateNotAvailable() {
logger.log('Host is up to date.'); logger.log(`Host is up to date.`);
if (!skipModuleUpdate) { if (!skipModuleUpdate) {
checkForModuleUpdates(); checkForModuleUpdates();
} else { } else {
@ -381,7 +305,7 @@ function hostOnUpdateNotAvailable() {
} }
function hostOnUpdateManually(newVersion) { function hostOnUpdateManually(newVersion) {
logger.log('Host update is available. Manual update required!'); logger.log(`Host update is available. Manual update required!`);
hostUpdateAvailable = true; hostUpdateAvailable = true;
checkingForUpdates = false; checkingForUpdates = false;
events.emit(UPDATE_MANUALLY, newVersion); events.emit(UPDATE_MANUALLY, newVersion);
@ -389,14 +313,14 @@ function hostOnUpdateManually(newVersion) {
} }
function hostOnUpdateDownloaded() { function hostOnUpdateDownloaded() {
logger.log('Host update downloaded.'); logger.log(`Host update downloaded.`);
checkingForUpdates = false; checkingForUpdates = false;
events.emit(DOWNLOADED_MODULE, 'host', 1, 1, true); events.emit(DOWNLOADED_MODULE, 'host', 1, 1, true);
events.emit(DOWNLOADING_MODULES_FINISHED, 1, 0); events.emit(DOWNLOADING_MODULES_FINISHED, 1, 0);
} }
function hostOnError(err) { function hostOnError(err) {
logger.log('Host update failed: ' + err); logger.log(`Host update failed: ${err}`);
// [adill] osx unsigned builds will fire this code signing error inside setFeedURL and // [adill] osx unsigned builds will fire this code signing error inside setFeedURL and
// if we don't do anything about it hostUpdater.checkForUpdates() will never respond. // if we don't do anything about it hostUpdater.checkForUpdates() will never respond.
@ -430,33 +354,33 @@ function checkForUpdates() {
function getRemoteModuleName(name) { function getRemoteModuleName(name) {
if (process.platform === 'win32' && process.arch === 'x64') { if (process.platform === 'win32' && process.arch === 'x64') {
return name + '.x64'; return `${name}.x64`;
} }
return name; return name;
} }
function checkForModuleUpdates() { function checkForModuleUpdates() {
var query = _extends({}, remoteQuery, { _: Math.floor(Date.now() / 1000 / 60 / 5) }); const query = _extends({}, remoteQuery, { _: Math.floor(Date.now() / 1000 / 60 / 5) });
var url = remoteBaseURL + '/versions.json'; const url = `${remoteBaseURL}/versions.json`;
logger.log('Checking for module updates at ' + url); logger.log(`Checking for module updates at ${url}`);
request.get({ request.get({
url: url, url,
agent: false, agent: false,
encoding: null, encoding: null,
qs: query, qs: query,
timeout: REQUEST_TIMEOUT, timeout: REQUEST_TIMEOUT,
strictSSL: false strictSSL: false
}, function (err, response, body) { }, (err, response, body) => {
checkingForUpdates = false; checkingForUpdates = false;
if (!err && response.statusCode !== 200) { if (!err && response.statusCode !== 200) {
err = new Error('Non-200 response code: ' + response.statusCode); err = new Error(`Non-200 response code: ${response.statusCode}`);
} }
if (err) { if (err) {
logger.log('Failed fetching module versions: ' + String(err)); logger.log(`Failed fetching module versions: ${String(err)}`);
events.emit(UPDATE_CHECK_FINISHED, false, 0, false); events.emit(UPDATE_CHECK_FINISHED, false, 0, false);
return; return;
} }
@ -471,60 +395,35 @@ function checkForModuleUpdates() {
} }
} }
var updatesToDownload = []; const updatesToDownload = [];
var _iteratorNormalCompletion2 = true; for (const moduleName of Object.keys(installedModules)) {
var _didIteratorError2 = false; const installedModule = installedModules[moduleName];
var _iteratorError2 = undefined; const installed = installedModule.installedVersion;
if (installed === null) {
try { continue;
for (var _iterator2 = Object.keys(installedModules)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var moduleName = _step2.value;
var installedModule = installedModules[moduleName];
var installed = installedModule.installedVersion;
if (installed === null) {
continue;
}
var update = installedModule.updateVersion || 0;
var remote = remoteModuleVersions[getRemoteModuleName(moduleName)] || 0;
// TODO: strict equality?
if (installed != remote && update != remote) {
logger.log('Module update available: ' + moduleName + '@' + remote + ' [installed: ' + installed + ']');
updatesToDownload.push({ name: moduleName, version: remote });
}
} }
} catch (err) {
_didIteratorError2 = true; const update = installedModule.updateVersion || 0;
_iteratorError2 = err; const remote = remoteModuleVersions[getRemoteModuleName(moduleName)] || 0;
} finally { // TODO: strict equality?
try { if (installed != remote && update != remote) {
if (!_iteratorNormalCompletion2 && _iterator2.return) { logger.log(`Module update available: ${moduleName}@${remote} [installed: ${installed}]`);
_iterator2.return(); updatesToDownload.push({ name: moduleName, version: remote });
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
} }
} }
events.emit(UPDATE_CHECK_FINISHED, true, updatesToDownload.length, false); events.emit(UPDATE_CHECK_FINISHED, true, updatesToDownload.length, false);
if (updatesToDownload.length === 0) { if (updatesToDownload.length === 0) {
logger.log('No module updates available.'); logger.log(`No module updates available.`);
} else { } else {
updatesToDownload.forEach(function (e) { updatesToDownload.forEach(e => addModuleToDownloadQueue(e.name, e.version));
return addModuleToDownloadQueue(e.name, e.version);
});
} }
}); });
} }
function addModuleToDownloadQueue(name, version, authToken) { function addModuleToDownloadQueue(name, version, authToken) {
download.queue.push({ name: name, version: version, authToken: authToken }); download.queue.push({ name, version, authToken });
process.nextTick(function () { process.nextTick(() => processDownloadQueue());
return processDownloadQueue();
});
} }
function processDownloadQueue() { function processDownloadQueue() {
@ -533,53 +432,51 @@ function processDownloadQueue() {
download.active = true; download.active = true;
var queuedModule = download.queue[download.next]; const queuedModule = download.queue[download.next];
download.next += 1; download.next += 1;
events.emit(DOWNLOADING_MODULE, queuedModule.name, download.next, download.queue.length); events.emit(DOWNLOADING_MODULE, queuedModule.name, download.next, download.queue.length);
var totalBytes = 1; let totalBytes = 1;
var receivedBytes = 0; let receivedBytes = 0;
var progress = 0; let progress = 0;
var hasErrored = false; let hasErrored = false;
var url = remoteBaseURL + '/' + getRemoteModuleName(queuedModule.name) + '/' + queuedModule.version; const url = `${remoteBaseURL}/${getRemoteModuleName(queuedModule.name)}/${queuedModule.version}`;
logger.log('Fetching ' + queuedModule.name + '@' + queuedModule.version + ' from ' + url); logger.log(`Fetching ${queuedModule.name}@${queuedModule.version} from ${url}`);
var headers = {}; const headers = {};
if (queuedModule.authToken) { if (queuedModule.authToken) {
headers['Authorization'] = queuedModule.authToken; headers['Authorization'] = queuedModule.authToken;
} }
request.get({ request.get({
url: url, url,
agent: false, agent: false,
encoding: null, encoding: null,
followAllRedirects: true, followAllRedirects: true,
qs: remoteQuery, qs: remoteQuery,
timeout: REQUEST_TIMEOUT, timeout: REQUEST_TIMEOUT,
strictSSL: false, strictSSL: false,
headers: headers headers
}).on('error', function (err) { }).on('error', err => {
if (hasErrored) return; if (hasErrored) return;
hasErrored = true; hasErrored = true;
logger.log('Failed fetching ' + queuedModule.name + '@' + queuedModule.version + ': ' + String(err)); logger.log(`Failed fetching ${queuedModule.name}@${queuedModule.version}: ${String(err)}`);
finishModuleDownload(queuedModule.name, queuedModule.version, null, false); finishModuleDownload(queuedModule.name, queuedModule.version, null, false);
}).on('response', function (response) { }).on('response', response => {
totalBytes = response.headers['content-length'] || 1; totalBytes = response.headers['content-length'] || 1;
var moduleZipPath = _path2.default.join(moduleDownloadPath, queuedModule.name + '-' + queuedModule.version + '.zip'); const moduleZipPath = _path2.default.join(moduleDownloadPath, `${queuedModule.name}-${queuedModule.version}.zip`);
logger.log('Streaming ' + queuedModule.name + '@' + queuedModule.version + ' [' + totalBytes + ' bytes] to ' + moduleZipPath); logger.log(`Streaming ${queuedModule.name}@${queuedModule.version} [${totalBytes} bytes] to ${moduleZipPath}`);
var stream = _fs2.default.createWriteStream(moduleZipPath); const stream = _fs2.default.createWriteStream(moduleZipPath);
stream.on('finish', function () { stream.on('finish', () => finishModuleDownload(queuedModule.name, queuedModule.version, moduleZipPath, response.statusCode === 200));
return finishModuleDownload(queuedModule.name, queuedModule.version, moduleZipPath, response.statusCode === 200);
});
response.on('data', function (chunk) { response.on('data', chunk => {
receivedBytes += chunk.length; receivedBytes += chunk.length;
stream.write(chunk); stream.write(chunk);
var fraction = receivedBytes / totalBytes; const fraction = receivedBytes / totalBytes;
var newProgress = Math.min(Math.floor(100 * fraction), 100); const newProgress = Math.min(Math.floor(100 * fraction), 100);
if (progress != newProgress) { if (progress != newProgress) {
progress = newProgress; progress = newProgress;
events.emit(DOWNLOADING_MODULE_PROGRESS, queuedModule.name, progress); events.emit(DOWNLOADING_MODULE_PROGRESS, queuedModule.name, progress);
@ -589,14 +486,12 @@ function processDownloadQueue() {
// TODO: on response error // TODO: on response error
// TODO: on stream error // TODO: on stream error
response.on('end', function () { response.on('end', () => stream.end());
return stream.end();
});
}); });
} }
function commitInstalledModules() { function commitInstalledModules() {
var data = JSON.stringify(installedModules, null, 2); const data = JSON.stringify(installedModules, null, 2);
_fs2.default.writeFileSync(installedModulesFilePath, data); _fs2.default.writeFileSync(installedModulesFilePath, data);
} }
@ -616,15 +511,15 @@ function finishModuleDownload(name, version, zipfile, succeeded) {
events.emit(DOWNLOADED_MODULE, name, download.next, download.queue.length, succeeded); events.emit(DOWNLOADED_MODULE, name, download.next, download.queue.length, succeeded);
if (download.next >= download.queue.length) { if (download.next >= download.queue.length) {
var successes = download.queue.length - download.failures; const successes = download.queue.length - download.failures;
logger.log('Finished module downloads. [success: ' + successes + '] [failure: ' + download.failures + ']'); logger.log(`Finished module downloads. [success: ${successes}] [failure: ${download.failures}]`);
events.emit(DOWNLOADING_MODULES_FINISHED, successes, download.failures); events.emit(DOWNLOADING_MODULES_FINISHED, successes, download.failures);
download.queue = []; download.queue = [];
download.next = 0; download.next = 0;
download.failures = 0; download.failures = 0;
download.active = false; download.active = false;
} else { } else {
var continueDownloads = function continueDownloads() { const continueDownloads = () => {
download.active = false; download.active = false;
processDownloadQueue(); processDownloadQueue();
}; };
@ -633,7 +528,7 @@ function finishModuleDownload(name, version, zipfile, succeeded) {
backoff.succeed(); backoff.succeed();
process.nextTick(continueDownloads); process.nextTick(continueDownloads);
} else { } else {
logger.log('Waiting ' + Math.floor(backoff.current) + 'ms before next download.'); logger.log(`Waiting ${Math.floor(backoff.current)}ms before next download.`);
backoff.fail(continueDownloads); backoff.fail(continueDownloads);
} }
} }
@ -644,10 +539,8 @@ function finishModuleDownload(name, version, zipfile, succeeded) {
} }
function addModuleToUnzipQueue(name, version, zipfile) { function addModuleToUnzipQueue(name, version, zipfile) {
unzip.queue.push({ name: name, version: version, zipfile: zipfile }); unzip.queue.push({ name, version, zipfile });
process.nextTick(function () { process.nextTick(() => processUnzipQueue());
return processUnzipQueue();
});
} }
function processUnzipQueue() { function processUnzipQueue() {
@ -656,17 +549,17 @@ function processUnzipQueue() {
unzip.active = true; unzip.active = true;
var queuedModule = unzip.queue[unzip.next]; const queuedModule = unzip.queue[unzip.next];
unzip.next += 1; unzip.next += 1;
events.emit(INSTALLING_MODULE, queuedModule.name, unzip.next, unzip.queue.length); events.emit(INSTALLING_MODULE, queuedModule.name, unzip.next, unzip.queue.length);
var hasErrored = false; let hasErrored = false;
var onError = function onError(error, zipfile) { const onError = (error, zipfile) => {
if (hasErrored) return; if (hasErrored) return;
hasErrored = true; hasErrored = true;
logger.log('Failed installing ' + queuedModule.name + '@' + queuedModule.version + ': ' + String(error)); logger.log(`Failed installing ${queuedModule.name}@${queuedModule.version}: ${String(error)}`);
succeeded = false; succeeded = false;
if (zipfile) { if (zipfile) {
zipfile.close(); zipfile.close();
@ -674,22 +567,22 @@ function processUnzipQueue() {
finishModuleUnzip(queuedModule, succeeded); finishModuleUnzip(queuedModule, succeeded);
}; };
var succeeded = true; let succeeded = true;
var extractRoot = _path2.default.join(moduleInstallPath, queuedModule.name); const extractRoot = _path2.default.join(moduleInstallPath, queuedModule.name);
logger.log('Installing ' + queuedModule.name + '@' + queuedModule.version + ' from ' + queuedModule.zipfile); logger.log(`Installing ${queuedModule.name}@${queuedModule.version} from ${queuedModule.zipfile}`);
var processZipfile = function processZipfile(err, zipfile) { const processZipfile = (err, zipfile) => {
if (err) { if (err) {
onError(err, null); onError(err, null);
return; return;
} }
var totalEntries = zipfile.entryCount; const totalEntries = zipfile.entryCount;
var processedEntries = 0; let processedEntries = 0;
zipfile.on('entry', function (entry) { zipfile.on('entry', entry => {
processedEntries += 1; processedEntries += 1;
var percent = Math.min(Math.floor(processedEntries / totalEntries * 100), 100); const percent = Math.min(Math.floor(processedEntries / totalEntries * 100), 100);
events.emit(INSTALLING_MODULE_PROGRESS, queuedModule.name, percent); events.emit(INSTALLING_MODULE_PROGRESS, queuedModule.name, percent);
// skip directories // skip directories
@ -698,17 +591,15 @@ function processUnzipQueue() {
return; return;
} }
zipfile.openReadStream(entry, function (err, stream) { zipfile.openReadStream(entry, (err, stream) => {
if (err) { if (err) {
onError(err, zipfile); onError(err, zipfile);
return; return;
} }
stream.on('error', function (e) { stream.on('error', e => onError(e, zipfile));
return onError(e, zipfile);
});
(0, _mkdirp2.default)(_path2.default.join(extractRoot, _path2.default.dirname(entry.fileName)), function (err) { (0, _mkdirp2.default)(_path2.default.join(extractRoot, _path2.default.dirname(entry.fileName)), err => {
if (err) { if (err) {
onError(err, zipfile); onError(err, zipfile);
return; return;
@ -716,11 +607,11 @@ function processUnzipQueue() {
// [adill] createWriteStream via original-fs is broken in Electron 4.0.0-beta.6 with .asar files // [adill] createWriteStream via original-fs is broken in Electron 4.0.0-beta.6 with .asar files
// so we unzip to a temporary filename and rename it afterwards // so we unzip to a temporary filename and rename it afterwards
var tempFileName = _path2.default.join(extractRoot, entry.fileName + '.tmp'); const tempFileName = _path2.default.join(extractRoot, entry.fileName + '.tmp');
var finalFileName = _path2.default.join(extractRoot, entry.fileName); const finalFileName = _path2.default.join(extractRoot, entry.fileName);
var writeStream = originalFs.createWriteStream(tempFileName); const writeStream = originalFs.createWriteStream(tempFileName);
writeStream.on('error', function (e) { writeStream.on('error', e => {
stream.destroy(); stream.destroy();
try { try {
originalFs.unlinkSync(tempFileName); originalFs.unlinkSync(tempFileName);
@ -728,7 +619,7 @@ function processUnzipQueue() {
onError(e, zipfile); onError(e, zipfile);
}); });
writeStream.on('finish', function () { writeStream.on('finish', () => {
try { try {
originalFs.unlinkSync(finalFileName); originalFs.unlinkSync(finalFileName);
} catch (err) {} } catch (err) {}
@ -746,11 +637,11 @@ function processUnzipQueue() {
}); });
}); });
zipfile.on('error', function (err) { zipfile.on('error', err => {
onError(err, zipfile); onError(err, zipfile);
}); });
zipfile.on('end', function () { zipfile.on('end', () => {
if (!succeeded) return; if (!succeeded) return;
installedModules[queuedModule.name].installedVersion = queuedModule.version; installedModules[queuedModule.name].installedVersion = queuedModule.version;
@ -780,9 +671,9 @@ function finishModuleUnzip(unzippedModule, succeeded) {
events.emit(INSTALLED_MODULE, unzippedModule.name, unzip.next, unzip.queue.length, succeeded); events.emit(INSTALLED_MODULE, unzippedModule.name, unzip.next, unzip.queue.length, succeeded);
if (unzip.next >= unzip.queue.length) { if (unzip.next >= unzip.queue.length) {
var successes = unzip.queue.length - unzip.failures; const successes = unzip.queue.length - unzip.failures;
bootstrapping = false; bootstrapping = false;
logger.log('Finished module installations. [success: ' + successes + '] [failure: ' + unzip.failures + ']'); logger.log(`Finished module installations. [success: ${successes}] [failure: ${unzip.failures}]`);
unzip.queue = []; unzip.queue = [];
unzip.next = 0; unzip.next = 0;
unzip.failures = 0; unzip.failures = 0;
@ -791,14 +682,14 @@ function finishModuleUnzip(unzippedModule, succeeded) {
return; return;
} }
process.nextTick(function () { process.nextTick(() => {
unzip.active = false; unzip.active = false;
processUnzipQueue(); processUnzipQueue();
}); });
} }
function quitAndInstallUpdates() { function quitAndInstallUpdates() {
logger.log('Relaunching to install ' + (hostUpdateAvailable ? 'host' : 'module') + ' updates...'); logger.log(`Relaunching to install ${hostUpdateAvailable ? 'host' : 'module'} updates...`);
if (hostUpdateAvailable) { if (hostUpdateAvailable) {
hostUpdater.quitAndInstall(); hostUpdater.quitAndInstall();
} else { } else {
@ -808,16 +699,13 @@ function quitAndInstallUpdates() {
function relaunch() { function relaunch() {
logger.end(); logger.end();
const { app } = require('electron');
var _require = require('electron'),
app = _require.app;
app.relaunch(); app.relaunch();
app.quit(); app.quit();
} }
function isInstalled(name, version) { function isInstalled(name, version) {
var metadata = installedModules[name]; const metadata = installedModules[name];
if (locallyInstalledModules) return true; if (locallyInstalledModules) return true;
if (metadata && metadata.installedVersion > 0) { if (metadata && metadata.installedVersion > 0) {
if (!version) return true; if (!version) return true;
@ -831,10 +719,7 @@ function getInstalled() {
} }
function install(name, defer, options) { function install(name, defer, options) {
var _ref = options || {}, let { version, authToken } = options || {};
version = _ref.version,
authToken = _ref.authToken;
if (isInstalled(name, version)) { if (isInstalled(name, version)) {
if (!defer) { if (!defer) {
events.emit(INSTALLED_MODULE, name, 1, 1, true); events.emit(INSTALLED_MODULE, name, 1, 1, true);
@ -845,19 +730,19 @@ function install(name, defer, options) {
if (newInstallInProgress[name]) return; if (newInstallInProgress[name]) return;
if (!updatable) { if (!updatable) {
logger.log('Not updatable; ignoring request to install ' + name + '...'); logger.log(`Not updatable; ignoring request to install ${name}...`);
return; return;
} }
if (defer) { if (defer) {
if (version) { if (version) {
throw new Error('Cannot defer install for a specific version module (' + name + ', ' + version + ')'); throw new Error(`Cannot defer install for a specific version module (${name}, ${version})`);
} }
logger.log('Deferred install for ' + name + '...'); logger.log(`Deferred install for ${name}...`);
installedModules[name] = { installedVersion: 0 }; installedModules[name] = { installedVersion: 0 };
commitInstalledModules(); commitInstalledModules();
} else { } else {
logger.log('Starting to install ' + name + '...'); logger.log(`Starting to install ${name}...`);
if (!version) { if (!version) {
version = remoteModuleVersions[name] || 0; version = remoteModuleVersions[name] || 0;
} }
@ -867,76 +752,32 @@ function install(name, defer, options) {
} }
function installPendingUpdates() { function installPendingUpdates() {
var updatesToInstall = []; const updatesToInstall = [];
if (bootstrapping) { if (bootstrapping) {
var modules = {}; let modules = {};
try { try {
modules = JSON.parse(_fs2.default.readFileSync(bootstrapManifestFilePath)); modules = JSON.parse(_fs2.default.readFileSync(bootstrapManifestFilePath));
} catch (err) {} } catch (err) {}
var _iteratorNormalCompletion3 = true; for (const moduleName of Object.keys(modules)) {
var _didIteratorError3 = false; installedModules[moduleName] = { installedVersion: 0 };
var _iteratorError3 = undefined; const zipfile = _path2.default.join(paths.getResources(), 'bootstrap', `${moduleName}.zip`);
updatesToInstall.push({ moduleName, update: modules[moduleName], zipfile });
try {
for (var _iterator3 = Object.keys(modules)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var moduleName = _step3.value;
installedModules[moduleName] = { installedVersion: 0 };
var zipfile = _path2.default.join(paths.getResources(), 'bootstrap', moduleName + '.zip');
updatesToInstall.push({ moduleName: moduleName, update: modules[moduleName], zipfile: zipfile });
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
} }
} }
var _iteratorNormalCompletion4 = true; for (const moduleName of Object.keys(installedModules)) {
var _didIteratorError4 = false; const update = installedModules[moduleName].updateVersion || 0;
var _iteratorError4 = undefined; const zipfile = installedModules[moduleName].updateZipfile;
if (update > 0 && zipfile != null) {
try { updatesToInstall.push({ moduleName, update, zipfile });
for (var _iterator4 = Object.keys(installedModules)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var _moduleName = _step4.value;
var update = installedModules[_moduleName].updateVersion || 0;
var _zipfile = installedModules[_moduleName].updateZipfile;
if (update > 0 && _zipfile != null) {
updatesToInstall.push({ moduleName: _moduleName, update: update, zipfile: _zipfile });
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
} }
} }
if (updatesToInstall.length > 0) { if (updatesToInstall.length > 0) {
logger.log((bootstrapping ? 'Bootstrapping' : 'Installing updates') + '...'); logger.log(`${bootstrapping ? 'Bootstrapping' : 'Installing updates'}...`);
updatesToInstall.forEach(function (e) { updatesToInstall.forEach(e => addModuleToUnzipQueue(e.moduleName, e.update, e.zipfile));
return addModuleToUnzipQueue(e.moduleName, e.update, e.zipfile);
});
} else { } else {
logger.log('No updates to install'); logger.log('No updates to install');
events.emit(NO_PENDING_UPDATES); events.emit(NO_PENDING_UPDATES);

View File

@ -29,17 +29,15 @@ var _rimraf2 = _interopRequireDefault(_rimraf);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Determines environment-specific paths based on info provided // Determines environment-specific paths based on info provided
var originalFs = require('original-fs'); const originalFs = require('original-fs');
var userDataPath = null; let userDataPath = null;
var userDataVersionedPath = null; let userDataVersionedPath = null;
var resourcesPath = null; let resourcesPath = null;
var modulePath = null; let modulePath = null;
function determineAppUserDataRoot() { function determineAppUserDataRoot() {
var _require = require('electron'), const { app } = require('electron');
app = _require.app;
return app.getPath('appData'); return app.getPath('appData');
} }
@ -49,13 +47,13 @@ function determineUserData(userDataRoot, buildInfo) {
// cleans old version data in the background // cleans old version data in the background
function cleanOldVersions(buildInfo) { function cleanOldVersions(buildInfo) {
var entries = _fs2.default.readdirSync(userDataPath) || []; const entries = _fs2.default.readdirSync(userDataPath) || [];
entries.forEach(function (entry) { entries.forEach(entry => {
var fullPath = _path2.default.join(userDataPath, entry); const fullPath = _path2.default.join(userDataPath, entry);
if (_fs2.default.statSync(fullPath).isDirectory() && entry.indexOf(buildInfo.version) === -1) { if (_fs2.default.statSync(fullPath).isDirectory() && entry.indexOf(buildInfo.version) === -1) {
if (entry.match('^[0-9]+.[0-9]+.[0-9]+') != null) { if (entry.match('^[0-9]+.[0-9]+.[0-9]+') != null) {
console.log('Removing old directory ', entry); console.log('Removing old directory ', entry);
(0, _rimraf2.default)(fullPath, originalFs, function (error) { (0, _rimraf2.default)(fullPath, originalFs, error => {
if (error) { if (error) {
console.warn('...failed with error: ', error); console.warn('...failed with error: ', error);
} }
@ -68,13 +66,11 @@ function cleanOldVersions(buildInfo) {
function init(buildInfo) { function init(buildInfo) {
resourcesPath = _path2.default.join(require.main.filename, '..', '..', '..'); resourcesPath = _path2.default.join(require.main.filename, '..', '..', '..');
var userDataRoot = determineAppUserDataRoot(); const userDataRoot = determineAppUserDataRoot();
userDataPath = determineUserData(userDataRoot, buildInfo); userDataPath = determineUserData(userDataRoot, buildInfo);
var _require2 = require('electron'), const { app } = require('electron');
app = _require2.app;
app.setPath('userData', userDataPath); app.setPath('userData', userDataPath);
userDataVersionedPath = _path2.default.join(userDataPath, buildInfo.version); userDataVersionedPath = _path2.default.join(userDataPath, buildInfo.version);

View File

@ -10,52 +10,46 @@
"topLevelPatterns": [ "topLevelPatterns": [
"devtron@1.4.0", "devtron@1.4.0",
"mkdirp@^0.5.1", "mkdirp@^0.5.1",
"request@2.83.0", "request@2.88.0",
"rimraf@^2.5.2", "rimraf@^2.6.3",
"yauzl@^2.5.0" "yauzl@^2.10.0"
], ],
"lockfileEntries": { "lockfileEntries": {
"accessibility-developer-tools@^2.11.0": "https://registry.yarnpkg.com/accessibility-developer-tools/-/accessibility-developer-tools-2.12.0.tgz#3da0cce9d6ec6373964b84f35db7cfc3df7ab514", "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", "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",
"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", "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", "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", "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", "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", "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", "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", "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.7.tgz#2d1d24317afb8abe95d6d2c0b07b57813539d828",
"combined-stream@1.0.6": "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.6.tgz#723e7df6e801ac5613113a7e445a9b69cb632818", "combined-stream@~1.0.6": "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.7.tgz#2d1d24317afb8abe95d6d2c0b07b57813539d828",
"combined-stream@~1.0.5": "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.5.tgz#938370a57b4a51dea2c77c15d5c5fdf895164009",
"concat-map@0.0.1": "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b", "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", "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", "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", "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", "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", "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.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", "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", "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", "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", "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", "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-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", "har-validator@~5.1.0": "https://registry.yarnpkg.com/har-validator/-/har-validator-5.1.3.tgz#1ef89ebd3e4996557675eed9893110dc350fa080",
"hawk@~6.0.2": "https://registry.yarnpkg.com/hawk/-/hawk-6.0.2.tgz#af4d914eb065f9b5ce4d9d11c1cb2126eecc3038",
"highlight.js@^9.3.0": "https://registry.yarnpkg.com/highlight.js/-/highlight.js-9.12.0.tgz#e6d9dbe57cbefe60751f02af336195870c90c01e", "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", "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", "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", "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", "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", "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", "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-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", "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", "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.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.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", "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", "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", "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", "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", "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", "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", "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", "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", "punycode@^2.1.0": "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec",
"request@2.83.0": "https://registry.yarnpkg.com/request/-/request-2.83.0.tgz#ca0b65da02ed62935887808e6f510381034e3356", "qs@~6.5.2": "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36",
"rimraf@^2.5.2": "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.2.tgz#2ed8150d24a16ea8651e6d6ef0f47c4158ce7a36", "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.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", "safe-buffer@^5.1.2": "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d",
"sntp@2.x.x": "https://registry.yarnpkg.com/sntp/-/sntp-2.1.0.tgz#2c6cec14fedc2222739caf9b5c3d85d1cc5a2cc8",
"sshpk@^1.7.0": "https://registry.yarnpkg.com/sshpk/-/sshpk-1.13.1.tgz#512df6da6287144316dc4c18fe1cf1d940739be3", "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.4.3": "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.4.3.tgz#53f36da3f47783b0925afa06ff9f3b165280f781",
"tough-cookie@~2.3.3": "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.3.4.tgz#ec60cee38ac675063ffc97a5c18970578ee83655",
"tunnel-agent@^0.6.0": "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd", "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.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", "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", "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", "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": [], "files": [],
"artifacts": {} "artifacts": {}

View File

@ -1,6 +1,6 @@
The MIT License (MIT) 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -2,30 +2,35 @@
# Ajv: Another JSON Schema Validator # 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) [![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](https://img.shields.io/npm/v/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 downloads](https://img.shields.io/npm/dm/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) [![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/) [![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) [![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. __Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance:
[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:
```javascript ```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')); 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) - [Command line interface](#command-line-interface)
- Validation - Validation
- [Keywords](#validation-keywords) - [Keywords](#validation-keywords)
- [Annotation keywords](#annotation-keywords)
- [Formats](#formats) - [Formats](#formats)
- [Combining schemas with $ref](#ref) - [Combining schemas with $ref](#ref)
- [$data reference](#data-reference) - [$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) - [Defining custom keywords](#defining-custom-keywords)
- [Asynchronous schema compilation](#asynchronous-schema-compilation) - [Asynchronous schema compilation](#asynchronous-schema-compilation)
- [Asynchronous validation](#asynchronous-validation) - [Asynchronous validation](#asynchronous-validation)
- [Security considerations](#security-considerations)
- Modifying data during validation - Modifying data during validation
- [Filtering data](#filtering-data) - [Filtering data](#filtering-data)
- [Assigning defaults](#assigning-defaults) - [Assigning defaults](#assigning-defaults)
@ -55,14 +62,15 @@ ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
- [Methods](#api) - [Methods](#api)
- [Options](#options) - [Options](#options)
- [Validation errors](#validation-errors) - [Validation errors](#validation-errors)
- [Plugins](#plugins)
- [Related packages](#related-packages) - [Related packages](#related-packages)
- [Packages using Ajv](#some-packages-using-ajv) - [Some packages using Ajv](#some-packages-using-ajv)
- [Tests, Contributing, History, License](#tests) - [Tests, Contributing, History, License](#tests)
## Performance ## 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: 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 ## 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)) - 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) - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available)
- support of circular references between schemas - support of circular references between schemas
- correct string lengths for strings with unicode pairs (can be turned off) - 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) - [validates schemas against meta-schema](#api-validateschema)
- supports [browsers](#using-in-browser) and Node.js 0.10-8.x - supports [browsers](#using-in-browser) and Node.js 0.10-8.x
- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation - [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 - [assigning defaults](#assigning-defaults) to missing properties and items
- [coercing data](#coercing-data-types) to the types specified in `type` keywords - [coercing data](#coercing-data-types) to the types specified in `type` keywords
- [custom keywords](#defining-custom-keywords) - [custom keywords](#defining-custom-keywords)
- draft-6 keywords `const`, `contains` and `propertyNames` - draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else`
- draft-6 boolean schemas (`true`/`false` as a schema to always pass/fail). - 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 - 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 - [$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 - [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 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 ## <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: 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)) - 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)) - migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate))
- validating data file(s) against JSON-schema - validating data file(s) against JSON Schema
- testing expected validity of data against JSON-schema - testing expected validity of data against JSON Schema
- referenced schemas - referenced schemas
- custom meta-schemas - custom meta-schemas
- files in JSON and JavaScript format - 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 ## 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) - [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 - [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 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 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) - [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. - [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. - [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. 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 ## Formats
The following formats are supported for string validation with "format" keyword: 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). - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).
- _time_: time with optional time-zone. - _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)). - _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. - _uri_: full URI.
- _url_: [URL record](https://url.spec.whatwg.org/#concept-url). - _uri-reference_: URI reference, including full and relative URIs.
- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) - _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. - _email_: email address.
- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). - _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5).
- _ipv4_: IP address v4. - _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). - _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). - _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. 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 ## $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: 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). 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. 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. __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. 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. 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: Example:
```javascript ```javascript
/** var ajv = new Ajv;
* Default mode is non-transpiled generator function wrapped with `co`. // require('ajv-async')(ajv);
* 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);
ajv.addKeyword('idExists', { ajv.addKeyword('idExists', {
async: true, async: true,
@ -580,41 +580,25 @@ validate({ userId: 1, postId: 19 })
### Using transpilers with asynchronous validation functions. ### Using transpilers with asynchronous validation functions.
To use a transpiler you should separately install it (or load its bundle in the browser). [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).
Ajv npm package includes minified browser bundles of regenerator and nodent in dist folder.
#### Using nodent #### Using nodent
```javascript ```javascript
var setupAsync = require('ajv-async'); var ajv = new Ajv;
var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' }); require('ajv-async')(ajv);
setupAsync(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 var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc); 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 #### Using other transpilers
```javascript ```javascript
var ajv = new Ajv({ async: 'es7', processCode: transpileFunc }); var ajv = new Ajv({ processCode: transpileFunc });
var validate = ajv.compile(schema); // transpiled es7 async function var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc); validate(data).then(successFunc).catch(errorFunc);
``` ```
@ -622,24 +606,55 @@ validate(data).then(successFunc).catch(errorFunc);
See [Options](#options). See [Options](#options).
#### Comparison of async modes ## Security considerations
|mode|transpile<br>speed*|run-time<br>speed*|bundle<br>size| 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.
|---|:-:|:-:|:-:|
|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|
\* 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 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.
- 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 If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent:
- works in IE 9 (regenerator does not) - 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 ## 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 [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. 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. __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.
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.
Example 1 (`default` in `properties`): Example 1 (`default` in `properties`):
@ -785,32 +798,6 @@ console.log(validate(data)); // true
console.log(data); // [ 1, "foo" ] 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: `default` keywords in other cases are ignored:
- not in `properties` or `items` subschemas - not in `properties` or `items` subschemas
@ -884,9 +871,9 @@ Create Ajv instance.
Generate validating function and cache the compiled schema for future use. 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 ##### <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 ```javascript
var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri);
``` ```
##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv ##### .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). 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 ##### <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. 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 `-`. 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. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions.
Example Keywords: Example Keywords:
- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. - `"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 - `"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: Keyword definition is an object with the following properties:
@ -1062,16 +1049,18 @@ Defaults:
$data: false, $data: false,
allErrors: false, allErrors: false,
verbose: false, verbose: false,
$comment: false, // NEW in Ajv version 6.0
jsonPointers: false, jsonPointers: false,
uniqueItems: true, uniqueItems: true,
unicode: true, unicode: true,
nullable: false,
format: 'fast', format: 'fast',
formats: {}, formats: {},
unknownFormats: true, unknownFormats: true,
schemas: {}, schemas: {},
logger: undefined, logger: undefined,
// referenced schema options: // referenced schema options:
schemaId: undefined // recommended '$id' schemaId: '$id',
missingRefs: true, missingRefs: true,
extendRefs: 'ignore', // recommended 'fail' extendRefs: 'ignore', // recommended 'fail'
loadSchema: undefined, // function(uri: string): Promise {} loadSchema: undefined, // function(uri: string): Promise {}
@ -1080,7 +1069,6 @@ Defaults:
useDefaults: false, useDefaults: false,
coerceTypes: false, coerceTypes: false,
// asynchronous validation options: // asynchronous validation options:
async: 'co*',
transpile: undefined, // requires ajv-async package transpile: undefined, // requires ajv-async package
// advanced options: // advanced options:
meta: true, meta: true,
@ -1091,7 +1079,7 @@ Defaults:
loopRequired: Infinity, loopRequired: Infinity,
ownProperties: false, ownProperties: false,
multipleOfPrecision: false, multipleOfPrecision: false,
errorDataPath: 'object', errorDataPath: 'object', // deprecated
messages: true, messages: true,
sourceCode: false, sourceCode: false,
processCode: undefined, // function (str: string): string {} 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). - _$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. - _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). - _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. - _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). - _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. - _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. - _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. - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
- _unknownFormats_: handling of unknown formats. Option values: - _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. - `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. - `[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. - _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: - _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. - 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 ##### Referenced schema options
- _schemaId_: this option defines which keywords are used as schema URI. Option value: - _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). - `"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: - _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). - `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. - `"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). - `"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. - `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). - `"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 - `false` (default) - do not use defaults
- `true` - insert defaults by value (safer and slower, object literal is used). - `true` - insert defaults by value (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. - `"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: - _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. - `false` (default) - no type coercion.
- `true` - coerce scalar data types. - `true` - coerce scalar data types.
@ -1156,30 +1150,16 @@ Defaults:
##### Asynchronous validation options ##### 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: - _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. - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported.
- `"regenerator"` - transpile with [regenerator](https://github.com/facebook/regenerator). If regenerator is not installed, the exception will be thrown. - `true` - always transpile with nodent.
- 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. - `false` - do not transpile; if async functions are not supported an exception will be thrown.
##### Advanced options ##### 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. - _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. - `true` (default) - if the validation fails, throw the exception.
- `"log"` - if the validation fails, log error. - `"log"` - if the validation fails, log error.
- `false` - skip schema validation. - `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. - _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. - _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). - _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)). - _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). - _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: - _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). - `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) - `type` - property `type` (required type(s), a string, can be a comma-separated list)
- `uniqueItems` - properties `i` and `j` (indices of duplicate items). - `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). - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword).
- `$ref` - property `ref` with the referenced schema URI. - `$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). - 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 ## 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-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-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-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) - custom validation keywords (if/then/else, select, typeof, etc.) - [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) - keywords $merge and $patch - [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 - [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 - [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 - [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 - [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 - [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 - [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 - [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 - [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 - [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 - [@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 - [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 - [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 - [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 - [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 - [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 ## Tests
@ -1311,15 +1306,15 @@ Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/mas
See https://github.com/epoberezkin/ajv/releases 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 ## 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/stable/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; (options?: ajv.Options): ajv.Ajv;
new (options?: ajv.Options): ajv.Ajv; new(options?: ajv.Options): ajv.Ajv;
ValidationError: ValidationError; ValidationError: typeof AjvErrors.ValidationError;
MissingRefError: MissingRefError; MissingRefError: typeof AjvErrors.MissingRefError;
$dataMetaSchema: object; $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 { declare namespace ajv {
type ValidationError = AjvErrors.ValidationError;
type MissingRefError = AjvErrors.MissingRefError;
interface Ajv { interface Ajv {
/** /**
* Validate data using schema * Validate data using schema
@ -15,7 +39,7 @@ declare namespace ajv {
* @param {Any} data to be validated * @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`). * @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. * Create validating function for passed schema.
* @param {object|Boolean} schema schema object * @param {object|Boolean} schema schema object
@ -29,9 +53,9 @@ declare namespace ajv {
* @param {object|Boolean} schema schema object * @param {object|Boolean} schema schema object
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped * @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. * @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. * 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. * @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`. * @param {object} options optional options with properties `separator` and `dataVar`.
* @return {string} human readable string with all errors descriptions * @return {string} human readable string with all errors descriptions
*/ */
errorsText(errors?: Array<ErrorObject>, options?: ErrorsTextOptions): string; errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string;
errors?: Array<ErrorObject>; errors?: Array<ErrorObject> | null;
} }
interface Thenable <R> { interface CustomLogger {
then <U> (onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>; log(...args: any[]): any;
warn(...args: any[]): any;
error(...args: any[]): any;
} }
interface ValidateFunction { interface ValidateFunction {
@ -118,7 +144,7 @@ declare namespace ajv {
parentData?: object | Array<any>, parentData?: object | Array<any>,
parentDataProperty?: string | number, parentDataProperty?: string | number,
rootData?: object | Array<any> rootData?: object | Array<any>
): boolean | Thenable<any>; ): boolean | PromiseLike<any>;
schema?: object | boolean; schema?: object | boolean;
errors?: null | Array<ErrorObject>; errors?: null | Array<ErrorObject>;
refs?: object; refs?: object;
@ -139,10 +165,10 @@ declare namespace ajv {
formats?: object; formats?: object;
unknownFormats?: true | string[] | 'ignore'; unknownFormats?: true | string[] | 'ignore';
schemas?: Array<object> | object; schemas?: Array<object> | object;
schemaId?: '$id' | 'id'; schemaId?: '$id' | 'id' | 'auto';
missingRefs?: true | 'ignore' | 'fail'; missingRefs?: true | 'ignore' | 'fail';
extendRefs?: 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'; removeAdditional?: boolean | 'all' | 'failing';
useDefaults?: boolean | 'shared'; useDefaults?: boolean | 'shared';
coerceTypes?: boolean | 'array'; coerceTypes?: boolean | 'array';
@ -161,16 +187,30 @@ declare namespace ajv {
sourceCode?: boolean; sourceCode?: boolean;
processCode?: (code: string) => string; processCode?: (code: string) => string;
cache?: object; 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 { interface NumberFormatDefinition {
validate: FormatValidator; type: "number",
compare: (data1: string, data2: string) => number; validate: NumberFormatValidator;
compare?: (data1: number, data2: number) => number;
async?: boolean; async?: boolean;
} }
interface StringFormatDefinition {
type?: "string",
validate: FormatValidator;
compare?: (data1: string, data2: string) => number;
async?: boolean;
}
type FormatDefinition = NumberFormatDefinition | StringFormatDefinition;
interface KeywordDefinition { interface KeywordDefinition {
type?: string | Array<string>; type?: string | Array<string>;
async?: boolean; async?: boolean;
@ -227,7 +267,7 @@ declare namespace ajv {
parentData?: object | Array<any>, parentData?: object | Array<any>,
parentDataProperty?: string | number, parentDataProperty?: string | number,
rootData?: object | Array<any> rootData?: object | Array<any>
): boolean | Thenable<any>; ): boolean | PromiseLike<any>;
errors?: Array<ErrorObject>; errors?: Array<ErrorObject>;
} }
@ -252,11 +292,11 @@ declare namespace ajv {
} }
type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams | type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams |
DependenciesParams | FormatParams | ComparisonParams | DependenciesParams | FormatParams | ComparisonParams |
MultipleOfParams | PatternParams | RequiredParams | MultipleOfParams | PatternParams | RequiredParams |
TypeParams | UniqueItemsParams | CustomParams | TypeParams | UniqueItemsParams | CustomParams |
PatternGroupsParams | PatternRequiredParams | PatternRequiredParams | PropertyNamesParams |
PropertyNamesParams | SwitchParams | NoParams | EnumParams; IfParams | SwitchParams | NoParams | EnumParams;
interface RefParams { interface RefParams {
ref: string; ref: string;
@ -312,12 +352,6 @@ declare namespace ajv {
keyword: string; keyword: string;
} }
interface PatternGroupsParams {
reason: string;
limit: number;
pattern: string;
}
interface PatternRequiredParams { interface PatternRequiredParams {
missingPattern: string; missingPattern: string;
} }
@ -326,33 +360,19 @@ declare namespace ajv {
propertyName: string; propertyName: string;
} }
interface IfParams {
failingKeyword: string;
}
interface SwitchParams { interface SwitchParams {
caseIndex: number; caseIndex: number;
} }
interface NoParams {} interface NoParams { }
interface EnumParams { interface EnumParams {
allowedValues: Array<any>; 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; export = ajv;

View File

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

View File

@ -2,8 +2,8 @@
var util = require('./util'); var util = require('./util');
var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/; 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 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 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 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; 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 = /^(?:(?: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 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 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)*)*)$/; 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: http://tools.ietf.org/html/rfc3339#section-5.6
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6 // 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, 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(?:\.\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: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
uri: /^(?:[a-z][a-z0-9+-.]*)(?::|\/)\/?[^\s]*$/i, uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i,
'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i, 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
'uri-template': URITEMPLATE, 'uri-template': URITEMPLATE,
url: URL, url: URL,
// email (sources from jsen validator): // email (sources from jsen validator):
@ -54,6 +55,7 @@ formats.fast = {
// JSON-pointer: https://tools.ietf.org/html/rfc6901 // JSON-pointer: https://tools.ietf.org/html/rfc6901
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
'json-pointer': JSON_POINTER, '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: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
'relative-json-pointer': RELATIVE_JSON_POINTER 'relative-json-pointer': RELATIVE_JSON_POINTER
}; };
@ -67,25 +69,35 @@ formats.full = {
'uri-reference': URIREF, 'uri-reference': URIREF,
'uri-template': URITEMPLATE, 'uri-template': URITEMPLATE,
url: URL, 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, hostname: hostname,
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, 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, 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, regex: regex,
uuid: UUID, uuid: UUID,
'json-pointer': JSON_POINTER, 'json-pointer': JSON_POINTER,
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
'relative-json-pointer': RELATIVE_JSON_POINTER '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) { function date(str) {
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6 // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
var matches = str.match(DATE); var matches = str.match(DATE);
if (!matches) return false; if (!matches) return false;
var month = +matches[1]; var year = +matches[1];
var day = +matches[2]; var month = +matches[2];
return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month]; 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 minute = matches[2];
var second = matches[3]; var second = matches[3];
var timeZone = matches[5]; 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 * Functions below are used inside compiled validations function
*/ */
var co = require('co');
var ucs2length = util.ucs2length; var ucs2length = util.ucs2length;
var equal = require('fast-deep-equal'); var equal = require('fast-deep-equal');
@ -70,9 +69,11 @@ function compile(schema, root, localRefs, baseId) {
endCompiling.call(this, schema, root, baseId); endCompiling.call(this, schema, root, baseId);
} }
/* @this {*} - custom context, see passContext option */
function callValidate() { function callValidate() {
/* jshint validthis: true */
var validate = compilation.validate; var validate = compilation.validate;
var result = validate.apply(null, arguments); var result = validate.apply(this, arguments);
callValidate.errors = validate.errors; callValidate.errors = validate.errors;
return result; return result;
} }
@ -124,7 +125,6 @@ function compile(schema, root, localRefs, baseId) {
'refVal', 'refVal',
'defaults', 'defaults',
'customRules', 'customRules',
'co',
'equal', 'equal',
'ucs2length', 'ucs2length',
'ValidationError', 'ValidationError',
@ -139,7 +139,6 @@ function compile(schema, root, localRefs, baseId) {
refVal, refVal,
defaults, defaults,
customRules, customRules,
co,
equal, equal,
ucs2length, ucs2length,
ValidationError ValidationError
@ -224,7 +223,7 @@ function compile(schema, root, localRefs, baseId) {
function resolvedRef(refVal, code) { function resolvedRef(refVal, code) {
return typeof refVal == 'object' || typeof refVal == 'boolean' return typeof refVal == 'object' || typeof refVal == 'boolean'
? { code: code, schema: refVal, inline: true } ? { code: code, schema: refVal, inline: true }
: { code: code, $async: refVal && refVal.$async }; : { code: code, $async: refVal && !!refVal.$async };
} }
function usePattern(regexStr) { function usePattern(regexStr) {

View File

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

View File

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

View File

@ -38,7 +38,7 @@ module.exports = function (metaSchema, keywordsJsonPointers) {
keywords[key] = { keywords[key] = {
anyOf: [ anyOf: [
schema, 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}}) { || {{=$data}} !== {{=$data}}) {
var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}='; var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}=';
{{
if ($schema === undefined) {
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaValueExcl;
$isData = $isDataExcl;
}
}}
{{??}} {{??}}
{{ {{
var $exclIsNumber = typeof $schemaExcl == 'number' var $exclIsNumber = typeof $schemaExcl == 'number'

9
appasar/stable/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 }} {{# def.storeDefOut:def_callRuleValidate }}
{{? $rDef.errors === false }} {{? $rDef.errors === false }}
{{=$valid}} = {{? $asyncKeyword }}{{=it.yieldAwait}}{{?}}{{= def_callRuleValidate }}; {{=$valid}} = {{? $asyncKeyword }}await {{?}}{{= def_callRuleValidate }};
{{??}} {{??}}
{{? $asyncKeyword }} {{? $asyncKeyword }}
{{ $ruleErrs = 'customErrors' + $lvl; }} {{ $ruleErrs = 'customErrors' + $lvl; }}
var {{=$ruleErrs}} = null; var {{=$ruleErrs}} = null;
try { try {
{{=$valid}} = {{=it.yieldAwait}}{{= def_callRuleValidate }}; {{=$valid}} = await {{= def_callRuleValidate }};
} catch (e) { } catch (e) {
{{=$valid}} = false; {{=$valid}} = false;
if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors; if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors;

View File

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

View File

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

View File

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

75
appasar/stable/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.setupKeyword }}
{{# def.setupNextLevel }} {{# def.setupNextLevel }}
var {{=$errs}} = errors; {{
var prevValid{{=$lvl}} = false; var $currentBaseId = $it.baseId
var {{=$valid}} = false; , $prevValid = 'prevValid' + $lvl
, $passingSchemas = 'passingSchemas' + $lvl;
}}
var {{=$errs}} = errors
, {{=$prevValid}} = false
, {{=$valid}} = false
, {{=$passingSchemas}} = null;
{{ var $currentBaseId = $it.baseId; }}
{{# def.setCompositeRule }} {{# def.setCompositeRule }}
{{~ $schema:$sch:$i }} {{~ $schema:$sch:$i }}
@ -24,13 +30,17 @@ var {{=$valid}} = false;
{{?}} {{?}}
{{? $i }} {{? $i }}
if ({{=$nextValid}} && prevValid{{=$lvl}}) if ({{=$nextValid}} && {{=$prevValid}}) {
{{=$valid}} = false; {{=$valid}} = false;
else { {{=$passingSchemas}} = [{{=$passingSchemas}}, {{=$i}}];
} else {
{{ $closingBraces += '}'; }} {{ $closingBraces += '}'; }}
{{?}} {{?}}
if ({{=$nextValid}}) {{=$valid}} = prevValid{{=$lvl}} = true; if ({{=$nextValid}}) {
{{=$valid}} = {{=$prevValid}} = true;
{{=$passingSchemas}} = {{=$i}};
}
{{~}} {{~}}
{{# def.resetCompositeRule }} {{# def.resetCompositeRule }}

View File

@ -42,13 +42,8 @@
, $currentBaseId = it.baseId; , $currentBaseId = it.baseId;
var $required = it.schema.required; 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); 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 }} {{? $someProperties }}
var isAdditional{{=$lvl}} = !(false var isAdditional{{=$lvl}} = !(false
{{? $schemaKeys.length }} {{? $schemaKeys.length }}
{{? $schemaKeys.length > 5 }} {{? $schemaKeys.length > 8 }}
|| validate.schema{{=$schemaPath}}[{{=$key}}] || validate.schema{{=$schemaPath}}.hasOwnProperty({{=$key}})
{{??}} {{??}}
{{~ $schemaKeys:$propertyKey }} {{~ $schemaKeys:$propertyKey }}
|| {{=$key}} == {{= it.util.toQuotedString($propertyKey) }} || {{=$key}} == {{= it.util.toQuotedString($propertyKey) }}
@ -76,11 +71,6 @@ var {{=$nextValid}} = true;
|| {{= it.usePattern($pProperty) }}.test({{=$key}}) || {{= it.usePattern($pProperty) }}.test({{=$key}})
{{~}} {{~}}
{{?}} {{?}}
{{? it.opts.patternGroups && $pgPropertyKeys.length }}
{{~ $pgPropertyKeys:$pgProperty:$i }}
|| {{= it.usePattern($pgProperty) }}.test({{=$key}})
{{~}}
{{?}}
); );
if (isAdditional{{=$lvl}}) { 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 }} {{? $breakOnError }}
{{= $closingBraces }} {{= $closingBraces }}
if ({{=$errs}} == errors) { if ({{=$errs}} == errors) {

View File

@ -3,6 +3,8 @@
{{# def.setupKeyword }} {{# def.setupKeyword }}
{{# def.setupNextLevel }} {{# def.setupNextLevel }}
var {{=$errs}} = errors;
{{? {{# def.nonEmptySchema:$schema }} }} {{? {{# def.nonEmptySchema:$schema }} }}
{{ {{
$it.schema = $schema; $it.schema = $schema;
@ -22,8 +24,6 @@
, $currentBaseId = it.baseId; , $currentBaseId = it.baseId;
}} }}
var {{=$errs}} = errors;
{{? $ownProperties }} {{? $ownProperties }}
var {{=$dataProperties}} = undefined; 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; $refCode = $refVal.code;
}} }}
{{?}} {{?}}
@ -65,7 +65,7 @@
{{ if (!it.async) throw new Error('async schema referenced by sync schema'); }} {{ if (!it.async) throw new Error('async schema referenced by sync schema'); }}
{{? $breakOnError }} var {{=$valid}}; {{?}} {{? $breakOnError }} var {{=$valid}}; {{?}}
try { try {
{{=it.yieldAwait}} {{=__callValidate}}; await {{=__callValidate}};
{{? $breakOnError }} {{=$valid}} = true; {{?}} {{? $breakOnError }} {{=$valid}} = true; {{?}}
} catch (e) { } catch (e) {
if (!(e instanceof ValidationError)) throw e; if (!(e instanceof ValidationError)) throw e;

View File

@ -14,18 +14,42 @@
else { else {
{{?}} {{?}}
var {{=$valid}} = true; var i = {{=$data}}.length
if ({{=$data}}.length > 1) { , {{=$valid}} = true
var i = {{=$data}}.length, j; , j;
outer: if (i > 1) {
for (;i--;) { {{
for (j = i; j--;) { var $itemType = it.schema.items && it.schema.items.type
if (equal({{=$data}}[i], {{=$data}}[j])) { , $typeIsArray = Array.isArray($itemType);
{{=$valid}} = false; }}
break outer; {{? !$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 }} } {{?}} {{? $isData }} } {{?}}

View File

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

View File

@ -52,7 +52,8 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -65,7 +66,13 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
if ($isData) { if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; 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 { } else {
var $exclIsNumber = typeof $schemaExcl == 'number', var $exclIsNumber = typeof $schemaExcl == 'number',
$opStr = $op; $opStr = $op;
@ -132,7 +139,8 @@ module.exports = function generate__limit(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

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

View File

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

View File

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

View File

@ -52,7 +52,8 @@ module.exports = function generate_anyOf(it, $keyword, $ruleType) {
out += ' {} '; out += ' {} ';
} }
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; 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) { if (it.async) {
out += ' throw new ValidationError(vErrors); '; out += ' throw new ValidationError(vErrors); ';
} else { } else {

14
appasar/stable/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); $$outStack.push(out);
out = ''; /* istanbul ignore else */ out = ''; /* istanbul ignore else */
if (it.createErrors !== false) { 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) { if (it.opts.messages !== false) {
out += ' , message: \'should be equal to constant\' '; out += ' , message: \'should be equal to constant\' ';
} }
@ -38,7 +38,8 @@ module.exports = function generate_const(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

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

View File

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

View File

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

View File

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

View File

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

104
appasar/stable/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/stable/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; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {

View File

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

View File

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

View File

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

View File

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

View File

@ -8,7 +8,6 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors; var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || ''); var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl; var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it); var $it = it.util.copy(it);
var $closingBraces = ''; var $closingBraces = '';
@ -31,11 +30,7 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
$ownProperties = it.opts.ownProperties, $ownProperties = it.opts.ownProperties,
$currentBaseId = it.baseId; $currentBaseId = it.baseId;
var $required = it.schema.required; var $required = it.schema.required;
if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required); 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);
}
out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
if ($ownProperties) { if ($ownProperties) {
out += ' var ' + ($dataProperties) + ' = undefined;'; out += ' var ' + ($dataProperties) + ' = undefined;';
@ -49,8 +44,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
if ($someProperties) { if ($someProperties) {
out += ' var isAdditional' + ($lvl) + ' = !(false '; out += ' var isAdditional' + ($lvl) + ' = !(false ';
if ($schemaKeys.length) { if ($schemaKeys.length) {
if ($schemaKeys.length > 5) { if ($schemaKeys.length > 8) {
out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] '; out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
} else { } else {
var arr1 = $schemaKeys; var arr1 = $schemaKeys;
if (arr1) { 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) + ') { '; out += ' ); if (isAdditional' + ($lvl) + ') { ';
} }
if ($removeAdditional == 'all') { if ($removeAdditional == 'all') {
@ -108,7 +92,13 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
if (it.createErrors !== false) { if (it.createErrors !== false) {
out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
if (it.opts.messages !== false) { 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) { if (it.opts.verbose) {
out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; 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; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -185,12 +176,12 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
} }
var $useDefaults = it.opts.useDefaults && !it.compositeRule; var $useDefaults = it.opts.useDefaults && !it.compositeRule;
if ($schemaKeys.length) { if ($schemaKeys.length) {
var arr4 = $schemaKeys; var arr3 = $schemaKeys;
if (arr4) { if (arr3) {
var $propertyKey, i4 = -1, var $propertyKey, i3 = -1,
l4 = arr4.length - 1; l3 = arr3.length - 1;
while (i4 < l4) { while (i3 < l3) {
$propertyKey = arr4[i4 += 1]; $propertyKey = arr3[i3 += 1];
var $sch = $schema[$propertyKey]; var $sch = $schema[$propertyKey];
if (it.util.schemaHasRules($sch, it.RULES.all)) { if (it.util.schemaHasRules($sch, it.RULES.all)) {
var $prop = it.util.getProperty($propertyKey), var $prop = it.util.getProperty($propertyKey),
@ -249,7 +240,8 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -287,12 +279,12 @@ module.exports = function generate_properties(it, $keyword, $ruleType) {
} }
} }
if ($pPropertyKeys.length) { if ($pPropertyKeys.length) {
var arr5 = $pPropertyKeys; var arr4 = $pPropertyKeys;
if (arr5) { if (arr4) {
var $pProperty, i5 = -1, var $pProperty, i4 = -1,
l5 = arr5.length - 1; l4 = arr4.length - 1;
while (i5 < l5) { while (i4 < l4) {
$pProperty = arr5[i5 += 1]; $pProperty = arr4[i4 += 1];
var $sch = $pProperties[$pProperty]; var $sch = $pProperties[$pProperty];
if (it.util.schemaHasRules($sch, it.RULES.all)) { if (it.util.schemaHasRules($sch, it.RULES.all)) {
$it.schema = $sch; $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) { if ($breakOnError) {
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
} }

View File

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

View File

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

View File

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

View File

@ -21,7 +21,21 @@ module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
if ($isData) { if ($isData) {
out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; 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) { if ($isData) {
out += ' } '; out += ' } ';
} }
@ -49,7 +63,8 @@ module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } 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'), $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
$id = it.self._getId(it.schema); $id = it.self._getId(it.schema);
if (it.isTop) { if (it.isTop) {
if ($async) {
it.async = true;
var $es7 = it.opts.async == 'es7';
it.yieldAwait = $es7 ? 'await' : 'yield';
}
out += ' var validate = '; out += ' var validate = ';
if ($async) { if ($async) {
if ($es7) { it.async = true;
out += ' (async function '; out += 'async ';
} else {
if (it.opts.async != '*') {
out += 'co.wrap';
}
out += '(function* ';
}
} else {
out += ' (function ';
} }
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)) { if ($id && (it.opts.sourceCode || it.opts.processCode)) {
out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
} }
@ -62,7 +49,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -83,7 +71,7 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
} }
if (it.isTop) { if (it.isTop) {
out += ' }); return validate; '; out += ' }; return validate; ';
} }
return out; return out;
} }
@ -114,6 +102,14 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
var $errorKeyword; var $errorKeyword;
var $typeSchema = it.schema.type, var $typeSchema = it.schema.type,
$typeIsArray = Array.isArray($typeSchema); $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) { if ($typeIsArray && $typeSchema.length == 1) {
$typeSchema = $typeSchema[0]; $typeSchema = $typeSchema[0];
$typeIsArray = false; $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 + '"'); 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 ($typeSchema) {
if (it.opts.coerceTypes) { if (it.opts.coerceTypes) {
var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
@ -207,7 +206,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -254,7 +254,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -280,9 +281,6 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
$closingBraces2 += '}'; $closingBraces2 += '}';
} }
} else { } 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; var arr2 = it.RULES;
if (arr2) { if (arr2) {
var $rulesGroup, i2 = -1, var $rulesGroup, i2 = -1,
@ -306,7 +304,11 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
var $sch = $schema[$propertyKey]; var $sch = $schema[$propertyKey];
if ($sch.default !== undefined) { if ($sch.default !== undefined) {
var $passData = $data + it.util.getProperty($propertyKey); 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') { if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' '; out += ' ' + (it.useDefault($sch.default)) + ' ';
} else { } else {
@ -325,7 +327,11 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
$sch = arr4[$i += 1]; $sch = arr4[$i += 1];
if ($sch.default !== undefined) { if ($sch.default !== undefined) {
var $passData = $data + '[' + $i + ']'; 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') { if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' '; out += ' ' + (it.useDefault($sch.default)) + ' ';
} else { } else {
@ -393,7 +399,8 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
} }
var __err = out; var __err = out;
out = $$outStack.pop(); out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) { if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); '; out += ' throw new ValidationError([' + (__err) + ']); ';
} else { } else {
@ -430,7 +437,7 @@ module.exports = function generate_validate(it, $keyword, $ruleType) {
out += ' validate.errors = vErrors; '; out += ' validate.errors = vErrors; ';
out += ' return errors === 0; '; out += ' return errors === 0; ';
} }
out += ' }); return validate;'; out += ' }; return validate;';
} else { } else {
out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
} }

View File

@ -51,7 +51,7 @@ function addKeyword(keyword, definition) {
metaSchema = { metaSchema = {
anyOf: [ anyOf: [
metaSchema, 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#", "$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#", "$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#",
"description": "Meta-schema for $data reference (JSON-schema extension proposal)", "description": "Meta-schema for $data reference (JSON Schema extension proposal)",
"type": "object", "type": "object",
"required": [ "$data" ], "required": [ "$data" ],
"properties": { "properties": {

View File

@ -28,12 +28,10 @@
"type": "object", "type": "object",
"properties": { "properties": {
"id": { "id": {
"type": "string", "type": "string"
"format": "uri"
}, },
"$schema": { "$schema": {
"type": "string", "type": "string"
"format": "uri"
}, },
"title": { "title": {
"type": "string" "type": "string"
@ -137,6 +135,7 @@
} }
] ]
}, },
"format": { "type": "string" },
"allOf": { "$ref": "#/definitions/schemaArray" }, "allOf": { "$ref": "#/definitions/schemaArray" },
"anyOf": { "$ref": "#/definitions/schemaArray" }, "anyOf": { "$ref": "#/definitions/schemaArray" },
"oneOf": { "$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", "name": "ajv",
"version": "5.5.2", "version": "6.8.1",
"description": "Another JSON Schema Validator", "description": "Another JSON Schema Validator",
"main": "lib/ajv.js", "main": "lib/ajv.js",
"typings": "lib/ajv.d.ts", "typings": "lib/ajv.d.ts",
@ -12,23 +12,20 @@
".tonic_example.js" ".tonic_example.js"
], ],
"scripts": { "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/**/*", "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-fast": "AJV_FAST_TEST=true npm run test-spec",
"test-debug": "mocha spec/*.spec.js --debug-brk -R spec", "test-debug": "mocha spec/*.spec.js --debug-brk -R spec",
"test-cov": "nyc npm run test-spec", "test-cov": "nyc npm run test-spec",
"test-ts": "tsc --target ES5 --noImplicitAny lib/ajv.d.ts", "test-ts": "tsc --target ES5 --noImplicitAny --noEmit spec/typescript/index.ts",
"bundle": "node ./scripts/bundle.js . Ajv pure_getters", "bundle": "del-cli dist && 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",
"bundle-beautify": "node ./scripts/bundle.js js-beautify", "bundle-beautify": "node ./scripts/bundle.js js-beautify",
"build": "del-cli lib/dotjs/*.js && node scripts/compile-dots.js", "build": "del-cli lib/dotjs/*.js '!lib/dotjs/index.js' && node scripts/compile-dots.js",
"test-karma": "karma start --single-run --browsers PhantomJS", "test-karma": "karma start",
"test-browser": "del-cli .browser && npm run bundle-all && scripts/prepare-tests && npm run test-karma", "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 4 npm run test-browser", "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-all", "prepublish": "npm run build && npm run bundle",
"watch": "watch 'npm run build' ./lib/dot" "watch": "watch 'npm run build' ./lib/dot"
}, },
"nyc": { "nyc": {
@ -63,41 +60,37 @@
"homepage": "https://github.com/epoberezkin/ajv", "homepage": "https://github.com/epoberezkin/ajv",
"tonicExampleFilename": ".tonic_example.js", "tonicExampleFilename": ".tonic_example.js",
"dependencies": { "dependencies": {
"co": "^4.6.0", "fast-deep-equal": "^2.0.1",
"fast-deep-equal": "^1.0.0",
"fast-json-stable-stringify": "^2.0.0", "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": { "devDependencies": {
"ajv-async": "^0.1.0", "ajv-async": "^1.0.0",
"bluebird": "^3.1.5", "bluebird": "^3.5.3",
"brfs": "^1.4.3", "brfs": "^2.0.0",
"browserify": "^14.1.0", "browserify": "^16.2.0",
"chai": "^4.0.1", "chai": "^4.0.1",
"coveralls": "^3.0.0", "coveralls": "^3.0.1",
"del-cli": "^1.1.0", "del-cli": "^1.1.0",
"dot": "^1.0.3", "dot": "^1.0.3",
"eslint": "^4.1.0", "eslint": "^5.0.0",
"gh-pages-generator": "^0.2.0", "gh-pages-generator": "^0.2.3",
"glob": "^7.0.0", "glob": "^7.0.0",
"if-node-version": "^1.0.0", "if-node-version": "^1.0.0",
"js-beautify": "^1.7.3", "js-beautify": "^1.7.3",
"jshint": "^2.9.4", "jshint": "^2.9.4",
"json-schema-test": "^2.0.0", "json-schema-test": "^2.0.0",
"karma": "^1.0.0", "karma": "^3.0.0",
"karma-chrome-launcher": "^2.0.0", "karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.1.1", "karma-mocha": "^1.1.1",
"karma-phantomjs-launcher": "^1.0.0", "karma-sauce-launcher": "^2.0.0",
"karma-sauce-launcher": "^1.1.0", "mocha": "^5.1.1",
"mocha": "^4.0.0", "nyc": "^12.0.1",
"nodent": "^3.0.17",
"nyc": "^11.0.2",
"phantomjs-prebuilt": "^2.1.4",
"pre-commit": "^1.1.1", "pre-commit": "^1.1.1",
"regenerator": "^0.12.2",
"require-globify": "^1.3.0", "require-globify": "^1.3.0",
"typescript": "^2.6.2", "typescript": "^2.8.3",
"uglify-js": "^3.1.5", "uglify-js": "^3.3.24",
"watch": "^1.0.0" "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) { RequestSigner.prototype.matchHost = function(host) {
var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/) var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)
var hostParts = (match || []).slice(1, 3) var hostParts = (match || []).slice(1, 3)
// ES's hostParts are sometimes the other way round, if the value that is expected // 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 === '..') { if (normalizePath && piece === '..') {
path.pop() path.pop()
} else if (!normalizePath || piece !== '.') { } else if (!normalizePath || piece !== '.') {
if (decodePath) piece = querystring.unescape(piece) if (decodePath) piece = decodeURIComponent(piece)
path.push(encodeRfc3986(querystring.escape(piece))) path.push(encodeRfc3986(encodeURIComponent(piece)))
} }
return path return path
}, []).join('/') }, []).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 // 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)) { if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
path = path.split('/').map(function(piece) { path = path.split('/').map(function(piece) {
return querystring.escape(querystring.unescape(piece)) return encodeURIComponent(decodeURIComponent(piece))
}).join('/') }).join('/')
} }

View File

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

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