simpl-schema
Advanced tools
Comparing version 1.5.5 to 1.5.6
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,37 +6,26 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; | ||
var _clone = _interopRequireDefault(require("clone")); | ||
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 _lodash = _interopRequireDefault(require("lodash.isempty")); | ||
var _clone = require('clone'); | ||
var _mongoObject = _interopRequireDefault(require("mongo-object")); | ||
var _clone2 = _interopRequireDefault(_clone); | ||
var _utility = require("./utility"); | ||
var _lodash = require('lodash.isempty'); | ||
var _SimpleSchema = require("./SimpleSchema"); | ||
var _lodash2 = _interopRequireDefault(_lodash); | ||
var _convertToProperType = _interopRequireDefault(require("./clean/convertToProperType")); | ||
var _mongoObject = require('mongo-object'); | ||
var _setAutoValues = _interopRequireDefault(require("./clean/setAutoValues")); | ||
var _mongoObject2 = _interopRequireDefault(_mongoObject); | ||
var _typeValidator = _interopRequireDefault(require("./validation/typeValidator")); | ||
var _utility = require('./utility'); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var _SimpleSchema = require('./SimpleSchema'); | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
var _convertToProperType = require('./clean/convertToProperType'); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
var _convertToProperType2 = _interopRequireDefault(_convertToProperType); | ||
var _setAutoValues = require('./clean/setAutoValues'); | ||
var _setAutoValues2 = _interopRequireDefault(_setAutoValues); | ||
var _typeValidator = require('./validation/typeValidator'); | ||
var _typeValidator2 = _interopRequireDefault(_typeValidator); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
@@ -64,19 +53,14 @@ * @param {SimpleSchema} ss - A SimpleSchema instance | ||
*/ | ||
function clean(ss, doc) { | ||
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
function clean(ss, doc, options = {}) { | ||
// By default, doc will be filtered and autoconverted | ||
options = _extends({ | ||
options = _objectSpread({ | ||
isModifier: (0, _utility.looksLikeModifier)(doc), | ||
isUpsert: false | ||
}, ss._cleanOptions, options); | ||
}, ss._cleanOptions, options); // Clone so we do not mutate | ||
// Clone so we do not mutate | ||
var cleanDoc = options.mutate ? doc : (0, _clone2.default)(doc); | ||
const cleanDoc = options.mutate ? doc : (0, _clone.default)(doc); | ||
const mongoObject = options.mongoObject || new _mongoObject.default(cleanDoc, ss.blackboxKeys()); // Clean loop | ||
var mongoObject = options.mongoObject || new _mongoObject2.default(cleanDoc, ss.blackboxKeys()); | ||
// Clean loop | ||
if (options.filter || options.autoConvert || options.removeEmptyStrings || options.trimStrings) { | ||
var removedPositions = []; // For removing now-empty objects after | ||
const removedPositions = []; // For removing now-empty objects after | ||
@@ -87,12 +71,8 @@ mongoObject.forEachNode(function eachNode() { | ||
if (this.operator === '$unset') return; | ||
var gKey = this.genericKey; | ||
const gKey = this.genericKey; | ||
if (!gKey) return; | ||
var val = this.value; | ||
let val = this.value; | ||
if (val === undefined) return; | ||
let p; // Filter out props if necessary | ||
var p = void 0; | ||
// Filter out props if necessary | ||
if (options.filter && !ss.allowsKey(gKey) || options.removeNullsFromArrays && this.isArrayItem && val === null) { | ||
@@ -107,20 +87,22 @@ // XXX Special handling for $each; maybe this could be made nicer | ||
} | ||
if (_SimpleSchema.SimpleSchema.debug) { | ||
console.info('SimpleSchema.clean: filtered out value that would have affected key "' + gKey + '", which is not allowed by the schema'); | ||
console.info(`SimpleSchema.clean: filtered out value that would have affected key "${gKey}", which is not allowed by the schema`); | ||
} | ||
return; // no reason to do more | ||
} | ||
var outerDef = ss.schema(gKey); | ||
var defs = outerDef && outerDef.type.definitions; | ||
var def = defs && defs[0]; | ||
const outerDef = ss.schema(gKey); | ||
const defs = outerDef && outerDef.type.definitions; | ||
const def = defs && defs[0]; // Autoconvert values if requested and if possible | ||
// Autoconvert values if requested and if possible | ||
if (options.autoConvert && def) { | ||
var isValidType = defs.some(function (definition) { | ||
var errors = _typeValidator2.default.call({ | ||
const isValidType = defs.some(definition => { | ||
const errors = _typeValidator.default.call({ | ||
valueShouldBeChecked: true, | ||
definition: definition, | ||
definition, | ||
value: val | ||
}); | ||
return errors === undefined; | ||
@@ -130,5 +112,6 @@ }); | ||
if (!isValidType) { | ||
var newVal = (0, _convertToProperType2.default)(val, def.type); | ||
const newVal = (0, _convertToProperType.default)(val, def.type); | ||
if (newVal !== undefined && newVal !== val) { | ||
_SimpleSchema.SimpleSchema.debug && console.info('SimpleSchema.clean: autoconverted value ' + val + ' from ' + (typeof val === 'undefined' ? 'undefined' : _typeof(val)) + ' to ' + (typeof newVal === 'undefined' ? 'undefined' : _typeof(newVal)) + ' for ' + gKey); | ||
_SimpleSchema.SimpleSchema.debug && console.info(`SimpleSchema.clean: autoconverted value ${val} from ${typeof val} to ${typeof newVal} for ${gKey}`); | ||
val = newVal; | ||
@@ -138,22 +121,22 @@ this.updateValue(newVal); | ||
} | ||
} | ||
// Trim strings if | ||
} // Trim strings if | ||
// 1. The trimStrings option is `true` AND | ||
// 2. The field is not in the schema OR is in the schema with `trim` !== `false` AND | ||
// 3. The value is a string. | ||
if (options.trimStrings && (!def || def.trim !== false) && typeof val === 'string') { | ||
val = val.trim(); | ||
this.updateValue(val); | ||
} | ||
// Remove empty strings if | ||
} // Remove empty strings if | ||
// 1. The removeEmptyStrings option is `true` AND | ||
// 2. The value is in a normal object or in the $set part of a modifier | ||
// 3. The value is an empty string. | ||
if (options.removeEmptyStrings && (!this.operator || this.operator === '$set') && typeof val === 'string' && !val.length) { | ||
// For a document, we remove any fields that are being set to an empty string | ||
this.remove(); | ||
// For a modifier, we $unset any fields that are being set to an empty string. | ||
this.remove(); // For a modifier, we $unset any fields that are being set to an empty string. | ||
// But only if we're not already within an entire object that is being set. | ||
if (this.operator === '$set' && this.position.match(/\[.+?\]/g).length < 2) { | ||
@@ -164,25 +147,25 @@ p = this.position.replace('$set', '$unset'); | ||
} | ||
}, { endPointsOnly: false }); | ||
}, { | ||
endPointsOnly: false | ||
}); // Remove any objects that are now empty after filtering | ||
// Remove any objects that are now empty after filtering | ||
removedPositions.forEach(function (removedPosition) { | ||
var lastBrace = removedPosition.lastIndexOf('['); | ||
removedPositions.forEach(removedPosition => { | ||
const lastBrace = removedPosition.lastIndexOf('['); | ||
if (lastBrace !== -1) { | ||
var removedPositionParent = removedPosition.slice(0, lastBrace); | ||
var value = mongoObject.getValueForPosition(removedPositionParent); | ||
if ((0, _lodash2.default)(value)) mongoObject.removeValueForPosition(removedPositionParent); | ||
const removedPositionParent = removedPosition.slice(0, lastBrace); | ||
const value = mongoObject.getValueForPosition(removedPositionParent); | ||
if ((0, _lodash.default)(value)) mongoObject.removeValueForPosition(removedPositionParent); | ||
} | ||
}); | ||
mongoObject.removeArrayItems(); | ||
} | ||
} // Set automatic values | ||
// Set automatic values | ||
options.getAutoValues && (0, _setAutoValues2.default)(ss.autoValueFunctions(), mongoObject, options.isModifier, options.isUpsert, options.extendAutoValueContext); | ||
// Ensure we don't have any operators set to an empty object | ||
options.getAutoValues && (0, _setAutoValues.default)(ss.autoValueFunctions(), mongoObject, options.isModifier, options.isUpsert, options.extendAutoValueContext); // Ensure we don't have any operators set to an empty object | ||
// since MongoDB 2.6+ will throw errors. | ||
if (options.isModifier) { | ||
Object.keys(cleanDoc || {}).forEach(function (op) { | ||
if ((0, _lodash2.default)(cleanDoc[op])) delete cleanDoc[op]; | ||
Object.keys(cleanDoc || {}).forEach(op => { | ||
if ((0, _lodash.default)(cleanDoc[op])) delete cleanDoc[op]; | ||
}); | ||
@@ -194,2 +177,5 @@ } | ||
exports.default = clean; | ||
var _default = clean; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,25 +6,18 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; | ||
var _clone = _interopRequireDefault(require("clone")); | ||
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 _lodash = _interopRequireDefault(require("lodash.includes")); | ||
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 _utility = require("../utility"); | ||
var _clone = require('clone'); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var _clone2 = _interopRequireDefault(_clone); | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
var _lodash = require('lodash.includes'); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
var _lodash2 = _interopRequireDefault(_lodash); | ||
var _utility = require('../utility'); | ||
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"); } } | ||
function getFieldInfo(mongoObject, key) { | ||
var keyInfo = mongoObject.getInfoForKey(key) || {}; | ||
const keyInfo = mongoObject.getInfoForKey(key) || {}; | ||
return { | ||
@@ -37,6 +30,4 @@ isSet: keyInfo.value !== undefined, | ||
var AutoValueRunner = function () { | ||
function AutoValueRunner(options) { | ||
_classCallCheck(this, AutoValueRunner); | ||
class AutoValueRunner { | ||
constructor(options) { | ||
this.options = options; | ||
@@ -46,104 +37,100 @@ this.doneKeys = []; | ||
_createClass(AutoValueRunner, [{ | ||
key: 'runForPosition', | ||
value: function runForPosition(_ref) { | ||
var affectedKey = _ref.key, | ||
operator = _ref.operator, | ||
position = _ref.position, | ||
value = _ref.value; | ||
var _options = this.options, | ||
closestSubschemaFieldName = _options.closestSubschemaFieldName, | ||
extendedAutoValueContext = _options.extendedAutoValueContext, | ||
func = _options.func, | ||
isModifier = _options.isModifier, | ||
isUpsert = _options.isUpsert, | ||
mongoObject = _options.mongoObject; | ||
runForPosition({ | ||
key: affectedKey, | ||
operator, | ||
position, | ||
value | ||
}) { | ||
const { | ||
closestSubschemaFieldName, | ||
extendedAutoValueContext, | ||
func, | ||
isModifier, | ||
isUpsert, | ||
mongoObject | ||
} = this.options; // If already called for this key, skip it | ||
// If already called for this key, skip it | ||
if ((0, _lodash.default)(this.doneKeys, affectedKey)) return; | ||
const fieldParentName = (0, _utility.getParentOfKey)(affectedKey, true); | ||
const parentFieldInfo = getFieldInfo(mongoObject, fieldParentName.slice(0, -1)); | ||
let doUnset = false; | ||
if ((0, _lodash2.default)(this.doneKeys, affectedKey)) return; | ||
if (Array.isArray(parentFieldInfo.value)) { | ||
if (isNaN(affectedKey.split('.').slice(-1).pop())) { | ||
// parent is an array, but the key to be set is not an integer (see issue #80) | ||
return; | ||
} | ||
} | ||
var fieldParentName = (0, _utility.getParentOfKey)(affectedKey, true); | ||
var parentFieldInfo = getFieldInfo(mongoObject, fieldParentName.slice(0, -1)); | ||
const autoValue = func.call(_objectSpread({ | ||
closestSubschemaFieldName: closestSubschemaFieldName.length ? closestSubschemaFieldName : null, | ||
var doUnset = false; | ||
field(fName) { | ||
return getFieldInfo(mongoObject, closestSubschemaFieldName + fName); | ||
}, | ||
if (Array.isArray(parentFieldInfo.value)) { | ||
if (isNaN(affectedKey.split('.').slice(-1).pop())) { | ||
// parent is an array, but the key to be set is not an integer (see issue #80) | ||
return; | ||
} | ||
} | ||
isModifier, | ||
isUpsert, | ||
isSet: value !== undefined, | ||
key: affectedKey, | ||
operator, | ||
var autoValue = func.call(_extends({ | ||
closestSubschemaFieldName: closestSubschemaFieldName.length ? closestSubschemaFieldName : null, | ||
field: function field(fName) { | ||
return getFieldInfo(mongoObject, closestSubschemaFieldName + fName); | ||
}, | ||
parentField() { | ||
return parentFieldInfo; | ||
}, | ||
isModifier: isModifier, | ||
isUpsert: isUpsert, | ||
isSet: value !== undefined, | ||
key: affectedKey, | ||
operator: operator, | ||
parentField: function parentField() { | ||
return parentFieldInfo; | ||
}, | ||
siblingField: function siblingField(fName) { | ||
return getFieldInfo(mongoObject, fieldParentName + fName); | ||
}, | ||
unset: function unset() { | ||
doUnset = true; | ||
}, | ||
siblingField(fName) { | ||
return getFieldInfo(mongoObject, fieldParentName + fName); | ||
}, | ||
value: value | ||
}, extendedAutoValueContext || {}), mongoObject.getObject()); | ||
unset() { | ||
doUnset = true; | ||
}, | ||
// Update tracking of which keys we've run autovalue for | ||
this.doneKeys.push(affectedKey); | ||
value | ||
}, extendedAutoValueContext || {}), mongoObject.getObject()); // Update tracking of which keys we've run autovalue for | ||
if (doUnset && position) mongoObject.removeValueForPosition(position); | ||
this.doneKeys.push(affectedKey); | ||
if (doUnset && position) mongoObject.removeValueForPosition(position); | ||
if (autoValue === undefined) return; // If the user's auto value is of the pseudo-modifier format, parse it | ||
// into operator and value. | ||
if (autoValue === undefined) return; | ||
if (isModifier) { | ||
let op; | ||
let newValue; | ||
// If the user's auto value is of the pseudo-modifier format, parse it | ||
// into operator and value. | ||
if (isModifier) { | ||
var op = void 0; | ||
var newValue = void 0; | ||
if (autoValue && (typeof autoValue === 'undefined' ? 'undefined' : _typeof(autoValue)) === 'object') { | ||
var avOperator = Object.keys(autoValue).find(function (avProp) { | ||
return avProp.substring(0, 1) === '$'; | ||
}); | ||
if (avOperator) { | ||
op = avOperator; | ||
newValue = autoValue[avOperator]; | ||
} | ||
} | ||
if (autoValue && typeof autoValue === 'object') { | ||
const avOperator = Object.keys(autoValue).find(avProp => avProp.substring(0, 1) === '$'); | ||
// Add $set for updates and upserts if necessary. Keep this | ||
// above the "if (op)" block below since we might change op | ||
// in this line. | ||
if (!op && position.slice(0, 1) !== '$') { | ||
op = '$set'; | ||
newValue = autoValue; | ||
if (avOperator) { | ||
op = avOperator; | ||
newValue = autoValue[avOperator]; | ||
} | ||
} // Add $set for updates and upserts if necessary. Keep this | ||
// above the "if (op)" block below since we might change op | ||
// in this line. | ||
if (op) { | ||
// Update/change value | ||
mongoObject.removeValueForPosition(position); | ||
mongoObject.setValueForPosition(op + '[' + affectedKey + ']', (0, _clone2.default)(newValue)); | ||
return; | ||
} | ||
if (!op && position.slice(0, 1) !== '$') { | ||
op = '$set'; | ||
newValue = autoValue; | ||
} | ||
// Update/change value. Cloning is necessary in case it's an object, because | ||
// if we later set some keys within it, they'd be set on the original object, too. | ||
mongoObject.setValueForPosition(position, (0, _clone2.default)(autoValue)); | ||
} | ||
}]); | ||
if (op) { | ||
// Update/change value | ||
mongoObject.removeValueForPosition(position); | ||
mongoObject.setValueForPosition(`${op}[${affectedKey}]`, (0, _clone.default)(newValue)); | ||
return; | ||
} | ||
} // Update/change value. Cloning is necessary in case it's an object, because | ||
// if we later set some keys within it, they'd be set on the original object, too. | ||
return AutoValueRunner; | ||
}(); | ||
exports.default = AutoValueRunner; | ||
mongoObject.setValueForPosition(position, (0, _clone.default)(autoValue)); | ||
} | ||
} | ||
exports.default = AutoValueRunner; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; | ||
var _SimpleSchema = require("../SimpleSchema"); | ||
var _SimpleSchema = require('../SimpleSchema'); | ||
/** | ||
@@ -21,34 +20,35 @@ * Converts value to proper type | ||
// Can't and shouldn't convert arrays or objects or null | ||
if (Array.isArray(value) || value && (typeof value === 'function' || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') && !(value instanceof Date) || value === null) return value; | ||
if (Array.isArray(value) || value && (typeof value === 'function' || typeof value === 'object') && !(value instanceof Date) || value === null) return value; // Convert to String type | ||
// Convert to String type | ||
if (type === String) { | ||
if (value === null || value === undefined) return value; | ||
return value.toString(); | ||
} | ||
} // Convert to Number type | ||
// Convert to Number type | ||
if (type === Number || type === _SimpleSchema.SimpleSchema.Integer) { | ||
if (typeof value === 'string' && value.length > 0) { | ||
// Try to convert numeric strings to numbers | ||
var numberVal = Number(value); | ||
const numberVal = Number(value); | ||
if (!isNaN(numberVal)) return numberVal; | ||
} | ||
// Leave it; will fail validation | ||
} // Leave it; will fail validation | ||
return value; | ||
} | ||
// If target type is a Date we can safely convert from either a | ||
} // If target type is a Date we can safely convert from either a | ||
// number (Integer value representing the number of milliseconds | ||
// since 1 January 1970 00:00:00 UTC) or a string that can be parsed | ||
// by Date. | ||
if (type === Date) { | ||
if (typeof value === 'string') { | ||
var parsedDate = Date.parse(value); | ||
const parsedDate = Date.parse(value); | ||
if (isNaN(parsedDate) === false) return new Date(parsedDate); | ||
} | ||
if (typeof value === 'number') return new Date(value); | ||
} | ||
} // Convert to Boolean type | ||
// Convert to Boolean type | ||
if (type === Boolean) { | ||
@@ -62,11 +62,13 @@ if (typeof value === 'string') { | ||
} | ||
} | ||
} // If an array is what you want, I'll give you an array | ||
// If an array is what you want, I'll give you an array | ||
if (type === Array) return [value]; | ||
// Could not convert | ||
if (type === Array) return [value]; // Could not convert | ||
return value; | ||
} | ||
exports.default = convertToProperType; | ||
var _default = convertToProperType; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -8,8 +8,6 @@ Object.defineProperty(exports, "__esModule", { | ||
var _mongoObject = require('mongo-object'); | ||
var _mongoObject = _interopRequireDefault(require("mongo-object")); | ||
var _mongoObject2 = _interopRequireDefault(_mongoObject); | ||
var _utility = require("../utility"); | ||
var _utility = require('../utility'); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -42,18 +40,17 @@ | ||
*/ | ||
function getPositionsForAutoValue(_ref) { | ||
var fieldName = _ref.fieldName, | ||
isModifier = _ref.isModifier, | ||
mongoObject = _ref.mongoObject; | ||
function getPositionsForAutoValue({ | ||
fieldName, | ||
isModifier, | ||
mongoObject | ||
}) { | ||
// Positions for this field | ||
var positions = mongoObject.getPositionsInfoForGenericKey(fieldName); | ||
const positions = mongoObject.getPositionsInfoForGenericKey(fieldName); // If the field is an object and will be created by MongoDB, | ||
// we don't need (and can't have) a value for it | ||
// If the field is an object and will be created by MongoDB, | ||
// we don't need (and can't have) a value for it | ||
if (isModifier && mongoObject.getPositionsThatCreateGenericKey(fieldName).length > 0) { | ||
return positions; | ||
} | ||
} // For simple top-level fields, just add an undefined would-be position | ||
// if there isn't a real position. | ||
// For simple top-level fields, just add an undefined would-be position | ||
// if there isn't a real position. | ||
if (fieldName.indexOf('.') === -1 && positions.length === 0) { | ||
@@ -64,3 +61,3 @@ positions.push({ | ||
operator: isModifier ? '$set' : null, | ||
position: isModifier ? '$set[' + fieldName + ']' : fieldName | ||
position: isModifier ? `$set[${fieldName}]` : fieldName | ||
}); | ||
@@ -70,15 +67,14 @@ return positions; | ||
var parentPath = (0, _utility.getParentOfKey)(fieldName); | ||
var lastPart = (0, _utility.getLastPartOfKey)(fieldName, parentPath); | ||
var lastPartWithBraces = lastPart.replace(/\./g, ']['); | ||
var parentPositions = mongoObject.getPositionsInfoForGenericKey(parentPath); | ||
const parentPath = (0, _utility.getParentOfKey)(fieldName); | ||
const lastPart = (0, _utility.getLastPartOfKey)(fieldName, parentPath); | ||
const lastPartWithBraces = lastPart.replace(/\./g, ']['); | ||
const parentPositions = mongoObject.getPositionsInfoForGenericKey(parentPath); | ||
if (parentPositions.length) { | ||
parentPositions.forEach(function (info) { | ||
var childPosition = info.position + '[' + lastPartWithBraces + ']'; | ||
if (!positions.find(function (i) { | ||
return i.position === childPosition; | ||
})) { | ||
parentPositions.forEach(info => { | ||
const childPosition = `${info.position}[${lastPartWithBraces}]`; | ||
if (!positions.find(i => i.position === childPosition)) { | ||
positions.push({ | ||
key: info.key + '.' + lastPart, | ||
key: `${info.key}.${lastPart}`, | ||
value: undefined, | ||
@@ -92,13 +88,15 @@ operator: info.operator, | ||
// positions that will create parentPath | ||
mongoObject.getPositionsThatCreateGenericKey(parentPath).forEach(function (info) { | ||
var operator = info.operator, | ||
position = info.position; | ||
mongoObject.getPositionsThatCreateGenericKey(parentPath).forEach(info => { | ||
const { | ||
operator, | ||
position | ||
} = info; | ||
let wouldBePosition; | ||
var wouldBePosition = void 0; | ||
if (operator) { | ||
var next = position.slice(position.indexOf('[') + 1, position.indexOf(']')); | ||
var nextPieces = next.split('.'); | ||
const next = position.slice(position.indexOf('[') + 1, position.indexOf(']')); | ||
const nextPieces = next.split('.'); | ||
const newPieces = []; | ||
let newKey; | ||
var newPieces = []; | ||
var newKey = void 0; | ||
while (nextPieces.length && newKey !== parentPath) { | ||
@@ -108,14 +106,14 @@ newPieces.push(nextPieces.shift()); | ||
} | ||
newKey = newKey + '.' + fieldName.slice(newKey.length + 1); | ||
wouldBePosition = '$set[' + newKey + ']'; | ||
newKey = `${newKey}.${fieldName.slice(newKey.length + 1)}`; | ||
wouldBePosition = `$set[${newKey}]`; | ||
} else { | ||
var lastPart2 = (0, _utility.getLastPartOfKey)(fieldName, parentPath); | ||
var lastPartWithBraces2 = lastPart2.replace(/\./g, ']['); | ||
wouldBePosition = position.slice(0, position.lastIndexOf('[')) + '[' + lastPartWithBraces2 + ']'; | ||
const lastPart2 = (0, _utility.getLastPartOfKey)(fieldName, parentPath); | ||
const lastPartWithBraces2 = lastPart2.replace(/\./g, ']['); | ||
wouldBePosition = `${position.slice(0, position.lastIndexOf('['))}[${lastPartWithBraces2}]`; | ||
} | ||
if (!positions.find(function (i) { | ||
return i.position === wouldBePosition; | ||
})) { | ||
if (!positions.find(i => i.position === wouldBePosition)) { | ||
positions.push({ | ||
key: _mongoObject2.default._positionToKey(wouldBePosition), | ||
key: _mongoObject.default._positionToKey(wouldBePosition), | ||
value: undefined, | ||
@@ -130,2 +128,5 @@ operator: operator ? '$set' : null, | ||
return positions; | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -7,11 +7,8 @@ Object.defineProperty(exports, "__esModule", { | ||
exports.sortAutoValueFunctions = sortAutoValueFunctions; | ||
exports.default = void 0; | ||
var _getPositionsForAutoValue = require('./getPositionsForAutoValue'); | ||
var _getPositionsForAutoValue = _interopRequireDefault(require("./getPositionsForAutoValue")); | ||
var _getPositionsForAutoValue2 = _interopRequireDefault(_getPositionsForAutoValue); | ||
var _AutoValueRunner = _interopRequireDefault(require("./AutoValueRunner")); | ||
var _AutoValueRunner = require('./AutoValueRunner'); | ||
var _AutoValueRunner2 = _interopRequireDefault(_AutoValueRunner); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -28,18 +25,16 @@ | ||
function sortAutoValueFunctions(autoValueFunctions) { | ||
var defaultFieldOrder = autoValueFunctions.reduce(function (acc, _ref, index) { | ||
var fieldName = _ref.fieldName; | ||
const defaultFieldOrder = autoValueFunctions.reduce((acc, { | ||
fieldName | ||
}, index) => { | ||
acc[fieldName] = index; | ||
return acc; | ||
}, {}); | ||
// Sort by how many dots each field name has, asc, such that we can auto-create | ||
}, {}); // Sort by how many dots each field name has, asc, such that we can auto-create | ||
// objects and arrays before we run the autoValues for properties within them. | ||
// Fields of the same level (same number of dots) preserve should order from the original array. | ||
return autoValueFunctions.sort(function (a, b) { | ||
var depthDiff = a.fieldName.split('.').length - b.fieldName.split('.').length; | ||
return autoValueFunctions.sort((a, b) => { | ||
const depthDiff = a.fieldName.split('.').length - b.fieldName.split('.').length; | ||
return depthDiff === 0 ? defaultFieldOrder[a.fieldName] - defaultFieldOrder[b.fieldName] : depthDiff; | ||
}); | ||
} | ||
/** | ||
@@ -57,23 +52,26 @@ * @method setAutoValues | ||
*/ | ||
function setAutoValues(autoValueFunctions, mongoObject, isModifier, isUpsert, extendedAutoValueContext) { | ||
var sortedAutoValueFunctions = sortAutoValueFunctions(autoValueFunctions); | ||
sortedAutoValueFunctions.forEach(function (_ref2) { | ||
var func = _ref2.func, | ||
fieldName = _ref2.fieldName, | ||
closestSubschemaFieldName = _ref2.closestSubschemaFieldName; | ||
var avRunner = new _AutoValueRunner2.default({ | ||
closestSubschemaFieldName: closestSubschemaFieldName, | ||
extendedAutoValueContext: extendedAutoValueContext, | ||
func: func, | ||
isModifier: isModifier, | ||
isUpsert: isUpsert, | ||
mongoObject: mongoObject | ||
function setAutoValues(autoValueFunctions, mongoObject, isModifier, isUpsert, extendedAutoValueContext) { | ||
const sortedAutoValueFunctions = sortAutoValueFunctions(autoValueFunctions); | ||
sortedAutoValueFunctions.forEach(({ | ||
func, | ||
fieldName, | ||
closestSubschemaFieldName | ||
}) => { | ||
const avRunner = new _AutoValueRunner.default({ | ||
closestSubschemaFieldName, | ||
extendedAutoValueContext, | ||
func, | ||
isModifier, | ||
isUpsert, | ||
mongoObject | ||
}); | ||
const positions = (0, _getPositionsForAutoValue.default)({ | ||
fieldName, | ||
isModifier, | ||
mongoObject | ||
}); // Run the autoValue function once for each place in the object that | ||
// has a value or that potentially should. | ||
var positions = (0, _getPositionsForAutoValue2.default)({ fieldName: fieldName, isModifier: isModifier, mongoObject: mongoObject }); | ||
// Run the autoValue function once for each place in the object that | ||
// has a value or that potentially should. | ||
positions.forEach(avRunner.runForPosition.bind(avRunner)); | ||
@@ -83,2 +81,3 @@ }); | ||
exports.default = setAutoValues; | ||
var _default = setAutoValues; | ||
exports.default = _default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,16 +6,45 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
var _regExp = require('./regExp'); | ||
var _regExp = _interopRequireDefault(require("./regExp")); | ||
var _regExp2 = _interopRequireDefault(_regExp); | ||
var _lodash = _interopRequireDefault(require("lodash.find")); | ||
var _lodash = require('lodash.find'); | ||
var _lodash2 = _interopRequireDefault(_lodash); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var regExpMessages = [{ exp: _regExp2.default.Email, msg: 'must be a valid email address' }, { exp: _regExp2.default.EmailWithTLD, msg: 'must be a valid email address' }, { exp: _regExp2.default.Domain, msg: 'must be a valid domain' }, { exp: _regExp2.default.WeakDomain, msg: 'must be a valid domain' }, { exp: _regExp2.default.IP, msg: 'must be a valid IPv4 or IPv6 address' }, { exp: _regExp2.default.IPv4, msg: 'must be a valid IPv4 address' }, { exp: _regExp2.default.IPv6, msg: 'must be a valid IPv6 address' }, { exp: _regExp2.default.Url, msg: 'must be a valid URL' }, { exp: _regExp2.default.Id, msg: 'must be a valid alphanumeric ID' }, { exp: _regExp2.default.ZipCode, msg: 'must be a valid ZIP code' }, { exp: _regExp2.default.Phone, msg: 'must be a valid phone number' }]; | ||
var defaultMessages = { | ||
const regExpMessages = [{ | ||
exp: _regExp.default.Email, | ||
msg: 'must be a valid email address' | ||
}, { | ||
exp: _regExp.default.EmailWithTLD, | ||
msg: 'must be a valid email address' | ||
}, { | ||
exp: _regExp.default.Domain, | ||
msg: 'must be a valid domain' | ||
}, { | ||
exp: _regExp.default.WeakDomain, | ||
msg: 'must be a valid domain' | ||
}, { | ||
exp: _regExp.default.IP, | ||
msg: 'must be a valid IPv4 or IPv6 address' | ||
}, { | ||
exp: _regExp.default.IPv4, | ||
msg: 'must be a valid IPv4 address' | ||
}, { | ||
exp: _regExp.default.IPv6, | ||
msg: 'must be a valid IPv6 address' | ||
}, { | ||
exp: _regExp.default.Url, | ||
msg: 'must be a valid URL' | ||
}, { | ||
exp: _regExp.default.Id, | ||
msg: 'must be a valid alphanumeric ID' | ||
}, { | ||
exp: _regExp.default.ZipCode, | ||
msg: 'must be a valid ZIP code' | ||
}, { | ||
exp: _regExp.default.Phone, | ||
msg: 'must be a valid phone number' | ||
}]; | ||
const defaultMessages = { | ||
initialLanguage: 'en', | ||
@@ -39,17 +68,16 @@ messages: { | ||
expectedType: '{{{label}}} must be of type {{dataType}}', | ||
regEx: function regEx(_ref) { | ||
var label = _ref.label, | ||
regExp = _ref.regExp; | ||
regEx({ | ||
label, | ||
regExp | ||
}) { | ||
// See if there's one where exp matches this expression | ||
var msgObj = void 0; | ||
let msgObj; | ||
if (regExp) { | ||
msgObj = (0, _lodash2.default)(regExpMessages, function (o) { | ||
return o.exp && o.exp.toString() === regExp; | ||
}); | ||
msgObj = (0, _lodash.default)(regExpMessages, o => o.exp && o.exp.toString() === regExp); | ||
} | ||
var regExpMessage = msgObj ? msgObj.msg : 'failed regular expression validation'; | ||
return label + ' ' + regExpMessage; | ||
const regExpMessage = msgObj ? msgObj.msg : 'failed regular expression validation'; | ||
return `${label} ${regExpMessage}`; | ||
}, | ||
@@ -61,3 +89,5 @@ | ||
}; | ||
exports.default = defaultMessages; | ||
var _default = defaultMessages; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,45 +6,30 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; | ||
var _mongoObject = _interopRequireDefault(require("mongo-object")); | ||
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 _lodash = _interopRequireDefault(require("lodash.omit")); | ||
var _mongoObject = require('mongo-object'); | ||
var _lodash2 = _interopRequireDefault(require("lodash.isobject")); | ||
var _mongoObject2 = _interopRequireDefault(_mongoObject); | ||
var _lodash3 = _interopRequireDefault(require("lodash.union")); | ||
var _lodash = require('lodash.omit'); | ||
var _lodash4 = _interopRequireDefault(require("lodash.includes")); | ||
var _lodash2 = _interopRequireDefault(_lodash); | ||
var _SimpleSchema = require("./SimpleSchema"); | ||
var _lodash3 = require('lodash.isobject'); | ||
var _utility = require("./utility"); | ||
var _lodash4 = _interopRequireDefault(_lodash3); | ||
var _typeValidator = _interopRequireDefault(require("./validation/typeValidator")); | ||
var _lodash5 = require('lodash.union'); | ||
var _requiredValidator = _interopRequireDefault(require("./validation/requiredValidator")); | ||
var _lodash6 = _interopRequireDefault(_lodash5); | ||
var _allowedValuesValidator = _interopRequireDefault(require("./validation/allowedValuesValidator")); | ||
var _lodash7 = require('lodash.includes'); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var _lodash8 = _interopRequireDefault(_lodash7); | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
var _SimpleSchema = require('./SimpleSchema'); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
var _utility = require('./utility'); | ||
var _typeValidator = require('./validation/typeValidator'); | ||
var _typeValidator2 = _interopRequireDefault(_typeValidator); | ||
var _requiredValidator = require('./validation/requiredValidator'); | ||
var _requiredValidator2 = _interopRequireDefault(_requiredValidator); | ||
var _allowedValuesValidator = require('./validation/allowedValuesValidator'); | ||
var _allowedValuesValidator2 = _interopRequireDefault(_allowedValuesValidator); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function shouldCheck(key) { | ||
@@ -55,15 +40,15 @@ if (key === '$pushAll') throw new Error('$pushAll is not supported; use $push + $each'); | ||
function doValidation(_ref) { | ||
var extendedCustomContext = _ref.extendedCustomContext, | ||
ignoreTypes = _ref.ignoreTypes, | ||
isModifier = _ref.isModifier, | ||
isUpsert = _ref.isUpsert, | ||
keysToValidate = _ref.keysToValidate, | ||
mongoObject = _ref.mongoObject, | ||
obj = _ref.obj, | ||
schema = _ref.schema, | ||
validationContext = _ref.validationContext; | ||
function doValidation({ | ||
extendedCustomContext, | ||
ignoreTypes, | ||
isModifier, | ||
isUpsert, | ||
keysToValidate, | ||
mongoObject, | ||
obj, | ||
schema, | ||
validationContext | ||
}) { | ||
// First do some basic checks of the object, and throw errors if necessary | ||
if (!(0, _lodash4.default)(obj)) { | ||
if (!(0, _lodash2.default)(obj)) { | ||
throw new Error('The first argument of validate() must be an object'); | ||
@@ -76,5 +61,4 @@ } | ||
var validationErrors = []; | ||
let validationErrors = []; // Validation function called for each affected key | ||
// Validation function called for each affected key | ||
function validate(val, affectedKey, affectedKeyGeneric, def, op, isInArrayItemObject, isInSubObject) { | ||
@@ -85,3 +69,2 @@ // Get the schema for this key, marking invalid if there isn't one. | ||
if (op === '$unset') return; | ||
validationErrors.push({ | ||
@@ -93,5 +76,5 @@ name: affectedKey, | ||
return; | ||
} | ||
} // For $rename, make sure that the new name is allowed by the schema | ||
// For $rename, make sure that the new name is allowed by the schema | ||
if (op === '$rename' && !schema.allowsKey(val)) { | ||
@@ -104,13 +87,12 @@ validationErrors.push({ | ||
return; | ||
} | ||
} // Prepare the context object for the validator functions | ||
// Prepare the context object for the validator functions | ||
var fieldParentNameWithEndDot = (0, _utility.getParentOfKey)(affectedKey, true); | ||
var fieldParentName = fieldParentNameWithEndDot.slice(0, -1); | ||
const fieldParentNameWithEndDot = (0, _utility.getParentOfKey)(affectedKey, true); | ||
const fieldParentName = fieldParentNameWithEndDot.slice(0, -1); | ||
function getFieldInfo(key) { | ||
// Create mongoObject if necessary, cache for speed | ||
if (!mongoObject) mongoObject = new _mongoObject2.default(obj, schema.blackboxKeys()); | ||
var keyInfo = mongoObject.getInfoForKey(key) || {}; | ||
if (!mongoObject) mongoObject = new _mongoObject.default(obj, schema.blackboxKeys()); | ||
const keyInfo = mongoObject.getInfoForKey(key) || {}; | ||
return { | ||
@@ -123,11 +105,10 @@ isSet: keyInfo.value !== undefined, | ||
var fieldValidationErrors = []; | ||
const fieldValidationErrors = []; | ||
var validatorContext = _extends({ | ||
addValidationErrors: function addValidationErrors(errors) { | ||
errors.forEach(function (error) { | ||
return fieldValidationErrors.push(error); | ||
}); | ||
const validatorContext = _objectSpread({ | ||
addValidationErrors(errors) { | ||
errors.forEach(error => fieldValidationErrors.push(error)); | ||
}, | ||
field: function field(fName) { | ||
field(fName) { | ||
return getFieldInfo(fName); | ||
@@ -137,17 +118,19 @@ }, | ||
genericKey: affectedKeyGeneric, | ||
isInArrayItemObject: isInArrayItemObject, | ||
isInSubObject: isInSubObject, | ||
isModifier: isModifier, | ||
isInArrayItemObject, | ||
isInSubObject, | ||
isModifier, | ||
isSet: val !== undefined, | ||
key: affectedKey, | ||
obj: obj, | ||
obj, | ||
operator: op, | ||
parentField: function parentField() { | ||
parentField() { | ||
return getFieldInfo(fieldParentName); | ||
}, | ||
siblingField: function siblingField(fName) { | ||
siblingField(fName) { | ||
return getFieldInfo(fieldParentNameWithEndDot + fName); | ||
}, | ||
validationContext: validationContext, | ||
validationContext, | ||
value: val, | ||
@@ -159,29 +142,27 @@ // Value checks are not necessary for null or undefined values, | ||
var builtInValidators = [_requiredValidator2.default, _typeValidator2.default, _allowedValuesValidator2.default]; | ||
var validators = builtInValidators.concat(schema._validators).concat(_SimpleSchema.SimpleSchema._validators); | ||
// Loop through each of the definitions in the SimpleSchemaGroup. | ||
const builtInValidators = [_requiredValidator.default, _typeValidator.default, _allowedValuesValidator.default]; | ||
const validators = builtInValidators.concat(schema._validators).concat(_SimpleSchema.SimpleSchema._validators); // Loop through each of the definitions in the SimpleSchemaGroup. | ||
// If any return true, we're valid. | ||
var fieldIsValid = def.type.some(function (typeDef) { | ||
var finalValidatorContext = _extends({}, validatorContext, { | ||
const fieldIsValid = def.type.some(typeDef => { | ||
const finalValidatorContext = _objectSpread({}, validatorContext, { | ||
// Take outer definition props like "optional" and "label" | ||
// and add them to inner props like "type" and "min" | ||
definition: _extends({}, (0, _lodash2.default)(def, 'type'), typeDef) | ||
}); | ||
definition: _objectSpread({}, (0, _lodash.default)(def, 'type'), typeDef) | ||
}); // Add custom field validators to the list after the built-in | ||
// validators but before the schema and global validators. | ||
// Add custom field validators to the list after the built-in | ||
// validators but before the schema and global validators. | ||
var fieldValidators = validators.slice(0); | ||
const fieldValidators = validators.slice(0); | ||
if (typeof typeDef.custom === 'function') { | ||
fieldValidators.splice(builtInValidators.length, 0, typeDef.custom); | ||
} | ||
// We use _.every just so that we don't continue running more validator | ||
} // We use _.every just so that we don't continue running more validator | ||
// functions after the first one returns false or an error string. | ||
return fieldValidators.every(function (validator) { | ||
var result = validator.call(finalValidatorContext); | ||
// If the validator returns a string, assume it is the | ||
return fieldValidators.every(validator => { | ||
const result = validator.call(finalValidatorContext); // If the validator returns a string, assume it is the | ||
// error type. | ||
if (typeof result === 'string') { | ||
@@ -194,8 +175,8 @@ fieldValidationErrors.push({ | ||
return false; | ||
} | ||
} // If the validator returns an object, assume it is an | ||
// error object. | ||
// If the validator returns an object, assume it is an | ||
// error object. | ||
if ((typeof result === 'undefined' ? 'undefined' : _typeof(result)) === 'object' && result !== null) { | ||
fieldValidationErrors.push(_extends({ | ||
if (typeof result === 'object' && result !== null) { | ||
fieldValidationErrors.push(_objectSpread({ | ||
name: affectedKey, | ||
@@ -205,9 +186,8 @@ value: val | ||
return false; | ||
} | ||
// If the validator returns false, assume they already | ||
} // If the validator returns false, assume they already | ||
// called this.addValidationErrors within the function | ||
if (result === false) return false; | ||
// Any other return value we assume means it was valid | ||
if (result === false) return false; // Any other return value we assume means it was valid | ||
return true; | ||
@@ -220,54 +200,47 @@ }); | ||
} | ||
} | ||
} // The recursive function | ||
// The recursive function | ||
function checkObj(_ref2) { | ||
var val = _ref2.val, | ||
affectedKey = _ref2.affectedKey, | ||
operator = _ref2.operator, | ||
_ref2$isInArrayItemOb = _ref2.isInArrayItemObject, | ||
isInArrayItemObject = _ref2$isInArrayItemOb === undefined ? false : _ref2$isInArrayItemOb, | ||
_ref2$isInSubObject = _ref2.isInSubObject, | ||
isInSubObject = _ref2$isInSubObject === undefined ? false : _ref2$isInSubObject; | ||
var affectedKeyGeneric = void 0; | ||
var def = void 0; | ||
function checkObj({ | ||
val, | ||
affectedKey, | ||
operator, | ||
isInArrayItemObject = false, | ||
isInSubObject = false | ||
}) { | ||
let affectedKeyGeneric; | ||
let def; | ||
if (affectedKey) { | ||
// When we hit a blackbox key, we don't progress any further | ||
if (schema.keyIsInBlackBox(affectedKey)) return; | ||
// Make a generic version of the affected key, and use that | ||
if (schema.keyIsInBlackBox(affectedKey)) return; // Make a generic version of the affected key, and use that | ||
// to get the schema for this key. | ||
affectedKeyGeneric = _mongoObject2.default.makeKeyGeneric(affectedKey); | ||
var shouldValidateKey = !keysToValidate || keysToValidate.some(function (keyToValidate) { | ||
return keyToValidate === affectedKey || keyToValidate === affectedKeyGeneric || affectedKey.startsWith(keyToValidate + '.') || affectedKeyGeneric.startsWith(keyToValidate + '.'); | ||
}); | ||
affectedKeyGeneric = _mongoObject.default.makeKeyGeneric(affectedKey); | ||
const shouldValidateKey = !keysToValidate || keysToValidate.some(keyToValidate => keyToValidate === affectedKey || keyToValidate === affectedKeyGeneric || affectedKey.startsWith(`${keyToValidate}.`) || affectedKeyGeneric.startsWith(`${keyToValidate}.`)); // Perform validation for this key | ||
// Perform validation for this key | ||
def = schema.getDefinition(affectedKey); | ||
if (shouldValidateKey) { | ||
validate(val, affectedKey, affectedKeyGeneric, def, operator, isInArrayItemObject, isInSubObject); | ||
} | ||
} | ||
// If affectedKeyGeneric is undefined due to this being the first run of this | ||
} // If affectedKeyGeneric is undefined due to this being the first run of this | ||
// function, objectKeys will return the top-level keys. | ||
var childKeys = schema.objectKeys(affectedKeyGeneric); | ||
// Temporarily convert missing objects to empty objects | ||
const childKeys = schema.objectKeys(affectedKeyGeneric); // Temporarily convert missing objects to empty objects | ||
// so that the looping code will be called and required | ||
// descendent keys can be validated. | ||
if ((val === undefined || val === null) && (!def || !def.optional && childKeys && childKeys.length > 0)) { | ||
val = {}; | ||
} | ||
} // Loop through arrays | ||
// Loop through arrays | ||
if (Array.isArray(val)) { | ||
val.forEach(function (v, i) { | ||
val.forEach((v, i) => { | ||
checkObj({ | ||
val: v, | ||
affectedKey: affectedKey + '.' + i, | ||
operator: operator | ||
affectedKey: `${affectedKey}.${i}`, | ||
operator | ||
}); | ||
@@ -277,22 +250,18 @@ }); | ||
// Loop through object keys | ||
// Get list of present keys | ||
var presentKeys = Object.keys(val); | ||
// Check all present keys plus all keys defined by the schema. | ||
const presentKeys = Object.keys(val); // Check all present keys plus all keys defined by the schema. | ||
// This allows us to detect extra keys not allowed by the schema plus | ||
// any missing required keys, and to run any custom functions for other keys. | ||
var keysToCheck = (0, _lodash6.default)(presentKeys, childKeys); | ||
// If this object is within an array, make sure we check for | ||
const keysToCheck = (0, _lodash3.default)(presentKeys, childKeys); // If this object is within an array, make sure we check for | ||
// required as if it's not a modifier | ||
isInArrayItemObject = affectedKeyGeneric && affectedKeyGeneric.slice(-2) === '.$'; | ||
// Check all keys in the merged list | ||
keysToCheck.forEach(function (key) { | ||
isInArrayItemObject = affectedKeyGeneric && affectedKeyGeneric.slice(-2) === '.$'; // Check all keys in the merged list | ||
keysToCheck.forEach(key => { | ||
checkObj({ | ||
val: val[key], | ||
affectedKey: (0, _utility.appendAffectedKey)(affectedKey, key), | ||
operator: operator, | ||
isInArrayItemObject: isInArrayItemObject, | ||
operator, | ||
isInArrayItemObject, | ||
isInSubObject: true | ||
@@ -306,8 +275,9 @@ }); | ||
// Loop through operators | ||
Object.keys(mod).forEach(function (op) { | ||
var opObj = mod[op]; | ||
// If non-operators are mixed in, throw error | ||
Object.keys(mod).forEach(op => { | ||
const opObj = mod[op]; // If non-operators are mixed in, throw error | ||
if (op.slice(0, 1) !== '$') { | ||
throw new Error('Expected \'' + op + '\' to be a modifier operator like \'$set\''); | ||
throw new Error(`Expected '${op}' to be a modifier operator like '$set'`); | ||
} | ||
if (shouldCheck(op)) { | ||
@@ -317,5 +287,5 @@ // For an upsert, missing props would not be set if an insert is performed, | ||
if (isUpsert && (op === '$set' || op === '$setOnInsert')) { | ||
var presentKeys = Object.keys(opObj); | ||
schema.objectKeys().forEach(function (schemaKey) { | ||
if (!(0, _lodash8.default)(presentKeys, schemaKey)) { | ||
const presentKeys = Object.keys(opObj); | ||
schema.objectKeys().forEach(schemaKey => { | ||
if (!(0, _lodash4.default)(presentKeys, schemaKey)) { | ||
checkObj({ | ||
@@ -328,14 +298,17 @@ val: undefined, | ||
}); | ||
} | ||
// Don't use forEach here because it will not properly handle an | ||
} // Don't use forEach here because it will not properly handle an | ||
// object that has a property named `length` | ||
Object.keys(opObj).forEach(function (k) { | ||
var v = opObj[k]; | ||
Object.keys(opObj).forEach(k => { | ||
let v = opObj[k]; | ||
if (op === '$push' || op === '$addToSet') { | ||
if ((typeof v === 'undefined' ? 'undefined' : _typeof(v)) === 'object' && '$each' in v) { | ||
if (typeof v === 'object' && '$each' in v) { | ||
v = v.$each; | ||
} else { | ||
k = k + '.0'; | ||
k = `${k}.0`; | ||
} | ||
} | ||
checkObj({ | ||
@@ -349,26 +322,27 @@ val: v, | ||
}); | ||
} | ||
} // Kick off the validation | ||
// Kick off the validation | ||
if (isModifier) { | ||
checkModifier(obj); | ||
} else { | ||
checkObj({ val: obj }); | ||
} | ||
checkObj({ | ||
val: obj | ||
}); | ||
} // Custom whole-doc validators | ||
// Custom whole-doc validators | ||
var docValidators = schema._docValidators.concat(_SimpleSchema.SimpleSchema._docValidators); | ||
docValidators.forEach(function (func) { | ||
var errors = func(obj); | ||
const docValidators = schema._docValidators.concat(_SimpleSchema.SimpleSchema._docValidators); | ||
docValidators.forEach(func => { | ||
const errors = func(obj); | ||
if (!Array.isArray(errors)) throw new Error('Custom doc validator must return an array of error objects'); | ||
if (errors.length) validationErrors = validationErrors.concat(errors); | ||
}); | ||
var addedFieldNames = []; | ||
validationErrors = validationErrors.filter(function (errObj) { | ||
const addedFieldNames = []; | ||
validationErrors = validationErrors.filter(errObj => { | ||
// Remove error types the user doesn't care about | ||
if ((0, _lodash8.default)(ignoreTypes, errObj.type)) return false; | ||
// Make sure there is only one error per fieldName | ||
if ((0, _lodash8.default)(addedFieldNames, errObj.name)) return false; | ||
if ((0, _lodash4.default)(ignoreTypes, errObj.type)) return false; // Make sure there is only one error per fieldName | ||
if ((0, _lodash4.default)(addedFieldNames, errObj.name)) return false; | ||
addedFieldNames.push(errObj.name); | ||
@@ -380,2 +354,5 @@ return true; | ||
exports.default = doValidation; | ||
var _default = doValidation; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,10 +6,11 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
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 _mongoObject = _interopRequireDefault(require("mongo-object")); | ||
var _mongoObject = require('mongo-object'); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var _mongoObject2 = _interopRequireDefault(_mongoObject); | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
@@ -20,35 +21,43 @@ /** | ||
function expandShorthand(schema) { | ||
var schemaClone = {}; | ||
const schemaClone = {}; | ||
Object.keys(schema).forEach(key => { | ||
const definition = schema[key]; // CASE 1: Not shorthand. Just clone | ||
Object.keys(schema).forEach(function (key) { | ||
var definition = schema[key]; | ||
// CASE 1: Not shorthand. Just clone | ||
if (_mongoObject2.default.isBasicObject(definition)) { | ||
schemaClone[key] = _extends({}, definition); | ||
if (_mongoObject.default.isBasicObject(definition)) { | ||
schemaClone[key] = _objectSpread({}, definition); | ||
return; | ||
} | ||
} // CASE 2: The definition is an array of some type | ||
// CASE 2: The definition is an array of some type | ||
if (Array.isArray(definition)) { | ||
if (Array.isArray(definition[0])) { | ||
throw new Error('Array shorthand may only be used to one level of depth (' + key + ')'); | ||
throw new Error(`Array shorthand may only be used to one level of depth (${key})`); | ||
} | ||
var type = definition[0]; | ||
schemaClone[key] = { type: Array }; | ||
// Also add the item key definition | ||
var itemKey = key + '.$'; | ||
const type = definition[0]; | ||
schemaClone[key] = { | ||
type: Array | ||
}; // Also add the item key definition | ||
const itemKey = `${key}.$`; | ||
if (schema[itemKey]) { | ||
throw new Error('Array shorthand used for ' + key + ' field but ' + key + '.$ key is already in the schema'); | ||
throw new Error(`Array shorthand used for ${key} field but ${key}.$ key is already in the schema`); | ||
} | ||
if (type instanceof RegExp) { | ||
schemaClone[itemKey] = { type: String, regEx: type }; | ||
schemaClone[itemKey] = { | ||
type: String, | ||
regEx: type | ||
}; | ||
} else { | ||
schemaClone[itemKey] = { type: type }; | ||
schemaClone[itemKey] = { | ||
type | ||
}; | ||
} | ||
return; | ||
} | ||
} // CASE 3: The definition is a regular expression | ||
// CASE 3: The definition is a regular expression | ||
if (definition instanceof RegExp) { | ||
@@ -60,11 +69,15 @@ schemaClone[key] = { | ||
return; | ||
} | ||
} // CASE 4: The definition is something, a type | ||
// CASE 4: The definition is something, a type | ||
schemaClone[key] = { type: definition }; | ||
schemaClone[key] = { | ||
type: definition | ||
}; | ||
}); | ||
return schemaClone; | ||
} | ||
exports.default = expandShorthand; | ||
var _default = expandShorthand; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,2 +6,4 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
/* | ||
@@ -12,3 +14,2 @@ Code source: | ||
*/ | ||
function capitalize(text) { | ||
@@ -20,8 +21,7 @@ text = text || ''; | ||
text = text[0].toUpperCase() + text.substr(1).toLowerCase(); | ||
} | ||
} // Do "ID" instead of "id" or "Id" | ||
// Do "ID" instead of "id" or "Id" | ||
text = text.replace(/\bid\b/g, 'ID'); | ||
text = text.replace(/\bId\b/g, 'ID'); | ||
return text; | ||
@@ -33,6 +33,6 @@ } | ||
text = text.toString(); // might be a number | ||
text = text.trim(); | ||
text = text.replace(/([a-z\d])([A-Z]+)/g, '$1_$2'); | ||
text = text.replace(/[-\s]+/g, '_').toLowerCase(); | ||
return text; | ||
@@ -42,5 +42,4 @@ } | ||
function extname(text) { | ||
var index = text.lastIndexOf('.'); | ||
var ext = text.substring(index, text.length); | ||
const index = text.lastIndexOf('.'); | ||
const ext = text.substring(index, text.length); | ||
return index === -1 ? '' : ext; | ||
@@ -52,2 +51,3 @@ } | ||
text = text.toString(); // might be a number | ||
text = text.trim(); | ||
@@ -57,6 +57,8 @@ text = text.replace(extname(text), ''); | ||
text = text.replace(/[\W_]+/g, ' '); | ||
return capitalize(text); | ||
} | ||
exports.default = humanize; | ||
var _default = humanize; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,9 +6,12 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.ValidationContext = undefined; | ||
exports.default = void 0; | ||
var _SimpleSchema = require('./SimpleSchema'); | ||
var _SimpleSchema = require("./SimpleSchema"); | ||
require('./clean.js'); | ||
require("./clean.js"); | ||
exports.default = _SimpleSchema.SimpleSchema; | ||
exports.ValidationContext = _SimpleSchema.ValidationContext; | ||
_SimpleSchema.SimpleSchema.ValidationContext = _SimpleSchema.ValidationContext; | ||
var _default = _SimpleSchema.SimpleSchema; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,2 +6,3 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
// this domain regex matches all domains that have at least one . | ||
@@ -11,16 +12,16 @@ // sadly IPv4 Adresses will be caught too but technically those are valid domains | ||
// a modification enforces that the tld consists only of characters | ||
var rxDomain = '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z](?:[a-z-]*[a-z])?'; | ||
// this domain regex matches everythign that could be a domain in intranet | ||
const rxDomain = '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z](?:[a-z-]*[a-z])?'; // this domain regex matches everythign that could be a domain in intranet | ||
// that means "localhost" is a valid domain | ||
var rxNameDomain = '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.|$))+'; | ||
// strict IPv4 expression which allows 0-255 per oktett | ||
var rxIPv4 = '(?:(?:[0-1]?\\d{1,2}|2[0-4]\\d|25[0-5])(?:\\.|$)){4}'; | ||
// strict IPv6 expression which allows (and validates) all shortcuts | ||
var rxIPv6 = '(?:(?:[\\dA-Fa-f]{1,4}(?::|$)){8}' // full adress | ||
const rxNameDomain = '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.|$))+'; // strict IPv4 expression which allows 0-255 per oktett | ||
const rxIPv4 = '(?:(?:[0-1]?\\d{1,2}|2[0-4]\\d|25[0-5])(?:\\.|$)){4}'; // strict IPv6 expression which allows (and validates) all shortcuts | ||
const rxIPv6 = '(?:(?:[\\dA-Fa-f]{1,4}(?::|$)){8}' // full adress | ||
+ '|(?=(?:[^:\\s]|:[^:\\s])*::(?:[^:\\s]|:[^:\\s])*$)' // or min/max one '::' | ||
+ '[\\dA-Fa-f]{0,4}(?:::?(?:[\\dA-Fa-f]{1,4}|$)){1,6})'; // and short adress | ||
// this allows domains (also localhost etc) and ip adresses | ||
var rxWeakDomain = '(?:' + [rxNameDomain, rxIPv4, rxIPv6].join('|') + ')'; | ||
var regEx = { | ||
const rxWeakDomain = `(?:${[rxNameDomain, rxIPv4, rxIPv6].join('|')})`; | ||
const regEx = { | ||
// We use the RegExp suggested by W3C in http://www.w3.org/TR/html5/forms.html#valid-e-mail-address | ||
@@ -30,12 +31,9 @@ // This is probably the same logic used by most browsers when type=email, which is our goal. It is | ||
Email: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/, | ||
// Like Email but requires the TLD (.com, etc) | ||
EmailWithTLD: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, | ||
Domain: new RegExp('^' + rxDomain + '$'), | ||
WeakDomain: new RegExp('^' + rxWeakDomain + '$'), | ||
IP: new RegExp('^(?:' + rxIPv4 + '|' + rxIPv6 + ')$'), | ||
IPv4: new RegExp('^' + rxIPv4 + '$'), | ||
IPv6: new RegExp('^' + rxIPv6 + '$'), | ||
Domain: new RegExp(`^${rxDomain}$`), | ||
WeakDomain: new RegExp(`^${rxWeakDomain}$`), | ||
IP: new RegExp(`^(?:${rxIPv4}|${rxIPv6})$`), | ||
IPv4: new RegExp(`^${rxIPv4}$`), | ||
IPv6: new RegExp(`^${rxIPv6}$`), | ||
// URL RegEx from https://gist.github.com/dperini/729294 | ||
@@ -56,4 +54,7 @@ // http://mathiasbynens.be/demo/url-regex | ||
Phone: /^[0-90-9٠-٩۰-۹]{2}$|^[++]*(?:[-x‐-―−ー--/ ()()[].\[\]/~⁓∼~*]*[0-90-9٠-٩۰-۹]){3,}[-x‐-―−ー--/ ()()[].\[\]/~⁓∼~0-90-9٠-٩۰-۹]*(?:;ext=([0-90-9٠-٩۰-۹]{1,7})|[ \t,]*(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|[,xx##~~]|int|anexo|int)[:\..]?[ \t,-]*([0-90-9٠-٩۰-۹]{1,7})#?|[- ]+([0-90-9٠-٩۰-۹]{1,5})#)?$/i // eslint-disable-line no-irregular-whitespace | ||
}; | ||
exports.default = regEx; | ||
var _default = regEx; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,128 +6,86 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.ValidationContext = exports.SimpleSchema = exports.schemaDefinitionOptions = undefined; | ||
Object.defineProperty(exports, "ValidationContext", { | ||
enumerable: true, | ||
get: function () { | ||
return _ValidationContext.default; | ||
} | ||
}); | ||
exports.SimpleSchema = exports.schemaDefinitionOptions = void 0; | ||
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 _clone = _interopRequireDefault(require("clone")); | ||
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 _lodash = _interopRequireDefault(require("lodash.every")); | ||
var _clone = require('clone'); | ||
var _extend = _interopRequireDefault(require("extend")); | ||
var _clone2 = _interopRequireDefault(_clone); | ||
var _lodash2 = _interopRequireDefault(require("lodash.includes")); | ||
var _lodash = require('lodash.every'); | ||
var _lodash3 = _interopRequireDefault(require("lodash.isempty")); | ||
var _lodash2 = _interopRequireDefault(_lodash); | ||
var _messageBox = _interopRequireDefault(require("message-box")); | ||
var _extend2 = require('extend'); | ||
var _mongoObject = _interopRequireDefault(require("mongo-object")); | ||
var _extend3 = _interopRequireDefault(_extend2); | ||
var _lodash4 = _interopRequireDefault(require("lodash.omit")); | ||
var _lodash3 = require('lodash.includes'); | ||
var _lodash5 = _interopRequireDefault(require("lodash.pick")); | ||
var _lodash4 = _interopRequireDefault(_lodash3); | ||
var _lodash6 = _interopRequireDefault(require("lodash.uniq")); | ||
var _lodash5 = require('lodash.isempty'); | ||
var _humanize = _interopRequireDefault(require("./humanize.js")); | ||
var _lodash6 = _interopRequireDefault(_lodash5); | ||
var _ValidationContext = _interopRequireDefault(require("./ValidationContext")); | ||
var _messageBox = require('message-box'); | ||
var _SimpleSchemaGroup = _interopRequireDefault(require("./SimpleSchemaGroup")); | ||
var _messageBox2 = _interopRequireDefault(_messageBox); | ||
var _regExp = _interopRequireDefault(require("./regExp")); | ||
var _mongoObject = require('mongo-object'); | ||
var _clean = _interopRequireDefault(require("./clean")); | ||
var _mongoObject2 = _interopRequireDefault(_mongoObject); | ||
var _expandShorthand = _interopRequireDefault(require("./expandShorthand")); | ||
var _lodash7 = require('lodash.omit'); | ||
var _utility = require("./utility"); | ||
var _lodash8 = _interopRequireDefault(_lodash7); | ||
var _defaultMessages = _interopRequireDefault(require("./defaultMessages")); | ||
var _lodash9 = require('lodash.pick'); | ||
var _lodash10 = _interopRequireDefault(_lodash9); | ||
var _lodash11 = require('lodash.uniq'); | ||
var _lodash12 = _interopRequireDefault(_lodash11); | ||
var _humanize = require('./humanize.js'); | ||
var _humanize2 = _interopRequireDefault(_humanize); | ||
var _ValidationContext = require('./ValidationContext'); | ||
var _ValidationContext2 = _interopRequireDefault(_ValidationContext); | ||
var _SimpleSchemaGroup = require('./SimpleSchemaGroup'); | ||
var _SimpleSchemaGroup2 = _interopRequireDefault(_SimpleSchemaGroup); | ||
var _regExp = require('./regExp'); | ||
var _regExp2 = _interopRequireDefault(_regExp); | ||
var _clean2 = require('./clean'); | ||
var _clean3 = _interopRequireDefault(_clean2); | ||
var _expandShorthand = require('./expandShorthand'); | ||
var _expandShorthand2 = _interopRequireDefault(_expandShorthand); | ||
var _utility = require('./utility'); | ||
var _defaultMessages = require('./defaultMessages'); | ||
var _defaultMessages2 = _interopRequireDefault(_defaultMessages); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
// Exported for tests | ||
var schemaDefinitionOptions = exports.schemaDefinitionOptions = ['type', 'label', 'optional', 'required', 'autoValue', 'defaultValue']; | ||
const schemaDefinitionOptions = ['type', 'label', 'optional', 'required', 'autoValue', 'defaultValue']; | ||
exports.schemaDefinitionOptions = schemaDefinitionOptions; | ||
const oneOfProps = ['type', 'min', 'max', 'minCount', 'maxCount', 'allowedValues', 'exclusiveMin', 'exclusiveMax', 'regEx', 'custom', 'blackbox', 'trim']; | ||
const propsThatCanBeFunction = ['label', 'optional', 'min', 'max', 'minCount', 'maxCount', 'allowedValues', 'exclusiveMin', 'exclusiveMax', 'regEx']; | ||
var oneOfProps = ['type', 'min', 'max', 'minCount', 'maxCount', 'allowedValues', 'exclusiveMin', 'exclusiveMax', 'regEx', 'custom', 'blackbox', 'trim']; | ||
class SimpleSchema { | ||
constructor(schema = {}, { | ||
check, | ||
clean: cleanOptions, | ||
defaultLabel, | ||
humanizeAutoLabels = true, | ||
requiredByDefault = true, | ||
tracker | ||
} = {}) { | ||
_defineProperty(this, "pick", getPickOrOmit('pick')); | ||
var propsThatCanBeFunction = ['label', 'optional', 'min', 'max', 'minCount', 'maxCount', 'allowedValues', 'exclusiveMin', 'exclusiveMax', 'regEx']; | ||
_defineProperty(this, "omit", getPickOrOmit('omit')); | ||
var SimpleSchema = function () { | ||
function SimpleSchema() { | ||
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, | ||
check = _ref.check, | ||
cleanOptions = _ref.clean, | ||
defaultLabel = _ref.defaultLabel, | ||
_ref$humanizeAutoLabe = _ref.humanizeAutoLabels, | ||
humanizeAutoLabels = _ref$humanizeAutoLabe === undefined ? true : _ref$humanizeAutoLabe, | ||
_ref$requiredByDefaul = _ref.requiredByDefault, | ||
requiredByDefault = _ref$requiredByDefaul === undefined ? true : _ref$requiredByDefaul, | ||
tracker = _ref.tracker; | ||
_classCallCheck(this, SimpleSchema); | ||
this.pick = getPickOrOmit('pick'); | ||
this.omit = getPickOrOmit('omit'); | ||
// Stash the options object | ||
this._constructorOptions = { | ||
check: check, | ||
defaultLabel: defaultLabel, | ||
humanizeAutoLabels: humanizeAutoLabels, | ||
requiredByDefault: requiredByDefault, | ||
tracker: tracker | ||
}; | ||
check, | ||
defaultLabel, | ||
humanizeAutoLabels, | ||
requiredByDefault, | ||
tracker | ||
}; // Custom validators for this instance | ||
// Custom validators for this instance | ||
this._validators = []; | ||
this._docValidators = []; | ||
this._docValidators = []; // Named validation contexts | ||
// Named validation contexts | ||
this._validationContexts = {}; | ||
this._validationContexts = {}; // Schema-level defaults for cleaning | ||
// Schema-level defaults for cleaning | ||
this._cleanOptions = _extends({ | ||
this._cleanOptions = _objectSpread({ | ||
filter: true, | ||
@@ -140,876 +98,739 @@ autoConvert: true, | ||
extendAutoValueContext: {} | ||
}, cleanOptions); | ||
}, cleanOptions); // Clone, expanding shorthand, and store the schema object in this._schema | ||
// Clone, expanding shorthand, and store the schema object in this._schema | ||
this._schema = {}; | ||
this._depsLabels = {}; | ||
this.extend(schema); | ||
this.extend(schema); // Define default validation error messages | ||
// Define default validation error messages | ||
this.messageBox = new _messageBox2.default((0, _clone2.default)(_defaultMessages2.default)); | ||
this.messageBox = new _messageBox.default((0, _clone.default)(_defaultMessages.default)); | ||
this.version = SimpleSchema.version; | ||
} | ||
_createClass(SimpleSchema, [{ | ||
key: 'forEachAncestorSimpleSchema', | ||
value: function forEachAncestorSimpleSchema(key, func) { | ||
var _this = this; | ||
forEachAncestorSimpleSchema(key, func) { | ||
const genericKey = _mongoObject.default.makeKeyGeneric(key); | ||
var genericKey = _mongoObject2.default.makeKeyGeneric(key); | ||
(0, _utility.forEachKeyAncestor)(genericKey, function (ancestor) { | ||
var def = _this._schema[ancestor]; | ||
if (!def) return; | ||
def.type.definitions.forEach(function (typeDef) { | ||
if (SimpleSchema.isSimpleSchema(typeDef.type)) { | ||
func(typeDef.type, ancestor, genericKey.slice(ancestor.length + 1)); | ||
} | ||
}); | ||
(0, _utility.forEachKeyAncestor)(genericKey, ancestor => { | ||
const def = this._schema[ancestor]; | ||
if (!def) return; | ||
def.type.definitions.forEach(typeDef => { | ||
if (SimpleSchema.isSimpleSchema(typeDef.type)) { | ||
func(typeDef.type, ancestor, genericKey.slice(ancestor.length + 1)); | ||
} | ||
}); | ||
} | ||
}); | ||
} | ||
/** | ||
* Returns whether the obj is a SimpleSchema object. | ||
* @param {Object} [obj] An object to test | ||
* @returns {Boolean} True if the given object appears to be a SimpleSchema instance | ||
*/ | ||
/** | ||
* Returns whether the obj is a SimpleSchema object. | ||
* @param {Object} [obj] An object to test | ||
* @returns {Boolean} True if the given object appears to be a SimpleSchema instance | ||
*/ | ||
}, { | ||
key: 'reactiveLabelDependency', | ||
static isSimpleSchema(obj) { | ||
return obj && (obj instanceof SimpleSchema || obj._schema); | ||
} | ||
/** | ||
* For Meteor apps, add a reactive dependency on the label | ||
* for a key. | ||
*/ | ||
/** | ||
* For Meteor apps, add a reactive dependency on the label | ||
* for a key. | ||
*/ | ||
value: function reactiveLabelDependency(key) { | ||
var tracker = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._constructorOptions.tracker; | ||
reactiveLabelDependency(key, tracker = this._constructorOptions.tracker) { | ||
if (!key || !tracker) return; | ||
if (!key || !tracker) return; | ||
const genericKey = _mongoObject.default.makeKeyGeneric(key); // If in this schema | ||
var genericKey = _mongoObject2.default.makeKeyGeneric(key); | ||
// If in this schema | ||
if (this._schema[genericKey]) { | ||
if (!this._depsLabels[genericKey]) { | ||
this._depsLabels[genericKey] = new tracker.Dependency(); | ||
} | ||
this._depsLabels[genericKey].depend(); | ||
return; | ||
if (this._schema[genericKey]) { | ||
if (!this._depsLabels[genericKey]) { | ||
this._depsLabels[genericKey] = new tracker.Dependency(); | ||
} | ||
// If in subschema | ||
this.forEachAncestorSimpleSchema(key, function (simpleSchema, ancestor, subSchemaKey) { | ||
// Pass tracker down so that we get reactivity even if the subschema | ||
// didn't have tracker option set | ||
simpleSchema.reactiveLabelDependency(subSchemaKey, tracker); | ||
}); | ||
} | ||
this._depsLabels[genericKey].depend(); | ||
/** | ||
* @param {String} [key] One specific or generic key for which to get the schema. | ||
* @returns {Object} The entire schema object or just the definition for one key. | ||
* | ||
* Note that this returns the raw, unevaluated definition object. Use `getDefinition` | ||
* if you want the evaluated definition, where any properties that are functions | ||
* have been run to produce a result. | ||
*/ | ||
return; | ||
} // If in subschema | ||
}, { | ||
key: 'schema', | ||
value: function schema(key) { | ||
if (!key) return this._schema; | ||
var genericKey = _mongoObject2.default.makeKeyGeneric(key); | ||
var keySchema = this._schema[genericKey]; | ||
this.forEachAncestorSimpleSchema(key, (simpleSchema, ancestor, subSchemaKey) => { | ||
// Pass tracker down so that we get reactivity even if the subschema | ||
// didn't have tracker option set | ||
simpleSchema.reactiveLabelDependency(subSchemaKey, tracker); | ||
}); | ||
} | ||
/** | ||
* @param {String} [key] One specific or generic key for which to get the schema. | ||
* @returns {Object} The entire schema object or just the definition for one key. | ||
* | ||
* Note that this returns the raw, unevaluated definition object. Use `getDefinition` | ||
* if you want the evaluated definition, where any properties that are functions | ||
* have been run to produce a result. | ||
*/ | ||
// If not defined in this schema, see if it's defined in a subschema | ||
if (!keySchema) { | ||
var found = false; | ||
this.forEachAncestorSimpleSchema(key, function (simpleSchema, ancestor, subSchemaKey) { | ||
if (!found) keySchema = simpleSchema.schema(subSchemaKey); | ||
if (keySchema) found = true; | ||
}); | ||
} | ||
return keySchema; | ||
schema(key) { | ||
if (!key) return this._schema; | ||
const genericKey = _mongoObject.default.makeKeyGeneric(key); | ||
let keySchema = this._schema[genericKey]; // If not defined in this schema, see if it's defined in a subschema | ||
if (!keySchema) { | ||
let found = false; | ||
this.forEachAncestorSimpleSchema(key, (simpleSchema, ancestor, subSchemaKey) => { | ||
if (!found) keySchema = simpleSchema.schema(subSchemaKey); | ||
if (keySchema) found = true; | ||
}); | ||
} | ||
/** | ||
* @returns {Object} The entire schema object with subschemas merged. This is the | ||
* equivalent of what schema() returned in SimpleSchema < 2.0 | ||
* | ||
* Note that this returns the raw, unevaluated definition object. Use `getDefinition` | ||
* if you want the evaluated definition, where any properties that are functions | ||
* have been run to produce a result. | ||
*/ | ||
return keySchema; | ||
} | ||
/** | ||
* @returns {Object} The entire schema object with subschemas merged. This is the | ||
* equivalent of what schema() returned in SimpleSchema < 2.0 | ||
* | ||
* Note that this returns the raw, unevaluated definition object. Use `getDefinition` | ||
* if you want the evaluated definition, where any properties that are functions | ||
* have been run to produce a result. | ||
*/ | ||
}, { | ||
key: 'mergedSchema', | ||
value: function mergedSchema() { | ||
var _this2 = this; | ||
var mergedSchema = {}; | ||
mergedSchema() { | ||
const mergedSchema = {}; | ||
this._schemaKeys.forEach(function (key) { | ||
var keySchema = _this2._schema[key]; | ||
mergedSchema[key] = keySchema; | ||
keySchema.type.definitions.forEach(function (typeDef) { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
var childSchema = typeDef.type.mergedSchema(); | ||
Object.keys(childSchema).forEach(function (subKey) { | ||
mergedSchema[key + '.' + subKey] = childSchema[subKey]; | ||
}); | ||
this._schemaKeys.forEach(key => { | ||
const keySchema = this._schema[key]; | ||
mergedSchema[key] = keySchema; | ||
keySchema.type.definitions.forEach(typeDef => { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
const childSchema = typeDef.type.mergedSchema(); | ||
Object.keys(childSchema).forEach(subKey => { | ||
mergedSchema[`${key}.${subKey}`] = childSchema[subKey]; | ||
}); | ||
}); | ||
}); | ||
return mergedSchema; | ||
} | ||
return mergedSchema; | ||
} | ||
/** | ||
* Returns the evaluated definition for one key in the schema | ||
* | ||
* @param {String} key Generic or specific schema key | ||
* @param {Array(String)} [propList] Array of schema properties you need; performance optimization | ||
* @param {Object} [functionContext] The context to use when evaluating schema options that are functions | ||
* @returns {Object} The schema definition for the requested key | ||
*/ | ||
/** | ||
* Returns the evaluated definition for one key in the schema | ||
* | ||
* @param {String} key Generic or specific schema key | ||
* @param {Array(String)} [propList] Array of schema properties you need; performance optimization | ||
* @param {Object} [functionContext] The context to use when evaluating schema options that are functions | ||
* @returns {Object} The schema definition for the requested key | ||
*/ | ||
}, { | ||
key: 'getDefinition', | ||
value: function getDefinition(key, propList) { | ||
var _this3 = this; | ||
getDefinition(key, propList, functionContext = {}) { | ||
const defs = this.schema(key); | ||
if (!defs) return; | ||
var functionContext = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
const getPropIterator = (obj, newObj) => { | ||
return prop => { | ||
if (Array.isArray(propList) && !(0, _lodash2.default)(propList, prop)) return; | ||
const val = obj[prop]; // For any options that support specifying a function, evaluate the functions | ||
var defs = this.schema(key); | ||
if (!defs) return; | ||
if (propsThatCanBeFunction.indexOf(prop) > -1 && typeof val === 'function') { | ||
newObj[prop] = val.call(_objectSpread({ | ||
key | ||
}, functionContext)); // Inflect label if undefined | ||
var getPropIterator = function getPropIterator(obj, newObj) { | ||
return function (prop) { | ||
if (Array.isArray(propList) && !(0, _lodash4.default)(propList, prop)) return; | ||
var val = obj[prop]; | ||
// For any options that support specifying a function, evaluate the functions | ||
if (propsThatCanBeFunction.indexOf(prop) > -1 && typeof val === 'function') { | ||
newObj[prop] = val.call(_extends({ | ||
key: key | ||
}, functionContext)); | ||
// Inflect label if undefined | ||
if (prop === 'label' && typeof newObj[prop] !== 'string') newObj[prop] = inflectedLabel(key, _this3._constructorOptions.humanizeAutoLabels); | ||
} else { | ||
newObj[prop] = val; | ||
} | ||
}; | ||
if (prop === 'label' && typeof newObj[prop] !== 'string') newObj[prop] = inflectedLabel(key, this._constructorOptions.humanizeAutoLabels); | ||
} else { | ||
newObj[prop] = val; | ||
} | ||
}; | ||
}; | ||
var result = {}; | ||
Object.keys(defs).forEach(getPropIterator(defs, result)); | ||
const result = {}; | ||
Object.keys(defs).forEach(getPropIterator(defs, result)); // Resolve all the types and convert to a normal array to make it easier | ||
// to use. | ||
// Resolve all the types and convert to a normal array to make it easier | ||
// to use. | ||
if (defs.type) { | ||
result.type = defs.type.definitions.map(function (typeDef) { | ||
var newTypeDef = {}; | ||
Object.keys(typeDef).forEach(getPropIterator(typeDef, newTypeDef)); | ||
return newTypeDef; | ||
}); | ||
} | ||
return result; | ||
if (defs.type) { | ||
result.type = defs.type.definitions.map(typeDef => { | ||
const newTypeDef = {}; | ||
Object.keys(typeDef).forEach(getPropIterator(typeDef, newTypeDef)); | ||
return newTypeDef; | ||
}); | ||
} | ||
/** | ||
* Returns a string identifying the best guess data type for a key. For keys | ||
* that allow multiple types, the first type is used. This can be useful for | ||
* building forms. | ||
* | ||
* @param {String} key Generic or specific schema key | ||
* @returns {String} A type string. One of: | ||
* string, number, boolean, date, object, stringArray, numberArray, booleanArray, | ||
* dateArray, objectArray | ||
*/ | ||
return result; | ||
} | ||
/** | ||
* Returns a string identifying the best guess data type for a key. For keys | ||
* that allow multiple types, the first type is used. This can be useful for | ||
* building forms. | ||
* | ||
* @param {String} key Generic or specific schema key | ||
* @returns {String} A type string. One of: | ||
* string, number, boolean, date, object, stringArray, numberArray, booleanArray, | ||
* dateArray, objectArray | ||
*/ | ||
}, { | ||
key: 'getQuickTypeForKey', | ||
value: function getQuickTypeForKey(key) { | ||
var type = void 0; | ||
var fieldSchema = this.schema(key); | ||
if (!fieldSchema) return; | ||
getQuickTypeForKey(key) { | ||
let type; | ||
const fieldSchema = this.schema(key); | ||
if (!fieldSchema) return; | ||
const fieldType = fieldSchema.type.singleType; | ||
var fieldType = fieldSchema.type.singleType; | ||
if (fieldType === String) { | ||
type = 'string'; | ||
} else if (fieldType === Number || fieldType === SimpleSchema.Integer) { | ||
type = 'number'; | ||
} else if (fieldType === Boolean) { | ||
type = 'boolean'; | ||
} else if (fieldType === Date) { | ||
type = 'date'; | ||
} else if (fieldType === Array) { | ||
const arrayItemFieldSchema = this.schema(`${key}.$`); | ||
if (!arrayItemFieldSchema) return; | ||
const arrayItemFieldType = arrayItemFieldSchema.type.singleType; | ||
if (fieldType === String) { | ||
type = 'string'; | ||
} else if (fieldType === Number || fieldType === SimpleSchema.Integer) { | ||
type = 'number'; | ||
} else if (fieldType === Boolean) { | ||
type = 'boolean'; | ||
} else if (fieldType === Date) { | ||
type = 'date'; | ||
} else if (fieldType === Array) { | ||
var arrayItemFieldSchema = this.schema(key + '.$'); | ||
if (!arrayItemFieldSchema) return; | ||
var arrayItemFieldType = arrayItemFieldSchema.type.singleType; | ||
if (arrayItemFieldType === String) { | ||
type = 'stringArray'; | ||
} else if (arrayItemFieldType === Number || arrayItemFieldType === SimpleSchema.Integer) { | ||
type = 'numberArray'; | ||
} else if (arrayItemFieldType === Boolean) { | ||
type = 'booleanArray'; | ||
} else if (arrayItemFieldType === Date) { | ||
type = 'dateArray'; | ||
} else if (arrayItemFieldType === Object || SimpleSchema.isSimpleSchema(arrayItemFieldType)) { | ||
type = 'objectArray'; | ||
} | ||
} else if (fieldType === Object) { | ||
type = 'object'; | ||
if (arrayItemFieldType === String) { | ||
type = 'stringArray'; | ||
} else if (arrayItemFieldType === Number || arrayItemFieldType === SimpleSchema.Integer) { | ||
type = 'numberArray'; | ||
} else if (arrayItemFieldType === Boolean) { | ||
type = 'booleanArray'; | ||
} else if (arrayItemFieldType === Date) { | ||
type = 'dateArray'; | ||
} else if (arrayItemFieldType === Object || SimpleSchema.isSimpleSchema(arrayItemFieldType)) { | ||
type = 'objectArray'; | ||
} | ||
return type; | ||
} else if (fieldType === Object) { | ||
type = 'object'; | ||
} | ||
/** | ||
* Given a key that is an Object, returns a new SimpleSchema instance scoped to that object. | ||
* | ||
* @param {String} key Generic or specific schema key | ||
*/ | ||
return type; | ||
} | ||
/** | ||
* Given a key that is an Object, returns a new SimpleSchema instance scoped to that object. | ||
* | ||
* @param {String} key Generic or specific schema key | ||
*/ | ||
}, { | ||
key: 'getObjectSchema', | ||
value: function getObjectSchema(key) { | ||
var newSchemaDef = {}; | ||
var genericKey = _mongoObject2.default.makeKeyGeneric(key); | ||
var searchString = genericKey + '.'; | ||
var mergedSchema = this.mergedSchema(); | ||
Object.keys(mergedSchema).forEach(function (k) { | ||
if (k.indexOf(searchString) === 0) { | ||
newSchemaDef[k.slice(searchString.length)] = mergedSchema[k]; | ||
} | ||
}); | ||
getObjectSchema(key) { | ||
const newSchemaDef = {}; | ||
return this._copyWithSchema(newSchemaDef); | ||
} | ||
const genericKey = _mongoObject.default.makeKeyGeneric(key); | ||
// Returns an array of all the autovalue functions, including those in subschemas all the | ||
// way down the schema tree | ||
const searchString = `${genericKey}.`; | ||
const mergedSchema = this.mergedSchema(); | ||
Object.keys(mergedSchema).forEach(k => { | ||
if (k.indexOf(searchString) === 0) { | ||
newSchemaDef[k.slice(searchString.length)] = mergedSchema[k]; | ||
} | ||
}); | ||
return this._copyWithSchema(newSchemaDef); | ||
} // Returns an array of all the autovalue functions, including those in subschemas all the | ||
// way down the schema tree | ||
}, { | ||
key: 'autoValueFunctions', | ||
value: function autoValueFunctions() { | ||
var _this4 = this; | ||
var result = [].concat(this._autoValues); | ||
autoValueFunctions() { | ||
let result = [].concat(this._autoValues); | ||
this._schemaKeys.forEach(function (key) { | ||
_this4._schema[key].type.definitions.forEach(function (typeDef) { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
result = result.concat(typeDef.type.autoValueFunctions().map(function (_ref2) { | ||
var func = _ref2.func, | ||
fieldName = _ref2.fieldName, | ||
closestSubschemaFieldName = _ref2.closestSubschemaFieldName; | ||
return { | ||
func: func, | ||
fieldName: key + '.' + fieldName, | ||
closestSubschemaFieldName: closestSubschemaFieldName.length ? key + '.' + closestSubschemaFieldName : key | ||
}; | ||
})); | ||
}); | ||
this._schemaKeys.forEach(key => { | ||
this._schema[key].type.definitions.forEach(typeDef => { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
result = result.concat(typeDef.type.autoValueFunctions().map(({ | ||
func, | ||
fieldName, | ||
closestSubschemaFieldName | ||
}) => { | ||
return { | ||
func, | ||
fieldName: `${key}.${fieldName}`, | ||
closestSubschemaFieldName: closestSubschemaFieldName.length ? `${key}.${closestSubschemaFieldName}` : key | ||
}; | ||
})); | ||
}); | ||
}); | ||
return result; | ||
} | ||
return result; | ||
} // Returns an array of all the blackbox keys, including those in subschemas | ||
// Returns an array of all the blackbox keys, including those in subschemas | ||
}, { | ||
key: 'blackboxKeys', | ||
value: function blackboxKeys() { | ||
var _this5 = this; | ||
blackboxKeys() { | ||
const blackboxKeys = this._blackboxKeys; | ||
var blackboxKeys = this._blackboxKeys; | ||
this._schemaKeys.forEach(function (key) { | ||
_this5._schema[key].type.definitions.forEach(function (typeDef) { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
typeDef.type._blackboxKeys.forEach(function (blackboxKey) { | ||
blackboxKeys.push(key + '.' + blackboxKey); | ||
}); | ||
this._schemaKeys.forEach(key => { | ||
this._schema[key].type.definitions.forEach(typeDef => { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
typeDef.type._blackboxKeys.forEach(blackboxKey => { | ||
blackboxKeys.push(`${key}.${blackboxKey}`); | ||
}); | ||
}); | ||
return (0, _lodash12.default)(blackboxKeys); | ||
} | ||
}); | ||
// Check if the key is a nested dot-syntax key inside of a blackbox object | ||
return (0, _lodash6.default)(blackboxKeys); | ||
} // Check if the key is a nested dot-syntax key inside of a blackbox object | ||
}, { | ||
key: 'keyIsInBlackBox', | ||
value: function keyIsInBlackBox(key) { | ||
var _this6 = this; | ||
var isInBlackBox = false; | ||
(0, _utility.forEachKeyAncestor)(_mongoObject2.default.makeKeyGeneric(key), function (ancestor, remainder) { | ||
if (_this6._blackboxKeys.indexOf(ancestor) > -1) { | ||
isInBlackBox = true; | ||
} else { | ||
var testKeySchema = _this6.schema(ancestor); | ||
if (testKeySchema) { | ||
testKeySchema.type.definitions.forEach(function (typeDef) { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
if (typeDef.type.keyIsInBlackBox(remainder)) isInBlackBox = true; | ||
}); | ||
} | ||
keyIsInBlackBox(key) { | ||
let isInBlackBox = false; | ||
(0, _utility.forEachKeyAncestor)(_mongoObject.default.makeKeyGeneric(key), (ancestor, remainder) => { | ||
if (this._blackboxKeys.indexOf(ancestor) > -1) { | ||
isInBlackBox = true; | ||
} else { | ||
const testKeySchema = this.schema(ancestor); | ||
if (testKeySchema) { | ||
testKeySchema.type.definitions.forEach(typeDef => { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
if (typeDef.type.keyIsInBlackBox(remainder)) isInBlackBox = true; | ||
}); | ||
} | ||
}); | ||
return isInBlackBox; | ||
} | ||
} | ||
}); | ||
return isInBlackBox; | ||
} // Returns true if key is explicitly allowed by the schema or implied | ||
// by other explicitly allowed keys. | ||
// The key string should have $ in place of any numeric array positions. | ||
// Returns true if key is explicitly allowed by the schema or implied | ||
// by other explicitly allowed keys. | ||
// The key string should have $ in place of any numeric array positions. | ||
}, { | ||
key: 'allowsKey', | ||
value: function allowsKey(key) { | ||
var _this7 = this; | ||
allowsKey(key) { | ||
// Loop through all keys in the schema | ||
return this._schemaKeys.some(loopKey => { | ||
// If the schema key is the test key, it's allowed. | ||
if (loopKey === key) return true; | ||
const fieldSchema = this.schema(loopKey); | ||
const compare1 = key.slice(0, loopKey.length + 2); | ||
const compare2 = compare1.slice(0, -1); // Blackbox and subschema checks are needed only if key starts with | ||
// loopKey + a dot | ||
// Loop through all keys in the schema | ||
return this._schemaKeys.some(function (loopKey) { | ||
// If the schema key is the test key, it's allowed. | ||
if (loopKey === key) return true; | ||
if (compare2 !== `${loopKey}.`) return false; // Black box handling | ||
var fieldSchema = _this7.schema(loopKey); | ||
var compare1 = key.slice(0, loopKey.length + 2); | ||
var compare2 = compare1.slice(0, -1); | ||
if (this._blackboxKeys.indexOf(loopKey) > -1) { | ||
// If the test key is the black box key + ".$", then the test | ||
// key is NOT allowed because black box keys are by definition | ||
// only for objects, and not for arrays. | ||
return compare1 !== `${loopKey}.$`; | ||
} // Subschemas | ||
// Blackbox and subschema checks are needed only if key starts with | ||
// loopKey + a dot | ||
if (compare2 !== loopKey + '.') return false; | ||
// Black box handling | ||
if (_this7._blackboxKeys.indexOf(loopKey) > -1) { | ||
// If the test key is the black box key + ".$", then the test | ||
// key is NOT allowed because black box keys are by definition | ||
// only for objects, and not for arrays. | ||
return compare1 !== loopKey + '.$'; | ||
} | ||
// Subschemas | ||
var allowed = false; | ||
var subKey = key.slice(loopKey.length + 1); | ||
fieldSchema.type.definitions.forEach(function (typeDef) { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
if (typeDef.type.allowsKey(subKey)) allowed = true; | ||
}); | ||
return allowed; | ||
let allowed = false; | ||
const subKey = key.slice(loopKey.length + 1); | ||
fieldSchema.type.definitions.forEach(typeDef => { | ||
if (!SimpleSchema.isSimpleSchema(typeDef.type)) return; | ||
if (typeDef.type.allowsKey(subKey)) allowed = true; | ||
}); | ||
} | ||
return allowed; | ||
}); | ||
} | ||
/** | ||
* Returns all the child keys for the object identified by the generic prefix, | ||
* or all the top level keys if no prefix is supplied. | ||
* | ||
* @param {String} [keyPrefix] The Object-type generic key for which to get child keys. Omit for | ||
* top-level Object-type keys | ||
* @returns {[[Type]]} [[Description]] | ||
*/ | ||
/** | ||
* Returns all the child keys for the object identified by the generic prefix, | ||
* or all the top level keys if no prefix is supplied. | ||
* | ||
* @param {String} [keyPrefix] The Object-type generic key for which to get child keys. Omit for | ||
* top-level Object-type keys | ||
* @returns {[[Type]]} [[Description]] | ||
*/ | ||
}, { | ||
key: 'objectKeys', | ||
value: function objectKeys(keyPrefix) { | ||
if (!keyPrefix) return this._firstLevelSchemaKeys; | ||
return this._objectKeys[keyPrefix + '.'] || []; | ||
} | ||
objectKeys(keyPrefix) { | ||
if (!keyPrefix) return this._firstLevelSchemaKeys; | ||
return this._objectKeys[`${keyPrefix}.`] || []; | ||
} | ||
/** | ||
* Copies this schema into a new instance with the same validators, messages, | ||
* and options, but with different keys as defined in `schema` argument | ||
* | ||
* @param {Object} schema | ||
* @returns The new SimpleSchema instance (chainable) | ||
*/ | ||
/** | ||
* Copies this schema into a new instance with the same validators, messages, | ||
* and options, but with different keys as defined in `schema` argument | ||
* | ||
* @param {Object} schema | ||
* @returns The new SimpleSchema instance (chainable) | ||
*/ | ||
}, { | ||
key: '_copyWithSchema', | ||
value: function _copyWithSchema(schema) { | ||
var cl = new SimpleSchema(schema, (0, _clone2.default)(this._constructorOptions, false, 1)); | ||
cl._cleanOptions = this._cleanOptions; | ||
cl.messageBox = this.messageBox.clone(); | ||
return cl; | ||
} | ||
_copyWithSchema(schema) { | ||
const cl = new SimpleSchema(schema, (0, _clone.default)(this._constructorOptions, false, 1)); | ||
cl._cleanOptions = this._cleanOptions; | ||
cl.messageBox = this.messageBox.clone(); | ||
return cl; | ||
} | ||
/** | ||
* Clones this schema into a new instance with the same schema keys, validators, | ||
* and options. | ||
* | ||
* @returns The new SimpleSchema instance (chainable) | ||
*/ | ||
/** | ||
* Clones this schema into a new instance with the same schema keys, validators, | ||
* and options. | ||
* | ||
* @returns The new SimpleSchema instance (chainable) | ||
*/ | ||
}, { | ||
key: 'clone', | ||
value: function clone() { | ||
return this._copyWithSchema(this._schema); | ||
} | ||
clone() { | ||
return this._copyWithSchema(this._schema); | ||
} | ||
/** | ||
* Extends (mutates) this schema with another schema, key by key. | ||
* | ||
* @param {SimpleSchema|Object} schema | ||
* @returns The SimpleSchema instance (chainable) | ||
*/ | ||
/** | ||
* Extends (mutates) this schema with another schema, key by key. | ||
* | ||
* @param {SimpleSchema|Object} schema | ||
* @returns The SimpleSchema instance (chainable) | ||
*/ | ||
}, { | ||
key: 'extend', | ||
value: function extend() { | ||
var _this8 = this; | ||
extend(schema = {}) { | ||
if (Array.isArray(schema)) throw new Error('You may not pass an array of schemas to the SimpleSchema constructor or to extend()'); | ||
let schemaObj; | ||
var schema = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
if (SimpleSchema.isSimpleSchema(schema)) { | ||
schemaObj = schema._schema; | ||
this._validators = this._validators.concat(schema._validators); | ||
this._docValidators = this._docValidators.concat(schema._docValidators); | ||
this._cleanOptions = (0, _extend.default)(false, this._cleanOptions, schema._cleanOptions); | ||
this._constructorOptions = (0, _extend.default)(false, this._constructorOptions, schema._constructorOptions); | ||
} else { | ||
schemaObj = (0, _expandShorthand.default)(schema); | ||
} // Update all of the information cached on the instance | ||
if (Array.isArray(schema)) throw new Error('You may not pass an array of schemas to the SimpleSchema constructor or to extend()'); | ||
var schemaObj = void 0; | ||
if (SimpleSchema.isSimpleSchema(schema)) { | ||
schemaObj = schema._schema; | ||
this._validators = this._validators.concat(schema._validators); | ||
this._docValidators = this._docValidators.concat(schema._docValidators); | ||
this._cleanOptions = (0, _extend3.default)(false, this._cleanOptions, schema._cleanOptions); | ||
this._constructorOptions = (0, _extend3.default)(false, this._constructorOptions, schema._constructorOptions); | ||
} else { | ||
schemaObj = (0, _expandShorthand2.default)(schema); | ||
} | ||
Object.keys(schemaObj).forEach(fieldName => { | ||
const definition = standardizeDefinition(schemaObj[fieldName]); // Merge/extend with any existing definition | ||
// Update all of the information cached on the instance | ||
Object.keys(schemaObj).forEach(function (fieldName) { | ||
var definition = standardizeDefinition(schemaObj[fieldName]); | ||
// Merge/extend with any existing definition | ||
if (_this8._schema[fieldName]) { | ||
if (!_this8._schema.hasOwnProperty(fieldName)) { | ||
// fieldName is actually a method from Object itself! | ||
throw new Error(fieldName + ' key is actually the name of a method on Object, please rename it'); | ||
} | ||
_this8._schema[fieldName] = _extends({}, _this8._schema[fieldName], (0, _lodash8.default)(definition, 'type')); | ||
if (definition.type) _this8._schema[fieldName].type.extend(definition.type); | ||
} else { | ||
_this8._schema[fieldName] = definition; | ||
if (this._schema[fieldName]) { | ||
if (!this._schema.hasOwnProperty(fieldName)) { | ||
// fieldName is actually a method from Object itself! | ||
throw new Error(`${fieldName} key is actually the name of a method on Object, please rename it`); | ||
} | ||
checkAndScrubDefinition(fieldName, _this8._schema[fieldName], _this8._constructorOptions, schemaObj); | ||
}); | ||
this._schema[fieldName] = _objectSpread({}, this._schema[fieldName], (0, _lodash4.default)(definition, 'type')); | ||
if (definition.type) this._schema[fieldName].type.extend(definition.type); | ||
} else { | ||
this._schema[fieldName] = definition; | ||
} | ||
checkSchemaOverlap(this._schema); | ||
checkAndScrubDefinition(fieldName, this._schema[fieldName], this._constructorOptions, schemaObj); | ||
}); | ||
checkSchemaOverlap(this._schema); // Set/Reset all of these | ||
// Set/Reset all of these | ||
this._schemaKeys = Object.keys(this._schema); | ||
this._autoValues = []; | ||
this._blackboxKeys = []; | ||
this._firstLevelSchemaKeys = []; | ||
this._objectKeys = {}; | ||
this._schemaKeys = Object.keys(this._schema); | ||
this._autoValues = []; | ||
this._blackboxKeys = []; | ||
this._firstLevelSchemaKeys = []; | ||
this._objectKeys = {}; // Update all of the information cached on the instance | ||
// Update all of the information cached on the instance | ||
this._schemaKeys.forEach(function (fieldName) { | ||
// Make sure parent has a definition in the schema. No implied objects! | ||
if (fieldName.indexOf('.') > -1) { | ||
var parentFieldName = fieldName.slice(0, fieldName.lastIndexOf('.')); | ||
if (!_this8._schema.hasOwnProperty(parentFieldName)) throw new Error('"' + fieldName + '" is in the schema but "' + parentFieldName + '" is not'); | ||
} | ||
this._schemaKeys.forEach(fieldName => { | ||
// Make sure parent has a definition in the schema. No implied objects! | ||
if (fieldName.indexOf('.') > -1) { | ||
const parentFieldName = fieldName.slice(0, fieldName.lastIndexOf('.')); | ||
if (!this._schema.hasOwnProperty(parentFieldName)) throw new Error(`"${fieldName}" is in the schema but "${parentFieldName}" is not`); | ||
} | ||
var definition = _this8._schema[fieldName]; | ||
const definition = this._schema[fieldName]; // Keep list of all top level keys | ||
// Keep list of all top level keys | ||
if (fieldName.indexOf('.') === -1) _this8._firstLevelSchemaKeys.push(fieldName); | ||
if (fieldName.indexOf('.') === -1) this._firstLevelSchemaKeys.push(fieldName); // Keep list of all blackbox keys for passing to MongoObject constructor | ||
// XXX For now if any oneOf type is blackbox, then the whole field is. | ||
// Keep list of all blackbox keys for passing to MongoObject constructor | ||
// XXX For now if any oneOf type is blackbox, then the whole field is. | ||
(0, _lodash2.default)(definition.type.definitions, function (oneOfDef) { | ||
if (oneOfDef.blackbox === true) { | ||
_this8._blackboxKeys.push(fieldName); | ||
return false; // exit loop | ||
} | ||
return true; | ||
}); | ||
(0, _lodash.default)(definition.type.definitions, oneOfDef => { | ||
if (oneOfDef.blackbox === true) { | ||
this._blackboxKeys.push(fieldName); | ||
// Keep list of autoValue functions | ||
if (typeof definition.autoValue === 'function') { | ||
_this8._autoValues.push({ | ||
closestSubschemaFieldName: '', | ||
fieldName: fieldName, | ||
func: definition.autoValue | ||
}); | ||
return false; // exit loop | ||
} | ||
}); | ||
// Store child keys keyed by parent. This needs to be done recursively to handle | ||
// subschemas. | ||
var setObjectKeys = function setObjectKeys(curSchema, schemaParentKey) { | ||
Object.keys(curSchema).forEach(function (fieldName) { | ||
var definition = curSchema[fieldName]; | ||
fieldName = schemaParentKey ? schemaParentKey + '.' + fieldName : fieldName; | ||
if (fieldName.indexOf('.') > -1 && fieldName.slice(-2) !== '.$') { | ||
var parentKey = fieldName.slice(0, fieldName.lastIndexOf('.')); | ||
var parentKeyWithDot = parentKey + '.'; | ||
_this8._objectKeys[parentKeyWithDot] = _this8._objectKeys[parentKeyWithDot] || []; | ||
_this8._objectKeys[parentKeyWithDot].push(fieldName.slice(fieldName.lastIndexOf('.') + 1)); | ||
} | ||
return true; | ||
}); // Keep list of autoValue functions | ||
// If the current field is a nested SimpleSchema, | ||
// iterate over the child fields and cache their properties as well | ||
definition.type.definitions.forEach(function (_ref3) { | ||
var type = _ref3.type; | ||
if (SimpleSchema.isSimpleSchema(type)) { | ||
setObjectKeys(type._schema, fieldName); | ||
} | ||
}); | ||
if (typeof definition.autoValue === 'function') { | ||
this._autoValues.push({ | ||
closestSubschemaFieldName: '', | ||
fieldName, | ||
func: definition.autoValue | ||
}); | ||
}; | ||
setObjectKeys(this._schema); | ||
return this; | ||
} | ||
}, { | ||
key: 'getAllowedValuesForKey', | ||
value: function getAllowedValuesForKey(key) { | ||
// For array fields, `allowedValues` is on the array item definition | ||
if (this.allowsKey(key + '.$')) { | ||
key = key + '.$'; | ||
} | ||
var allowedValues = this.get(key, 'allowedValues'); | ||
return (0, _lodash6.default)(allowedValues) ? null : [].concat(_toConsumableArray(allowedValues)); | ||
} | ||
}, { | ||
key: 'newContext', | ||
value: function newContext() { | ||
return new _ValidationContext2.default(this); | ||
} | ||
}, { | ||
key: 'namedContext', | ||
value: function namedContext(name) { | ||
if (typeof name !== 'string') name = 'default'; | ||
if (!this._validationContexts[name]) { | ||
this._validationContexts[name] = new _ValidationContext2.default(this); | ||
} | ||
return this._validationContexts[name]; | ||
} | ||
}, { | ||
key: 'addValidator', | ||
value: function addValidator(func) { | ||
this._validators.push(func); | ||
} | ||
}, { | ||
key: 'addDocValidator', | ||
value: function addDocValidator(func) { | ||
this._docValidators.push(func); | ||
} | ||
}); // Store child keys keyed by parent. This needs to be done recursively to handle | ||
// subschemas. | ||
/** | ||
* @param obj {Object|Object[]} Object or array of objects to validate. | ||
* @param [options] {Object} Same options object that ValidationContext#validate takes | ||
* | ||
* Throws an Error with name `ClientError` and `details` property containing the errors. | ||
*/ | ||
}, { | ||
key: 'validate', | ||
value: function validate(obj) { | ||
var _this9 = this; | ||
const setObjectKeys = (curSchema, schemaParentKey) => { | ||
Object.keys(curSchema).forEach(fieldName => { | ||
const definition = curSchema[fieldName]; | ||
fieldName = schemaParentKey ? `${schemaParentKey}.${fieldName}` : fieldName; | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
if (fieldName.indexOf('.') > -1 && fieldName.slice(-2) !== '.$') { | ||
const parentKey = fieldName.slice(0, fieldName.lastIndexOf('.')); | ||
const parentKeyWithDot = `${parentKey}.`; | ||
this._objectKeys[parentKeyWithDot] = this._objectKeys[parentKeyWithDot] || []; | ||
// For Meteor apps, `check` option can be passed to silence audit-argument-checks | ||
var check = options.check || this._constructorOptions.check; | ||
if (typeof check === 'function') { | ||
// Call check but ignore the error | ||
try { | ||
check(obj); | ||
} catch (e) {/* ignore error */} | ||
} | ||
this._objectKeys[parentKeyWithDot].push(fieldName.slice(fieldName.lastIndexOf('.') + 1)); | ||
} // If the current field is a nested SimpleSchema, | ||
// iterate over the child fields and cache their properties as well | ||
// obj can be an array, in which case we validate each object in it and | ||
// throw as soon as one has an error | ||
var objects = Array.isArray(obj) ? obj : [obj]; | ||
objects.forEach(function (oneObj) { | ||
var validationContext = _this9.newContext(); | ||
var isValid = validationContext.validate(oneObj, options); | ||
if (isValid) return; | ||
definition.type.definitions.forEach(({ | ||
type | ||
}) => { | ||
if (SimpleSchema.isSimpleSchema(type)) { | ||
setObjectKeys(type._schema, fieldName); | ||
} | ||
}); | ||
}); | ||
}; | ||
var errors = validationContext.validationErrors(); | ||
setObjectKeys(this._schema); | ||
return this; | ||
} | ||
// In order for the message at the top of the stack trace to be useful, | ||
// we set it to the first validation error message. | ||
var message = _this9.messageForError(errors[0]); | ||
getAllowedValuesForKey(key) { | ||
// For array fields, `allowedValues` is on the array item definition | ||
if (this.allowsKey(`${key}.$`)) { | ||
key = `${key}.$`; | ||
} | ||
var error = new Error(message); | ||
const allowedValues = this.get(key, 'allowedValues'); | ||
return (0, _lodash3.default)(allowedValues) ? null : [...allowedValues]; | ||
} | ||
error.name = error.errorType = 'ClientError'; | ||
error.error = 'validation-error'; | ||
newContext() { | ||
return new _ValidationContext.default(this); | ||
} | ||
// Add meaningful error messages for each validation error. | ||
// Useful for display messages when using 'mdg:validated-method'. | ||
error.details = errors.map(function (errorDetail) { | ||
return _extends({}, errorDetail, { message: _this9.messageForError(errorDetail) }); | ||
}); | ||
namedContext(name) { | ||
if (typeof name !== 'string') name = 'default'; | ||
// The primary use for the validationErrorTransform is to convert the | ||
// vanilla Error into a Meteor.Error until DDP is able to pass | ||
// vanilla errors back to the client. | ||
if (typeof SimpleSchema.validationErrorTransform === 'function') { | ||
throw SimpleSchema.validationErrorTransform(error); | ||
} else { | ||
throw error; | ||
} | ||
}); | ||
if (!this._validationContexts[name]) { | ||
this._validationContexts[name] = new _ValidationContext.default(this); | ||
} | ||
/** | ||
* @param obj {Object} Object to validate. | ||
* @param [options] {Object} Same options object that ValidationContext#validate takes | ||
* | ||
* Returns a Promise that resolves with the errors | ||
*/ | ||
return this._validationContexts[name]; | ||
} | ||
}, { | ||
key: 'validateAndReturnErrorsPromise', | ||
value: function validateAndReturnErrorsPromise(obj, options) { | ||
var _this10 = this; | ||
addValidator(func) { | ||
this._validators.push(func); | ||
} | ||
var validationContext = this.newContext(); | ||
var isValid = validationContext.validate(obj, options); | ||
addDocValidator(func) { | ||
this._docValidators.push(func); | ||
} | ||
/** | ||
* @param obj {Object|Object[]} Object or array of objects to validate. | ||
* @param [options] {Object} Same options object that ValidationContext#validate takes | ||
* | ||
* Throws an Error with name `ClientError` and `details` property containing the errors. | ||
*/ | ||
if (isValid) return Promise.resolve([]); | ||
// Add the `message` prop | ||
var errors = validationContext.validationErrors().map(function (errorDetail) { | ||
return _extends({}, errorDetail, { message: _this10.messageForError(errorDetail) }); | ||
}); | ||
validate(obj, options = {}) { | ||
// For Meteor apps, `check` option can be passed to silence audit-argument-checks | ||
const check = options.check || this._constructorOptions.check; | ||
return Promise.resolve(errors); | ||
} | ||
}, { | ||
key: 'validator', | ||
value: function validator() { | ||
var _this11 = this; | ||
if (typeof check === 'function') { | ||
// Call check but ignore the error | ||
try { | ||
check(obj); | ||
} catch (e) { | ||
/* ignore error */ | ||
} | ||
} // obj can be an array, in which case we validate each object in it and | ||
// throw as soon as one has an error | ||
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
return function (obj) { | ||
var optionsClone = _extends({}, options); | ||
if (options.clean === true) { | ||
// Do this here and pass into both functions for better performance | ||
optionsClone.mongoObject = new _mongoObject2.default(obj, _this11.blackboxKeys()); | ||
_this11.clean(obj, optionsClone); | ||
} | ||
if (options.returnErrorsPromise) { | ||
return _this11.validateAndReturnErrorsPromise(obj, optionsClone); | ||
} | ||
return _this11.validate(obj, optionsClone); | ||
}; | ||
} | ||
}, { | ||
key: 'getFormValidator', | ||
value: function getFormValidator() { | ||
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
const objects = Array.isArray(obj) ? obj : [obj]; | ||
objects.forEach(oneObj => { | ||
const validationContext = this.newContext(); | ||
const isValid = validationContext.validate(oneObj, options); | ||
if (isValid) return; | ||
const errors = validationContext.validationErrors(); // In order for the message at the top of the stack trace to be useful, | ||
// we set it to the first validation error message. | ||
return this.validator(_extends({}, options, { returnErrorsPromise: true })); | ||
} | ||
}, { | ||
key: 'clean', | ||
value: function clean() { | ||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
const message = this.messageForError(errors[0]); | ||
const error = new Error(message); | ||
error.name = error.errorType = 'ClientError'; | ||
error.error = 'validation-error'; // Add meaningful error messages for each validation error. | ||
// Useful for display messages when using 'mdg:validated-method'. | ||
return _clean3.default.apply(undefined, [this].concat(args)); | ||
} | ||
error.details = errors.map(errorDetail => _objectSpread({}, errorDetail, { | ||
message: this.messageForError(errorDetail) | ||
})); // The primary use for the validationErrorTransform is to convert the | ||
// vanilla Error into a Meteor.Error until DDP is able to pass | ||
// vanilla errors back to the client. | ||
/** | ||
* Change schema labels on the fly, causing mySchema.label computation | ||
* to rerun. Useful when the user changes the language. | ||
* | ||
* @param {Object} labels A dictionary of all the new label values, by schema key. | ||
*/ | ||
if (typeof SimpleSchema.validationErrorTransform === 'function') { | ||
throw SimpleSchema.validationErrorTransform(error); | ||
} else { | ||
throw error; | ||
} | ||
}); | ||
} | ||
/** | ||
* @param obj {Object} Object to validate. | ||
* @param [options] {Object} Same options object that ValidationContext#validate takes | ||
* | ||
* Returns a Promise that resolves with the errors | ||
*/ | ||
}, { | ||
key: 'labels', | ||
value: function labels(_labels) { | ||
var _this12 = this; | ||
Object.keys(_labels).forEach(function (key) { | ||
var label = _labels[key]; | ||
if (typeof label !== 'string' && typeof label !== 'function') return; | ||
if (!_this12._schema.hasOwnProperty(key)) return; | ||
validateAndReturnErrorsPromise(obj, options) { | ||
const validationContext = this.newContext(); | ||
const isValid = validationContext.validate(obj, options); | ||
if (isValid) return Promise.resolve([]); // Add the `message` prop | ||
_this12._schema[key].label = label; | ||
_this12._depsLabels[key] && _this12._depsLabels[key].changed(); | ||
const errors = validationContext.validationErrors().map(errorDetail => { | ||
return _objectSpread({}, errorDetail, { | ||
message: this.messageForError(errorDetail) | ||
}); | ||
} | ||
}); | ||
return Promise.resolve(errors); | ||
} | ||
/** | ||
* Gets a field's label or all field labels reactively. | ||
* | ||
* @param {String} [key] The schema key, specific or generic. | ||
* Omit this argument to get a dictionary of all labels. | ||
* @returns {String} The label | ||
*/ | ||
validator(options = {}) { | ||
return obj => { | ||
const optionsClone = _objectSpread({}, options); | ||
}, { | ||
key: 'label', | ||
value: function label(key) { | ||
var _this13 = this; | ||
if (options.clean === true) { | ||
// Do this here and pass into both functions for better performance | ||
optionsClone.mongoObject = new _mongoObject.default(obj, this.blackboxKeys()); | ||
this.clean(obj, optionsClone); | ||
} | ||
// Get all labels | ||
if (key === null || key === undefined) { | ||
var result = {}; | ||
this._schemaKeys.forEach(function (schemaKey) { | ||
result[schemaKey] = _this13.label(schemaKey); | ||
}); | ||
return result; | ||
if (options.returnErrorsPromise) { | ||
return this.validateAndReturnErrorsPromise(obj, optionsClone); | ||
} | ||
// Get label for one field | ||
var label = this.get(key, 'label'); | ||
if (label) this.reactiveLabelDependency(key); | ||
return label || null; | ||
} | ||
return this.validate(obj, optionsClone); | ||
}; | ||
} | ||
/** | ||
* Gets a field's property | ||
* | ||
* @param {String} key The schema key, specific or generic. | ||
* @param {String} prop Name of the property to get for that schema key | ||
* @param {Object} [functionContext] The `this` context to use if prop is a function | ||
* @returns {any} The property value | ||
*/ | ||
getFormValidator(options = {}) { | ||
return this.validator(_objectSpread({}, options, { | ||
returnErrorsPromise: true | ||
})); | ||
} | ||
}, { | ||
key: 'get', | ||
value: function get(key, prop, functionContext) { | ||
var def = this.getDefinition(key, ['type', prop], functionContext); | ||
clean(...args) { | ||
return (0, _clean.default)(this, ...args); | ||
} | ||
/** | ||
* Change schema labels on the fly, causing mySchema.label computation | ||
* to rerun. Useful when the user changes the language. | ||
* | ||
* @param {Object} labels A dictionary of all the new label values, by schema key. | ||
*/ | ||
if (!def) return undefined; | ||
if ((0, _lodash4.default)(schemaDefinitionOptions, prop)) { | ||
return def[prop]; | ||
} | ||
labels(labels) { | ||
Object.keys(labels).forEach(key => { | ||
const label = labels[key]; | ||
if (typeof label !== 'string' && typeof label !== 'function') return; | ||
if (!this._schema.hasOwnProperty(key)) return; | ||
this._schema[key].label = label; | ||
this._depsLabels[key] && this._depsLabels[key].changed(); | ||
}); | ||
} | ||
/** | ||
* Gets a field's label or all field labels reactively. | ||
* | ||
* @param {String} [key] The schema key, specific or generic. | ||
* Omit this argument to get a dictionary of all labels. | ||
* @returns {String} The label | ||
*/ | ||
return (def.type.find(function (props) { | ||
return props[prop]; | ||
}) || {})[prop]; | ||
} | ||
// shorthand for getting defaultValue | ||
label(key) { | ||
// Get all labels | ||
if (key === null || key === undefined) { | ||
const result = {}; | ||
}, { | ||
key: 'defaultValue', | ||
value: function defaultValue(key) { | ||
return this.get(key, 'defaultValue'); | ||
} | ||
this._schemaKeys.forEach(schemaKey => { | ||
result[schemaKey] = this.label(schemaKey); | ||
}); | ||
// Returns a string message for the given error type and key. Passes through | ||
// to message-box pkg. | ||
return result; | ||
} // Get label for one field | ||
}, { | ||
key: 'messageForError', | ||
value: function messageForError(errorInfo) { | ||
var name = errorInfo.name; | ||
const label = this.get(key, 'label'); | ||
if (label) this.reactiveLabelDependency(key); | ||
return label || null; | ||
} | ||
/** | ||
* Gets a field's property | ||
* | ||
* @param {String} key The schema key, specific or generic. | ||
* @param {String} prop Name of the property to get for that schema key | ||
* @param {Object} [functionContext] The `this` context to use if prop is a function | ||
* @returns {any} The property value | ||
*/ | ||
return this.messageBox.message(errorInfo, { | ||
context: { | ||
key: name, // backward compatibility | ||
// The call to this.label() establishes a reactive dependency, too | ||
label: this.label(name) | ||
} | ||
}); | ||
get(key, prop, functionContext) { | ||
const def = this.getDefinition(key, ['type', prop], functionContext); | ||
if (!def) return undefined; | ||
if ((0, _lodash2.default)(schemaDefinitionOptions, prop)) { | ||
return def[prop]; | ||
} | ||
/** | ||
* @method SimpleSchema#pick | ||
* @param {[fields]} The list of fields to pick to instantiate the subschema | ||
* @returns {SimpleSchema} The subschema | ||
*/ | ||
return (def.type.find(props => props[prop]) || {})[prop]; | ||
} // shorthand for getting defaultValue | ||
/** | ||
* @method SimpleSchema#omit | ||
* @param {[fields]} The list of fields to omit to instantiate the subschema | ||
* @returns {SimpleSchema} The subschema | ||
*/ | ||
defaultValue(key) { | ||
return this.get(key, 'defaultValue'); | ||
} // Returns a string message for the given error type and key. Passes through | ||
// to message-box pkg. | ||
}], [{ | ||
key: 'isSimpleSchema', | ||
value: function isSimpleSchema(obj) { | ||
return obj && (obj instanceof SimpleSchema || obj._schema); | ||
} | ||
}, { | ||
key: 'extendOptions', | ||
// If you need to allow properties other than those listed above, call this from your app or package | ||
value: function extendOptions(options) { | ||
// For backwards compatibility we still take an object here, but we only care about the names | ||
if (!Array.isArray(options)) options = Object.keys(options); | ||
options.forEach(function (option) { | ||
schemaDefinitionOptions.push(option); | ||
}); | ||
} | ||
}, { | ||
key: 'defineValidationErrorTransform', | ||
value: function defineValidationErrorTransform(transform) { | ||
if (typeof transform !== 'function') { | ||
throw new Error('SimpleSchema.defineValidationErrorTransform must be passed a function that accepts an Error and returns an Error'); | ||
messageForError(errorInfo) { | ||
const { | ||
name | ||
} = errorInfo; | ||
return this.messageBox.message(errorInfo, { | ||
context: { | ||
key: name, | ||
// backward compatibility | ||
// The call to this.label() establishes a reactive dependency, too | ||
label: this.label(name) | ||
} | ||
SimpleSchema.validationErrorTransform = transform; | ||
} | ||
}, { | ||
key: 'validate', | ||
value: function validate(obj, schema, options) { | ||
// Allow passing just the schema object | ||
if (!SimpleSchema.isSimpleSchema(schema)) { | ||
schema = new SimpleSchema(schema); | ||
} | ||
}); | ||
} | ||
/** | ||
* @method SimpleSchema#pick | ||
* @param {[fields]} The list of fields to pick to instantiate the subschema | ||
* @returns {SimpleSchema} The subschema | ||
*/ | ||
return schema.validate(obj, options); | ||
} | ||
}, { | ||
key: 'oneOf', | ||
value: function oneOf() { | ||
for (var _len2 = arguments.length, definitions = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
definitions[_key2] = arguments[_key2]; | ||
} | ||
return new (Function.prototype.bind.apply(_SimpleSchemaGroup2.default, [null].concat(definitions)))(); | ||
// If you need to allow properties other than those listed above, call this from your app or package | ||
static extendOptions(options) { | ||
// For backwards compatibility we still take an object here, but we only care about the names | ||
if (!Array.isArray(options)) options = Object.keys(options); | ||
options.forEach(option => { | ||
schemaDefinitionOptions.push(option); | ||
}); | ||
} | ||
static defineValidationErrorTransform(transform) { | ||
if (typeof transform !== 'function') { | ||
throw new Error('SimpleSchema.defineValidationErrorTransform must be passed a function that accepts an Error and returns an Error'); | ||
} | ||
// Global custom validators | ||
SimpleSchema.validationErrorTransform = transform; | ||
} | ||
}, { | ||
key: 'addValidator', | ||
value: function addValidator(func) { | ||
SimpleSchema._validators.push(func); | ||
static validate(obj, schema, options) { | ||
// Allow passing just the schema object | ||
if (!SimpleSchema.isSimpleSchema(schema)) { | ||
schema = new SimpleSchema(schema); | ||
} | ||
}, { | ||
key: 'addDocValidator', | ||
value: function addDocValidator(func) { | ||
SimpleSchema._docValidators.push(func); | ||
} | ||
// Backwards compatibility | ||
return schema.validate(obj, options); | ||
} | ||
}]); | ||
static oneOf(...definitions) { | ||
return new _SimpleSchemaGroup.default(...definitions); | ||
} | ||
return SimpleSchema; | ||
}(); | ||
static addValidator(func) { | ||
SimpleSchema._validators.push(func); | ||
} | ||
static addDocValidator(func) { | ||
SimpleSchema._docValidators.push(func); | ||
} | ||
} | ||
/* | ||
* PRIVATE | ||
*/ | ||
// Throws an error if any fields are `type` SimpleSchema but then also | ||
@@ -1019,7 +840,13 @@ // have subfields defined outside of that. | ||
SimpleSchema.version = 2; | ||
SimpleSchema.RegEx = _regExp2.default; | ||
SimpleSchema._validators = []; | ||
SimpleSchema._docValidators = []; | ||
SimpleSchema.ErrorTypes = { | ||
exports.SimpleSchema = SimpleSchema; | ||
_defineProperty(SimpleSchema, "version", 2); | ||
_defineProperty(SimpleSchema, "RegEx", _regExp.default); | ||
_defineProperty(SimpleSchema, "_validators", []); | ||
_defineProperty(SimpleSchema, "_docValidators", []); | ||
_defineProperty(SimpleSchema, "ErrorTypes", { | ||
REQUIRED: 'required', | ||
@@ -1042,22 +869,25 @@ MIN_STRING: 'minString', | ||
KEY_NOT_IN_SCHEMA: 'keyNotInSchema' | ||
}; | ||
SimpleSchema.Integer = 'SimpleSchema.Integer'; | ||
SimpleSchema._makeGeneric = _mongoObject2.default.makeKeyGeneric; | ||
SimpleSchema.ValidationContext = _ValidationContext2.default; | ||
}); | ||
SimpleSchema.setDefaultMessages = function (messages) { | ||
(0, _extend3.default)(true, _defaultMessages2.default, messages); | ||
}; | ||
_defineProperty(SimpleSchema, "Integer", 'SimpleSchema.Integer'); | ||
_defineProperty(SimpleSchema, "_makeGeneric", _mongoObject.default.makeKeyGeneric); | ||
_defineProperty(SimpleSchema, "ValidationContext", _ValidationContext.default); | ||
_defineProperty(SimpleSchema, "setDefaultMessages", messages => { | ||
(0, _extend.default)(true, _defaultMessages.default, messages); | ||
}); | ||
function checkSchemaOverlap(schema) { | ||
Object.keys(schema).forEach(function (key) { | ||
var val = schema[key]; | ||
if (!val.type) throw new Error(key + ' key is missing "type"'); | ||
val.type.definitions.forEach(function (def) { | ||
Object.keys(schema).forEach(key => { | ||
const val = schema[key]; | ||
if (!val.type) throw new Error(`${key} key is missing "type"`); | ||
val.type.definitions.forEach(def => { | ||
if (!SimpleSchema.isSimpleSchema(def.type)) return; | ||
Object.keys(def.type._schema).forEach(subKey => { | ||
const newKey = `${key}.${subKey}`; | ||
Object.keys(def.type._schema).forEach(function (subKey) { | ||
var newKey = key + '.' + subKey; | ||
if (schema.hasOwnProperty(newKey)) { | ||
throw new Error('The type for "' + key + '" is set to a SimpleSchema instance that defines "' + key + '.' + subKey + '", but the parent SimpleSchema instance also tries to define "' + key + '.' + subKey + '"'); | ||
throw new Error(`The type for "${key}" is set to a SimpleSchema instance that defines "${key}.${subKey}", but the parent SimpleSchema instance also tries to define "${key}.${subKey}"`); | ||
} | ||
@@ -1068,3 +898,2 @@ }); | ||
} | ||
/** | ||
@@ -1075,9 +904,13 @@ * @param {String} fieldName The full generic schema key | ||
*/ | ||
function inflectedLabel(fieldName, shouldHumanize) { | ||
var pieces = fieldName.split('.'); | ||
var label = void 0; | ||
const pieces = fieldName.split('.'); | ||
let label; | ||
do { | ||
label = pieces.pop(); | ||
} while (label === '$' && pieces.length); | ||
return shouldHumanize ? (0, _humanize2.default)(label) : label; | ||
return shouldHumanize ? (0, _humanize.default)(label) : label; | ||
} | ||
@@ -1088,61 +921,56 @@ | ||
if (this.isSet) return; | ||
if (this.operator === null) return defaultValue; | ||
// Handle the case when pulling an object from an array the object contains a field | ||
if (this.operator === null) return defaultValue; // Handle the case when pulling an object from an array the object contains a field | ||
// which has a defaultValue. We don't want the default value to be returned in this case | ||
if (this.operator === '$pull') return; | ||
// Handle the case where we are $pushing an object into an array of objects and we | ||
if (this.operator === '$pull') return; // Handle the case where we are $pushing an object into an array of objects and we | ||
// want any fields missing from that object to be added if they have default values | ||
if (this.operator === '$push') return defaultValue; | ||
// If parent is set, we should update this position instead of $setOnInsert | ||
if (this.parentField().isSet) return defaultValue; | ||
if (this.operator === '$push') return defaultValue; // If parent is set, we should update this position instead of $setOnInsert | ||
// Make sure the default value is added on upsert insert | ||
if (this.isUpsert) return { $setOnInsert: defaultValue }; | ||
if (this.parentField().isSet) return defaultValue; // Make sure the default value is added on upsert insert | ||
if (this.isUpsert) return { | ||
$setOnInsert: defaultValue | ||
}; | ||
}; | ||
} | ||
} // Mutates def into standardized object with SimpleSchemaGroup type | ||
// Mutates def into standardized object with SimpleSchemaGroup type | ||
function standardizeDefinition(def) { | ||
var standardizedDef = (0, _lodash8.default)(def, oneOfProps); | ||
// Internally, all definition types are stored as groups for simplicity of access. | ||
const standardizedDef = (0, _lodash4.default)(def, oneOfProps); // Internally, all definition types are stored as groups for simplicity of access. | ||
// If we are extending, there may not actually be def.type, but it's okay because | ||
// it will be added later when the two SimpleSchemaGroups are merged. | ||
if (def.type && def.type instanceof _SimpleSchemaGroup2.default) { | ||
if (def.type && def.type instanceof _SimpleSchemaGroup.default) { | ||
standardizedDef.type = def.type.clone(); | ||
} else { | ||
var groupProps = (0, _lodash10.default)(def, oneOfProps); | ||
standardizedDef.type = new _SimpleSchemaGroup2.default(groupProps); | ||
const groupProps = (0, _lodash5.default)(def, oneOfProps); | ||
standardizedDef.type = new _SimpleSchemaGroup.default(groupProps); | ||
} | ||
return standardizedDef; | ||
} | ||
} // Checks and mutates definition. Clone it first. | ||
// Checks and mutates definition. Clone it first. | ||
function checkAndScrubDefinition(fieldName, definition, options, fullSchemaObj) { | ||
if (!definition.type) throw new Error(fieldName + ' key is missing "type"'); | ||
if (!definition.type) throw new Error(`${fieldName} key is missing "type"`); // Validate the field definition | ||
// Validate the field definition | ||
Object.keys(definition).forEach(function (key) { | ||
Object.keys(definition).forEach(key => { | ||
if (schemaDefinitionOptions.indexOf(key) === -1) { | ||
throw new Error('Invalid definition for ' + fieldName + ' field: "' + key + '" is not a supported property'); | ||
throw new Error(`Invalid definition for ${fieldName} field: "${key}" is not a supported property`); | ||
} | ||
}); | ||
}); // Make sure the `type`s are OK | ||
// Make sure the `type`s are OK | ||
var couldBeArray = false; | ||
definition.type.definitions.forEach(function (_ref4) { | ||
var type = _ref4.type; | ||
let couldBeArray = false; | ||
definition.type.definitions.forEach(({ | ||
type | ||
}) => { | ||
if (!type) throw new Error(`Invalid definition for ${fieldName} field: "type" option is required`); | ||
if (!type) throw new Error('Invalid definition for ' + fieldName + ' field: "type" option is required'); | ||
if (Array.isArray(type)) { | ||
throw new Error('Invalid definition for ' + fieldName + ' field: "type" may not be an array. Change it to Array.'); | ||
throw new Error(`Invalid definition for ${fieldName} field: "type" may not be an array. Change it to Array.`); | ||
} | ||
if (type.constructor === Object && (0, _lodash6.default)(type)) { | ||
throw new Error('Invalid definition for ' + fieldName + ' field: "type" may not be an object. Change it to Object'); | ||
if (type.constructor === Object && (0, _lodash3.default)(type)) { | ||
throw new Error(`Invalid definition for ${fieldName} field: "type" may not be an object. Change it to Object`); | ||
} | ||
@@ -1153,24 +981,23 @@ | ||
if (SimpleSchema.isSimpleSchema(type)) { | ||
Object.keys(type._schema).forEach(function (subKey) { | ||
var newKey = fieldName + '.' + subKey; | ||
Object.keys(type._schema).forEach(subKey => { | ||
const newKey = `${fieldName}.${subKey}`; | ||
if (fullSchemaObj.hasOwnProperty(newKey)) { | ||
throw new Error('The type for "' + fieldName + '" is set to a SimpleSchema instance that defines "' + newKey + '", but the parent SimpleSchema instance also tries to define "' + newKey + '"'); | ||
throw new Error(`The type for "${fieldName}" is set to a SimpleSchema instance that defines "${newKey}", but the parent SimpleSchema instance also tries to define "${newKey}"`); | ||
} | ||
}); | ||
} | ||
}); | ||
// If at least one of the possible types is Array, then make sure we have a | ||
}); // If at least one of the possible types is Array, then make sure we have a | ||
// definition for the array items, too. | ||
if (couldBeArray && !fullSchemaObj.hasOwnProperty(fieldName + '.$')) { | ||
throw new Error('"' + fieldName + '" is Array type but the schema does not include a "' + fieldName + '.$" definition for the array items"'); | ||
} | ||
// defaultValue -> autoValue | ||
if (couldBeArray && !fullSchemaObj.hasOwnProperty(`${fieldName}.$`)) { | ||
throw new Error(`"${fieldName}" is Array type but the schema does not include a "${fieldName}.$" definition for the array items"`); | ||
} // defaultValue -> autoValue | ||
// We support defaultValue shortcut by converting it immediately into an | ||
// autoValue. | ||
if ('defaultValue' in definition) { | ||
if ('autoValue' in definition && !definition.autoValue.isDefault) { | ||
console.warn('SimpleSchema: Found both autoValue and defaultValue options for "' + fieldName + '". Ignoring defaultValue.'); | ||
console.warn(`SimpleSchema: Found both autoValue and defaultValue options for "${fieldName}". Ignoring defaultValue.`); | ||
} else { | ||
@@ -1180,8 +1007,9 @@ if (fieldName.endsWith('.$')) { | ||
} | ||
definition.autoValue = getDefaultAutoValueFunction(definition.defaultValue); | ||
definition.autoValue.isDefault = true; | ||
} | ||
} | ||
} // REQUIREDNESS | ||
// REQUIREDNESS | ||
if (fieldName.endsWith('.$')) { | ||
@@ -1193,7 +1021,3 @@ definition.optional = true; | ||
if (typeof definition.required === 'function') { | ||
definition.optional = function optional() { | ||
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | ||
args[_key3] = arguments[_key3]; | ||
} | ||
definition.optional = function optional(...args) { | ||
return !definition.required.apply(this, args); | ||
@@ -1210,5 +1034,4 @@ }; | ||
delete definition.required; | ||
delete definition.required; // LABELS | ||
// LABELS | ||
if (!definition.hasOwnProperty('label')) { | ||
@@ -1226,20 +1049,13 @@ if (options.defaultLabel) { | ||
function getPickOrOmit(type) { | ||
return function pickOrOmit() { | ||
var _this14 = this; | ||
return function pickOrOmit(...args) { | ||
// If they are picking/omitting an object or array field, we need to also include everything under it | ||
const newSchema = {}; | ||
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { | ||
args[_key4] = arguments[_key4]; | ||
} | ||
// If they are picking/omitting an object or array field, we need to also include everything under it | ||
var newSchema = {}; | ||
this._schemaKeys.forEach(function (key) { | ||
this._schemaKeys.forEach(key => { | ||
// Pick/omit it if it IS in the array of keys they want OR if it | ||
// STARTS WITH something that is in the array plus a period | ||
var includeIt = args.some(function (wantedField) { | ||
return key === wantedField || key.indexOf(wantedField + '.') === 0; | ||
}); | ||
const includeIt = args.some(wantedField => key === wantedField || key.indexOf(`${wantedField}.`) === 0); | ||
if (includeIt && type === 'pick' || !includeIt && type === 'omit') { | ||
newSchema[key] = _this14._schema[key]; | ||
newSchema[key] = this._schema[key]; | ||
} | ||
@@ -1250,5 +1066,2 @@ }); | ||
}; | ||
} | ||
exports.SimpleSchema = SimpleSchema; | ||
exports.ValidationContext = _ValidationContext2.default; | ||
} |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,30 +6,15 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
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 _mongoObject = _interopRequireDefault(require("mongo-object")); | ||
var _mongoObject = require('mongo-object'); | ||
var _extend = _interopRequireDefault(require("extend")); | ||
var _mongoObject2 = _interopRequireDefault(_mongoObject); | ||
var _extend2 = require('extend'); | ||
var _extend3 = _interopRequireDefault(_extend2); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } | ||
class SimpleSchemaGroup { | ||
constructor(...definitions) { | ||
this.definitions = definitions.map(definition => { | ||
if (_mongoObject.default.isBasicObject(definition)) return (0, _extend.default)(true, {}, definition); | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
var SimpleSchemaGroup = function () { | ||
function SimpleSchemaGroup() { | ||
_classCallCheck(this, SimpleSchemaGroup); | ||
for (var _len = arguments.length, definitions = Array(_len), _key = 0; _key < _len; _key++) { | ||
definitions[_key] = arguments[_key]; | ||
} | ||
this.definitions = definitions.map(function (definition) { | ||
if (_mongoObject2.default.isBasicObject(definition)) return (0, _extend3.default)(true, {}, definition); | ||
if (definition instanceof RegExp) { | ||
@@ -48,27 +33,24 @@ return { | ||
_createClass(SimpleSchemaGroup, [{ | ||
key: 'clone', | ||
value: function clone() { | ||
return new (Function.prototype.bind.apply(SimpleSchemaGroup, [null].concat(_toConsumableArray(this.definitions))))(); | ||
} | ||
}, { | ||
key: 'extend', | ||
value: function extend(otherGroup) { | ||
// We extend based on index being the same. No better way I can think of at the moment. | ||
this.definitions = this.definitions.map(function (def, index) { | ||
var otherDef = otherGroup.definitions[index]; | ||
if (!otherDef) return def; | ||
return (0, _extend3.default)(true, {}, def, otherDef); | ||
}); | ||
} | ||
}, { | ||
key: 'singleType', | ||
get: function get() { | ||
return this.definitions[0].type; | ||
} | ||
}]); | ||
get singleType() { | ||
return this.definitions[0].type; | ||
} | ||
return SimpleSchemaGroup; | ||
}(); | ||
clone() { | ||
return new SimpleSchemaGroup(...this.definitions); | ||
} | ||
exports.default = SimpleSchemaGroup; | ||
extend(otherGroup) { | ||
// We extend based on index being the same. No better way I can think of at the moment. | ||
this.definitions = this.definitions.map((def, index) => { | ||
const otherDef = otherGroup.definitions[index]; | ||
if (!otherDef) return def; | ||
return (0, _extend.default)(true, {}, def, otherDef); | ||
}); | ||
} | ||
} | ||
var _default = SimpleSchemaGroup; | ||
exports.default = _default; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -7,5 +7,9 @@ Object.defineProperty(exports, "__esModule", { | ||
exports.default = appendAffectedKey; | ||
function appendAffectedKey(affectedKey, key) { | ||
if (key === '$each') return affectedKey; | ||
return affectedKey ? affectedKey + '.' + key : key; | ||
} | ||
return affectedKey ? `${affectedKey}.${key}` : key; | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -7,2 +7,3 @@ "use strict"; | ||
exports.default = dateToDateString; | ||
/** | ||
@@ -12,7 +13,10 @@ * Given a Date instance, returns a date string of the format YYYY-MM-DD | ||
function dateToDateString(date) { | ||
var m = date.getUTCMonth() + 1; | ||
if (m < 10) m = "0" + m; | ||
var d = date.getUTCDate(); | ||
if (d < 10) d = "0" + d; | ||
return date.getUTCFullYear() + "-" + m + "-" + d; | ||
} | ||
let m = date.getUTCMonth() + 1; | ||
if (m < 10) m = `0${m}`; | ||
let d = date.getUTCDate(); | ||
if (d < 10) d = `0${d}`; | ||
return `${date.getUTCFullYear()}-${m}-${d}`; | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -7,2 +7,3 @@ Object.defineProperty(exports, "__esModule", { | ||
exports.default = forEachKeyAncestor; | ||
/** | ||
@@ -13,14 +14,18 @@ * Run loopFunc for each ancestor key in a dot-delimited key. For example, | ||
function forEachKeyAncestor(key, loopFunc) { | ||
var lastDot = void 0; | ||
let lastDot; // Iterate the dot-syntax hierarchy | ||
// Iterate the dot-syntax hierarchy | ||
var ancestor = key; | ||
let ancestor = key; | ||
do { | ||
lastDot = ancestor.lastIndexOf('.'); | ||
if (lastDot !== -1) { | ||
ancestor = ancestor.slice(0, lastDot); | ||
var remainder = key.slice(ancestor.length + 1); | ||
const remainder = key.slice(ancestor.length + 1); | ||
loopFunc(ancestor, remainder); // Remove last path component | ||
} | ||
} while (lastDot !== -1); | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -7,2 +7,3 @@ "use strict"; | ||
exports.default = getKeysWithValueInObj; | ||
/** | ||
@@ -14,12 +15,11 @@ * Returns an array of keys that are in obj, have a value | ||
function getKeysWithValueInObj(obj, matchKey) { | ||
var keysWithValue = []; | ||
const keysWithValue = []; | ||
var keyAdjust = function keyAdjust(k) { | ||
return k.slice(0, matchKey.length + 1); | ||
}; | ||
var matchKeyPlusDot = matchKey + "."; | ||
const keyAdjust = k => k.slice(0, matchKey.length + 1); | ||
Object.keys(obj || {}).forEach(function (key) { | ||
var val = obj[key]; | ||
const matchKeyPlusDot = `${matchKey}.`; | ||
Object.keys(obj || {}).forEach(key => { | ||
const val = obj[key]; | ||
if (val === undefined || val === null) return; | ||
if (keyAdjust(key) === matchKeyPlusDot) { | ||
@@ -29,4 +29,6 @@ keysWithValue.push(key); | ||
}); | ||
return keysWithValue; | ||
} | ||
return keysWithValue; | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -7,2 +7,3 @@ Object.defineProperty(exports, "__esModule", { | ||
exports.default = getLastPartOfKey; | ||
/** | ||
@@ -16,4 +17,5 @@ * Returns the ending of key, after stripping out the beginning | ||
function getLastPartOfKey(key, ancestorKey) { | ||
var lastPart = ''; | ||
var startString = ancestorKey + '.'; | ||
let lastPart = ''; | ||
const startString = `${ancestorKey}.`; | ||
if (key.indexOf(startString) === 0) { | ||
@@ -23,3 +25,7 @@ lastPart = key.replace(startString, ''); | ||
} | ||
return lastPart; | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -7,2 +7,3 @@ Object.defineProperty(exports, "__esModule", { | ||
exports.default = getParentOfKey; | ||
/** | ||
@@ -14,4 +15,7 @@ * Returns the parent of a key. For example, returns 'a.b' when passed 'a.b.c'. | ||
function getParentOfKey(key, withEndDot) { | ||
var lastDot = key.lastIndexOf('.'); | ||
const lastDot = key.lastIndexOf('.'); | ||
return lastDot === -1 ? '' : key.slice(0, lastDot + Number(!!withEndDot)); | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,75 +6,67 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
var _appendAffectedKey = require('./appendAffectedKey'); | ||
Object.defineProperty(exports, 'appendAffectedKey', { | ||
Object.defineProperty(exports, "appendAffectedKey", { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_appendAffectedKey).default; | ||
get: function () { | ||
return _appendAffectedKey.default; | ||
} | ||
}); | ||
var _dateToDateString = require('./dateToDateString'); | ||
Object.defineProperty(exports, 'dateToDateString', { | ||
Object.defineProperty(exports, "dateToDateString", { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_dateToDateString).default; | ||
get: function () { | ||
return _dateToDateString.default; | ||
} | ||
}); | ||
var _forEachKeyAncestor = require('./forEachKeyAncestor'); | ||
Object.defineProperty(exports, 'forEachKeyAncestor', { | ||
Object.defineProperty(exports, "forEachKeyAncestor", { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_forEachKeyAncestor).default; | ||
get: function () { | ||
return _forEachKeyAncestor.default; | ||
} | ||
}); | ||
var _getKeysWithValueInObj = require('./getKeysWithValueInObj'); | ||
Object.defineProperty(exports, 'getKeysWithValueInObj', { | ||
Object.defineProperty(exports, "getKeysWithValueInObj", { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_getKeysWithValueInObj).default; | ||
get: function () { | ||
return _getKeysWithValueInObj.default; | ||
} | ||
}); | ||
var _getLastPartOfKey = require('./getLastPartOfKey'); | ||
Object.defineProperty(exports, 'getLastPartOfKey', { | ||
Object.defineProperty(exports, "getLastPartOfKey", { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_getLastPartOfKey).default; | ||
get: function () { | ||
return _getLastPartOfKey.default; | ||
} | ||
}); | ||
var _getParentOfKey = require('./getParentOfKey'); | ||
Object.defineProperty(exports, 'getParentOfKey', { | ||
Object.defineProperty(exports, "getParentOfKey", { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_getParentOfKey).default; | ||
get: function () { | ||
return _getParentOfKey.default; | ||
} | ||
}); | ||
var _isObjectWeShouldTraverse = require('./isObjectWeShouldTraverse'); | ||
Object.defineProperty(exports, 'isObjectWeShouldTraverse', { | ||
Object.defineProperty(exports, "isObjectWeShouldTraverse", { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_isObjectWeShouldTraverse).default; | ||
get: function () { | ||
return _isObjectWeShouldTraverse.default; | ||
} | ||
}); | ||
var _looksLikeModifier = require('./looksLikeModifier'); | ||
Object.defineProperty(exports, 'looksLikeModifier', { | ||
Object.defineProperty(exports, "looksLikeModifier", { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_looksLikeModifier).default; | ||
get: function () { | ||
return _looksLikeModifier.default; | ||
} | ||
}); | ||
var _appendAffectedKey = _interopRequireDefault(require("./appendAffectedKey")); | ||
var _dateToDateString = _interopRequireDefault(require("./dateToDateString")); | ||
var _forEachKeyAncestor = _interopRequireDefault(require("./forEachKeyAncestor")); | ||
var _getKeysWithValueInObj = _interopRequireDefault(require("./getKeysWithValueInObj")); | ||
var _getLastPartOfKey = _interopRequireDefault(require("./getLastPartOfKey")); | ||
var _getParentOfKey = _interopRequireDefault(require("./getParentOfKey")); | ||
var _isObjectWeShouldTraverse = _interopRequireDefault(require("./isObjectWeShouldTraverse")); | ||
var _looksLikeModifier = _interopRequireDefault(require("./looksLikeModifier")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } |
@@ -7,8 +7,9 @@ "use strict"; | ||
exports.default = isObjectWeShouldTraverse; | ||
function isObjectWeShouldTraverse(val) { | ||
// Some of these types don't exist in old browsers so we'll catch and return false in those cases | ||
try { | ||
if (val !== Object(val)) return false; | ||
// There are some object types that we know we shouldn't traverse because | ||
if (val !== Object(val)) return false; // There are some object types that we know we shouldn't traverse because | ||
// they will often result in overflows and it makes no sense to validate them. | ||
if (val instanceof Date) return false; | ||
@@ -29,2 +30,5 @@ if (val instanceof Int8Array) return false; | ||
return true; | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -7,2 +7,3 @@ Object.defineProperty(exports, "__esModule", { | ||
exports.default = looksLikeModifier; | ||
/** | ||
@@ -12,5 +13,6 @@ * Returns true if any of the keys of obj start with a $ | ||
function looksLikeModifier(obj) { | ||
return !!Object.keys(obj || {}).find(function (key) { | ||
return key.substring(0, 1) === '$'; | ||
}); | ||
} | ||
return !!Object.keys(obj || {}).find(key => key.substring(0, 1) === '$'); | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -8,8 +8,6 @@ Object.defineProperty(exports, "__esModule", { | ||
var _SimpleSchema = require('../SimpleSchema'); | ||
var _SimpleSchema = require("../SimpleSchema"); | ||
var _lodash = require('lodash.includes'); | ||
var _lodash = _interopRequireDefault(require("lodash.includes")); | ||
var _lodash2 = _interopRequireDefault(_lodash); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -19,15 +17,16 @@ | ||
if (!this.valueShouldBeChecked) return; | ||
var allowedValues = this.definition.allowedValues; | ||
const allowedValues = this.definition.allowedValues; | ||
if (!allowedValues) return; | ||
let isAllowed; // set defined in scope and allowedValues is its instance | ||
var isAllowed = void 0; | ||
// set defined in scope and allowedValues is its instance | ||
if (typeof Set === 'function' && allowedValues instanceof Set) { | ||
isAllowed = allowedValues.has(this.value); | ||
} else { | ||
isAllowed = (0, _lodash2.default)(allowedValues, this.value); | ||
isAllowed = (0, _lodash.default)(allowedValues, this.value); | ||
} | ||
return isAllowed ? true : _SimpleSchema.SimpleSchema.ErrorTypes.VALUE_NOT_ALLOWED; | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -8,5 +8,5 @@ Object.defineProperty(exports, "__esModule", { | ||
var _SimpleSchema = require('../SimpleSchema'); | ||
var _SimpleSchema = require("../SimpleSchema"); | ||
var _utility = require('../utility'); | ||
var _utility = require("../utility"); | ||
@@ -22,45 +22,41 @@ // Check for missing required values. The general logic is this: | ||
function requiredValidator() { | ||
var definition = this.definition, | ||
isInArrayItemObject = this.isInArrayItemObject, | ||
isInSubObject = this.isInSubObject, | ||
key = this.key, | ||
obj = this.obj, | ||
operator = this.operator, | ||
value = this.value; | ||
var optional = definition.optional; | ||
const { | ||
definition, | ||
isInArrayItemObject, | ||
isInSubObject, | ||
key, | ||
obj, | ||
operator, | ||
value | ||
} = this; | ||
const { | ||
optional | ||
} = definition; | ||
if (optional) return; // If value is null, no matter what, we add required | ||
if (value === null) return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; // If operator would remove, we add required | ||
if (optional) return; | ||
if (operator === '$unset' || operator === '$rename') return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; // The rest of these apply only if the value is undefined | ||
// If value is null, no matter what, we add required | ||
if (value === null) return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; | ||
if (value !== undefined) return; // At this point, if it's a normal, non-modifier object, then a missing value is an error | ||
// If operator would remove, we add required | ||
if (operator === '$unset' || operator === '$rename') return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; | ||
// The rest of these apply only if the value is undefined | ||
if (value !== undefined) return; | ||
// At this point, if it's a normal, non-modifier object, then a missing value is an error | ||
if (!operator) return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; | ||
// Everything beyond this point deals with modifier objects only | ||
if (!operator) return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; // Everything beyond this point deals with modifier objects only | ||
// We can skip the required check for keys that are ancestors of those in $set or | ||
// $setOnInsert because they will be created by MongoDB while setting. | ||
var keysWithValueInSet = (0, _utility.getKeysWithValueInObj)(obj.$set, key); | ||
const keysWithValueInSet = (0, _utility.getKeysWithValueInObj)(obj.$set, key); | ||
if (keysWithValueInSet.length) return; | ||
var keysWithValueInSetOnInsert = (0, _utility.getKeysWithValueInObj)(obj.$setOnInsert, key); | ||
if (keysWithValueInSetOnInsert.length) return; | ||
// In the case of $set and $setOnInsert, the value may be undefined here | ||
const keysWithValueInSetOnInsert = (0, _utility.getKeysWithValueInObj)(obj.$setOnInsert, key); | ||
if (keysWithValueInSetOnInsert.length) return; // In the case of $set and $setOnInsert, the value may be undefined here | ||
// but it is set in another operator. So check that first. | ||
var fieldInfo = this.field(key); | ||
if (fieldInfo.isSet && fieldInfo.value !== null) return; | ||
// Required if in an array or sub object | ||
if (isInArrayItemObject || isInSubObject) return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; | ||
const fieldInfo = this.field(key); | ||
if (fieldInfo.isSet && fieldInfo.value !== null) return; // Required if in an array or sub object | ||
// If we've got this far with an undefined $set or $setOnInsert value, it's a required error. | ||
if (isInArrayItemObject || isInSubObject) return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; // If we've got this far with an undefined $set or $setOnInsert value, it's a required error. | ||
if (operator === '$set' || operator === '$setOnInsert') return _SimpleSchema.SimpleSchema.ErrorTypes.REQUIRED; | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -8,3 +8,3 @@ Object.defineProperty(exports, "__esModule", { | ||
var _SimpleSchema = require('../../SimpleSchema'); | ||
var _SimpleSchema = require("../../SimpleSchema"); | ||
@@ -14,14 +14,26 @@ function doArrayChecks(def, keyValue) { | ||
if (!Array.isArray(keyValue)) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Array' }; | ||
} | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, | ||
dataType: 'Array' | ||
}; | ||
} // Are there fewer than the minimum number of items in the array? | ||
// Are there fewer than the minimum number of items in the array? | ||
if (def.minCount !== null && keyValue.length < def.minCount) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.MIN_COUNT, minCount: def.minCount }; | ||
} | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.MIN_COUNT, | ||
minCount: def.minCount | ||
}; | ||
} // Are there more than the maximum number of items in the array? | ||
// Are there more than the maximum number of items in the array? | ||
if (def.maxCount !== null && keyValue.length > def.maxCount) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.MAX_COUNT, maxCount: def.maxCount }; | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.MAX_COUNT, | ||
maxCount: def.maxCount | ||
}; | ||
} | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -8,19 +8,29 @@ Object.defineProperty(exports, "__esModule", { | ||
var _SimpleSchema = require('../../SimpleSchema'); | ||
var _SimpleSchema = require("../../SimpleSchema"); | ||
var _utility = require('../../utility'); | ||
var _utility = require("../../utility"); | ||
function doDateChecks(def, keyValue) { | ||
// Is it an invalid date? | ||
if (isNaN(keyValue.getTime())) return { type: _SimpleSchema.SimpleSchema.ErrorTypes.BAD_DATE }; | ||
if (isNaN(keyValue.getTime())) return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.BAD_DATE | ||
}; // Is it earlier than the minimum date? | ||
// Is it earlier than the minimum date? | ||
if (def.min && typeof def.min.getTime === 'function' && def.min.getTime() > keyValue.getTime()) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.MIN_DATE, min: (0, _utility.dateToDateString)(def.min) }; | ||
} | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.MIN_DATE, | ||
min: (0, _utility.dateToDateString)(def.min) | ||
}; | ||
} // Is it later than the maximum date? | ||
// Is it later than the maximum date? | ||
if (def.max && typeof def.max.getTime === 'function' && def.max.getTime() < keyValue.getTime()) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.MAX_DATE, max: (0, _utility.dateToDateString)(def.max) }; | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.MAX_DATE, | ||
max: (0, _utility.dateToDateString)(def.max) | ||
}; | ||
} | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -8,3 +8,3 @@ Object.defineProperty(exports, "__esModule", { | ||
var _SimpleSchema = require('../../SimpleSchema'); | ||
var _SimpleSchema = require("../../SimpleSchema"); | ||
@@ -19,19 +19,33 @@ // Polyfill to support IE11 | ||
if (typeof keyValue !== 'number' || isNaN(keyValue)) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: expectsInteger ? 'Integer' : 'Number' }; | ||
} | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, | ||
dataType: expectsInteger ? 'Integer' : 'Number' | ||
}; | ||
} // Assuming we are not incrementing, is the value less than the maximum value? | ||
// Assuming we are not incrementing, is the value less than the maximum value? | ||
if (op !== '$inc' && def.max !== null && (!!def.exclusiveMax ? def.max <= keyValue : def.max < keyValue)) { | ||
return { type: !!def.exclusiveMax ? _SimpleSchema.SimpleSchema.ErrorTypes.MAX_NUMBER_EXCLUSIVE : _SimpleSchema.SimpleSchema.ErrorTypes.MAX_NUMBER, max: def.max }; | ||
} | ||
return { | ||
type: !!def.exclusiveMax ? _SimpleSchema.SimpleSchema.ErrorTypes.MAX_NUMBER_EXCLUSIVE : _SimpleSchema.SimpleSchema.ErrorTypes.MAX_NUMBER, | ||
max: def.max | ||
}; | ||
} // Assuming we are not incrementing, is the value more than the minimum value? | ||
// Assuming we are not incrementing, is the value more than the minimum value? | ||
if (op !== '$inc' && def.min !== null && (!!def.exclusiveMin ? def.min >= keyValue : def.min > keyValue)) { | ||
return { type: !!def.exclusiveMin ? _SimpleSchema.SimpleSchema.ErrorTypes.MIN_NUMBER_EXCLUSIVE : _SimpleSchema.SimpleSchema.ErrorTypes.MIN_NUMBER, min: def.min }; | ||
} | ||
return { | ||
type: !!def.exclusiveMin ? _SimpleSchema.SimpleSchema.ErrorTypes.MIN_NUMBER_EXCLUSIVE : _SimpleSchema.SimpleSchema.ErrorTypes.MIN_NUMBER, | ||
min: def.min | ||
}; | ||
} // Is it an integer if we expect an integer? | ||
// Is it an integer if we expect an integer? | ||
if (expectsInteger && !Number.isInteger(keyValue)) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.MUST_BE_INTEGER }; | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.MUST_BE_INTEGER | ||
}; | ||
} | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -8,3 +8,3 @@ Object.defineProperty(exports, "__esModule", { | ||
var _SimpleSchema = require('../../SimpleSchema'); | ||
var _SimpleSchema = require("../../SimpleSchema"); | ||
@@ -14,28 +14,44 @@ function doStringChecks(def, keyValue) { | ||
if (typeof keyValue !== 'string') { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'String' }; | ||
} | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, | ||
dataType: 'String' | ||
}; | ||
} // Is the string too long? | ||
// Is the string too long? | ||
if (def.max !== null && def.max < keyValue.length) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.MAX_STRING, max: def.max }; | ||
} | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.MAX_STRING, | ||
max: def.max | ||
}; | ||
} // Is the string too short? | ||
// Is the string too short? | ||
if (def.min !== null && def.min > keyValue.length) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.MIN_STRING, min: def.min }; | ||
} | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.MIN_STRING, | ||
min: def.min | ||
}; | ||
} // Does the string match the regular expression? | ||
// Does the string match the regular expression? | ||
if (def.regEx instanceof RegExp && !def.regEx.test(keyValue)) { | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.FAILED_REGULAR_EXPRESSION, regExp: def.regEx.toString() }; | ||
} | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.FAILED_REGULAR_EXPRESSION, | ||
regExp: def.regEx.toString() | ||
}; | ||
} // If regEx is an array of regular expressions, does the string match all of them? | ||
// If regEx is an array of regular expressions, does the string match all of them? | ||
if (Array.isArray(def.regEx)) { | ||
var regExError = void 0; | ||
def.regEx.every(function (re) { | ||
let regExError; | ||
def.regEx.every(re => { | ||
if (!re.test(keyValue)) { | ||
regExError = { type: _SimpleSchema.SimpleSchema.ErrorTypes.FAILED_REGULAR_EXPRESSION, regExp: re.toString() }; | ||
regExError = { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.FAILED_REGULAR_EXPRESSION, | ||
regExp: re.toString() | ||
}; | ||
return false; | ||
} | ||
return true; | ||
@@ -45,2 +61,5 @@ }); | ||
} | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -8,20 +8,12 @@ Object.defineProperty(exports, "__esModule", { | ||
var _SimpleSchema = require('../../SimpleSchema'); | ||
var _SimpleSchema = require("../../SimpleSchema"); | ||
var _doDateChecks = require('./doDateChecks'); | ||
var _doDateChecks = _interopRequireDefault(require("./doDateChecks")); | ||
var _doDateChecks2 = _interopRequireDefault(_doDateChecks); | ||
var _doNumberChecks = _interopRequireDefault(require("./doNumberChecks")); | ||
var _doNumberChecks = require('./doNumberChecks'); | ||
var _doStringChecks = _interopRequireDefault(require("./doStringChecks")); | ||
var _doNumberChecks2 = _interopRequireDefault(_doNumberChecks); | ||
var _doArrayChecks = _interopRequireDefault(require("./doArrayChecks")); | ||
var _doStringChecks = require('./doStringChecks'); | ||
var _doStringChecks2 = _interopRequireDefault(_doStringChecks); | ||
var _doArrayChecks = require('./doArrayChecks'); | ||
var _doArrayChecks2 = _interopRequireDefault(_doArrayChecks); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -31,16 +23,17 @@ | ||
if (!this.valueShouldBeChecked) return; | ||
const def = this.definition; | ||
const expectedType = def.type; | ||
const keyValue = this.value; | ||
const op = this.operator; | ||
if (expectedType === String) return (0, _doStringChecks.default)(def, keyValue); | ||
if (expectedType === Number) return (0, _doNumberChecks.default)(def, keyValue, op, false); | ||
if (expectedType === _SimpleSchema.SimpleSchema.Integer) return (0, _doNumberChecks.default)(def, keyValue, op, true); | ||
var def = this.definition; | ||
var expectedType = def.type; | ||
var keyValue = this.value; | ||
var op = this.operator; | ||
if (expectedType === String) return (0, _doStringChecks2.default)(def, keyValue); | ||
if (expectedType === Number) return (0, _doNumberChecks2.default)(def, keyValue, op, false); | ||
if (expectedType === _SimpleSchema.SimpleSchema.Integer) return (0, _doNumberChecks2.default)(def, keyValue, op, true); | ||
if (expectedType === Boolean) { | ||
// Is it a boolean? | ||
if (typeof keyValue === 'boolean') return; | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Boolean' }; | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, | ||
dataType: 'Boolean' | ||
}; | ||
} | ||
@@ -51,14 +44,22 @@ | ||
if (keyValue === Object(keyValue) && !(keyValue instanceof Date)) return; | ||
return { type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: 'Object' }; | ||
return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, | ||
dataType: 'Object' | ||
}; | ||
} | ||
if (expectedType === Array) return (0, _doArrayChecks2.default)(def, keyValue); | ||
if (expectedType === Array) return (0, _doArrayChecks.default)(def, keyValue); | ||
if (expectedType instanceof Function) { | ||
// Generic constructor checks | ||
if (!(keyValue instanceof expectedType)) return { type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, dataType: expectedType.name }; | ||
if (!(keyValue instanceof expectedType)) return { | ||
type: _SimpleSchema.SimpleSchema.ErrorTypes.EXPECTED_TYPE, | ||
dataType: expectedType.name | ||
}; // Date checks | ||
// Date checks | ||
if (expectedType === Date) return (0, _doDateChecks2.default)(def, keyValue); | ||
if (expectedType === Date) return (0, _doDateChecks.default)(def, keyValue); | ||
} | ||
} | ||
} | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
@@ -1,2 +0,2 @@ | ||
'use strict'; | ||
"use strict"; | ||
@@ -6,40 +6,29 @@ Object.defineProperty(exports, "__esModule", { | ||
}); | ||
exports.default = void 0; | ||
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 _mongoObject = _interopRequireDefault(require("mongo-object")); | ||
var _mongoObject = require('mongo-object'); | ||
var _doValidation = _interopRequireDefault(require("./doValidation.js")); | ||
var _mongoObject2 = _interopRequireDefault(_mongoObject); | ||
var _lodash = _interopRequireDefault(require("lodash.findwhere")); | ||
var _doValidation = require('./doValidation.js'); | ||
var _doValidation2 = _interopRequireDefault(_doValidation); | ||
var _lodash = require('lodash.findwhere'); | ||
var _lodash2 = _interopRequireDefault(_lodash); | ||
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"); } } | ||
var ValidationContext = function () { | ||
function ValidationContext(ss) { | ||
var _this = this; | ||
_classCallCheck(this, ValidationContext); | ||
class ValidationContext { | ||
constructor(ss) { | ||
this._simpleSchema = ss; | ||
this._schema = ss.schema(); | ||
this._schemaKeys = Object.keys(this._schema); | ||
this._validationErrors = []; | ||
this._validationErrors = []; // Set up validation dependencies | ||
// Set up validation dependencies | ||
this._deps = {}; | ||
var tracker = ss._constructorOptions.tracker; | ||
const { | ||
tracker | ||
} = ss._constructorOptions; | ||
if (tracker) { | ||
this._depsAny = new tracker.Dependency(); | ||
this._schemaKeys.forEach(function (key) { | ||
_this._deps[key] = new tracker.Dependency(); | ||
this._schemaKeys.forEach(key => { | ||
this._deps[key] = new tracker.Dependency(); | ||
}); | ||
@@ -49,196 +38,120 @@ } | ||
_createClass(ValidationContext, [{ | ||
key: '_markKeyChanged', | ||
value: function _markKeyChanged(key) { | ||
var genericKey = _mongoObject2.default.makeKeyGeneric(key); | ||
if (this._deps.hasOwnProperty(genericKey)) this._deps[genericKey].changed(); | ||
} | ||
}, { | ||
key: '_markKeysChanged', | ||
value: function _markKeysChanged(keys) { | ||
var _this2 = this; | ||
_markKeyChanged(key) { | ||
const genericKey = _mongoObject.default.makeKeyGeneric(key); | ||
if (!keys || !Array.isArray(keys) || !keys.length) return; | ||
if (this._deps.hasOwnProperty(genericKey)) this._deps[genericKey].changed(); | ||
} | ||
keys.forEach(function (key) { | ||
return _this2._markKeyChanged(key); | ||
}); | ||
_markKeysChanged(keys) { | ||
if (!keys || !Array.isArray(keys) || !keys.length) return; | ||
keys.forEach(key => this._markKeyChanged(key)); | ||
this._depsAny && this._depsAny.changed(); | ||
} | ||
this._depsAny && this._depsAny.changed(); | ||
} | ||
}, { | ||
key: 'setValidationErrors', | ||
value: function setValidationErrors(errors) { | ||
var previousValidationErrors = this._validationErrors.map(function (o) { | ||
return o.name; | ||
}); | ||
var newValidationErrors = errors.map(function (o) { | ||
return o.name; | ||
}); | ||
setValidationErrors(errors) { | ||
const previousValidationErrors = this._validationErrors.map(o => o.name); | ||
this._validationErrors = errors; | ||
const newValidationErrors = errors.map(o => o.name); | ||
this._validationErrors = errors; // Mark all previous plus all new as changed | ||
// Mark all previous plus all new as changed | ||
var changedKeys = previousValidationErrors.concat(newValidationErrors); | ||
this._markKeysChanged(changedKeys); | ||
} | ||
}, { | ||
key: 'addValidationErrors', | ||
value: function addValidationErrors(errors) { | ||
var _this3 = this; | ||
const changedKeys = previousValidationErrors.concat(newValidationErrors); | ||
var newValidationErrors = errors.map(function (o) { | ||
return o.name; | ||
}); | ||
this._markKeysChanged(changedKeys); | ||
} | ||
errors.forEach(function (error) { | ||
return _this3._validationErrors.push(error); | ||
}); | ||
addValidationErrors(errors) { | ||
const newValidationErrors = errors.map(o => o.name); | ||
errors.forEach(error => this._validationErrors.push(error)); // Mark all new as changed | ||
// Mark all new as changed | ||
this._markKeysChanged(newValidationErrors); | ||
} | ||
this._markKeysChanged(newValidationErrors); | ||
} // Reset the validationErrors array | ||
// Reset the validationErrors array | ||
}, { | ||
key: 'reset', | ||
value: function reset() { | ||
this.setValidationErrors([]); | ||
} | ||
}, { | ||
key: 'getErrorForKey', | ||
value: function getErrorForKey(key) { | ||
var genericKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _mongoObject2.default.makeKeyGeneric(key); | ||
reset() { | ||
this.setValidationErrors([]); | ||
} | ||
var errors = this._validationErrors; | ||
return (0, _lodash2.default)(errors, { name: key }) || (0, _lodash2.default)(errors, { name: genericKey }); | ||
} | ||
}, { | ||
key: '_keyIsInvalid', | ||
value: function _keyIsInvalid(key, genericKey) { | ||
return !!this.getErrorForKey(key, genericKey); | ||
} | ||
getErrorForKey(key, genericKey = _mongoObject.default.makeKeyGeneric(key)) { | ||
const errors = this._validationErrors; | ||
return (0, _lodash.default)(errors, { | ||
name: key | ||
}) || (0, _lodash.default)(errors, { | ||
name: genericKey | ||
}); | ||
} | ||
// Like the internal one, but with deps | ||
_keyIsInvalid(key, genericKey) { | ||
return !!this.getErrorForKey(key, genericKey); | ||
} // Like the internal one, but with deps | ||
}, { | ||
key: 'keyIsInvalid', | ||
value: function keyIsInvalid(key) { | ||
var genericKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _mongoObject2.default.makeKeyGeneric(key); | ||
if (this._deps.hasOwnProperty(genericKey)) this._deps[genericKey].depend(); | ||
keyIsInvalid(key, genericKey = _mongoObject.default.makeKeyGeneric(key)) { | ||
if (this._deps.hasOwnProperty(genericKey)) this._deps[genericKey].depend(); | ||
return this._keyIsInvalid(key, genericKey); | ||
} | ||
return this._keyIsInvalid(key, genericKey); | ||
} | ||
}, { | ||
key: 'keyErrorMessage', | ||
value: function keyErrorMessage(key) { | ||
var genericKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _mongoObject2.default.makeKeyGeneric(key); | ||
keyErrorMessage(key, genericKey = _mongoObject.default.makeKeyGeneric(key)) { | ||
if (this._deps.hasOwnProperty(genericKey)) this._deps[genericKey].depend(); | ||
const errorObj = this.getErrorForKey(key, genericKey); | ||
if (!errorObj) return ''; | ||
return this._simpleSchema.messageForError(errorObj); | ||
} | ||
/** | ||
* Validates the object against the simple schema and sets a reactive array of error objects | ||
*/ | ||
if (this._deps.hasOwnProperty(genericKey)) this._deps[genericKey].depend(); | ||
var errorObj = this.getErrorForKey(key, genericKey); | ||
if (!errorObj) return ''; | ||
validate(obj, { | ||
extendedCustomContext = {}, | ||
ignore: ignoreTypes = [], | ||
keys: keysToValidate, | ||
modifier: isModifier = false, | ||
mongoObject, | ||
upsert: isUpsert = false | ||
} = {}) { | ||
const validationErrors = (0, _doValidation.default)({ | ||
extendedCustomContext, | ||
ignoreTypes, | ||
isModifier, | ||
isUpsert, | ||
keysToValidate, | ||
mongoObject, | ||
obj, | ||
schema: this._simpleSchema, | ||
validationContext: this | ||
}); | ||
return this._simpleSchema.messageForError(errorObj); | ||
if (keysToValidate) { | ||
// We have only revalidated the listed keys, so if there | ||
// are any other existing errors that are NOT in the keys list, | ||
// we should keep these errors. | ||
for (const error of this._validationErrors) { | ||
const wasValidated = keysToValidate.some(key => key === error.name || error.name.startsWith(`${key}.`)); | ||
if (!wasValidated) validationErrors.push(error); | ||
} | ||
} | ||
/** | ||
* Validates the object against the simple schema and sets a reactive array of error objects | ||
*/ | ||
this.setValidationErrors(validationErrors); // Return true if it was valid; otherwise, return false | ||
}, { | ||
key: 'validate', | ||
value: function validate(obj) { | ||
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, | ||
_ref$extendedCustomCo = _ref.extendedCustomContext, | ||
extendedCustomContext = _ref$extendedCustomCo === undefined ? {} : _ref$extendedCustomCo, | ||
_ref$ignore = _ref.ignore, | ||
ignoreTypes = _ref$ignore === undefined ? [] : _ref$ignore, | ||
keysToValidate = _ref.keys, | ||
_ref$modifier = _ref.modifier, | ||
isModifier = _ref$modifier === undefined ? false : _ref$modifier, | ||
mongoObject = _ref.mongoObject, | ||
_ref$upsert = _ref.upsert, | ||
isUpsert = _ref$upsert === undefined ? false : _ref$upsert; | ||
return !validationErrors.length; | ||
} | ||
var validationErrors = (0, _doValidation2.default)({ | ||
extendedCustomContext: extendedCustomContext, | ||
ignoreTypes: ignoreTypes, | ||
isModifier: isModifier, | ||
isUpsert: isUpsert, | ||
keysToValidate: keysToValidate, | ||
mongoObject: mongoObject, | ||
obj: obj, | ||
schema: this._simpleSchema, | ||
validationContext: this | ||
}); | ||
isValid() { | ||
this._depsAny && this._depsAny.depend(); | ||
return this._validationErrors.length === 0; | ||
} | ||
if (keysToValidate) { | ||
// We have only revalidated the listed keys, so if there | ||
// are any other existing errors that are NOT in the keys list, | ||
// we should keep these errors. | ||
var _iteratorNormalCompletion = true; | ||
var _didIteratorError = false; | ||
var _iteratorError = undefined; | ||
validationErrors() { | ||
this._depsAny && this._depsAny.depend(); | ||
return this._validationErrors; | ||
} | ||
try { | ||
var _loop = function _loop() { | ||
var error = _step.value; | ||
clean(...args) { | ||
return this._simpleSchema.clean(...args); | ||
} | ||
var wasValidated = keysToValidate.some(function (key) { | ||
return key === error.name || error.name.startsWith(key + '.'); | ||
}); | ||
if (!wasValidated) validationErrors.push(error); | ||
}; | ||
} | ||
for (var _iterator = this._validationErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
_loop(); | ||
} | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
} finally { | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return) { | ||
_iterator.return(); | ||
} | ||
} finally { | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
} | ||
} | ||
this.setValidationErrors(validationErrors); | ||
// Return true if it was valid; otherwise, return false | ||
return !validationErrors.length; | ||
} | ||
}, { | ||
key: 'isValid', | ||
value: function isValid() { | ||
this._depsAny && this._depsAny.depend(); | ||
return this._validationErrors.length === 0; | ||
} | ||
}, { | ||
key: 'validationErrors', | ||
value: function validationErrors() { | ||
this._depsAny && this._depsAny.depend(); | ||
return this._validationErrors; | ||
} | ||
}, { | ||
key: 'clean', | ||
value: function clean() { | ||
var _simpleSchema; | ||
return (_simpleSchema = this._simpleSchema).clean.apply(_simpleSchema, arguments); | ||
} | ||
}]); | ||
return ValidationContext; | ||
}(); | ||
exports.default = ValidationContext; | ||
exports.default = ValidationContext; | ||
module.exports = exports.default; | ||
module.exports.default = exports.default; |
{ | ||
"name": "simpl-schema", | ||
"version": "1.5.5", | ||
"version": "1.5.6", | ||
"description": "A schema validation package that supports direct validation of MongoDB update modifier objects.", | ||
@@ -27,3 +27,3 @@ "author": "Eric Dobbertin <aldeed@gmail.com>", | ||
"prepublishOnly": "npm run lintAndTest && npm run copyFiles && npm run build", | ||
"test": "mocha --compilers js:babel-core/register --recursive \"lib/**/*.tests.js\"", | ||
"test": "mocha --require @babel/register --recursive \"lib/**/*.tests.js\"", | ||
"test:watch": "npm test -- --watch" | ||
@@ -33,3 +33,3 @@ }, | ||
"clone": "^2.1.1", | ||
"extend": "^3.0.1", | ||
"extend": "^3.0.2", | ||
"lodash.every": "^4.6.0", | ||
@@ -49,9 +49,12 @@ "lodash.find": "^4.6.0", | ||
"devDependencies": { | ||
"babel-cli": "^6.10.1", | ||
"babel-core": "^6.26.3", | ||
"babel-eslint": "^6.0.4", | ||
"babel-polyfill": "^6.26.0", | ||
"babel-preset-es2015": "^6.9.0", | ||
"babel-preset-react": "^6.5.0", | ||
"babel-preset-stage-0": "^6.5.0", | ||
"@babel/cli": "7.0.0", | ||
"@babel/core": "7.0.0", | ||
"@babel/plugin-proposal-class-properties": "7.3.0", | ||
"@babel/plugin-proposal-object-rest-spread": "7.0.0", | ||
"@babel/polyfill": "7.2.5", | ||
"@babel/preset-env": "7.0.0", | ||
"@babel/register": "7.0.0", | ||
"babel-core": "7.0.0-bridge.0", | ||
"babel-eslint": "8.2.3", | ||
"babel-plugin-add-module-exports": "^1.0.2", | ||
"eslint": "^2.13.0", | ||
@@ -67,4 +70,24 @@ "eslint-config-airbnb": "^9.0.1", | ||
"presets": [ | ||
"es2015", | ||
"stage-0" | ||
[ | ||
"@babel/env", | ||
{ | ||
"targets": { | ||
"node": "8" | ||
} | ||
} | ||
] | ||
], | ||
"plugins": [ | ||
[ | ||
"@babel/plugin-proposal-class-properties", | ||
{ | ||
"loose": false | ||
} | ||
], | ||
[ | ||
"add-module-exports", | ||
{ | ||
"addDefaultProperty": true | ||
} | ||
] | ||
] | ||
@@ -71,0 +94,0 @@ }, |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
440934
71
12183
17
1
Updatedextend@^3.0.2