superstruct
Advanced tools
Comparing version 0.3.0 to 0.3.1
@@ -10,2 +10,14 @@ | ||
### `0.3.0` — November 30, 2017 | ||
###### BREAKING | ||
- **The `validate()` method now returns `[ error, result ]`.** Previously it only had a single return value, which necessitated extra type checking to see if the value was an error or a result. Now you can just destructure the array to get either return value, for easier coding. | ||
- **Errors have been simplified, removing "codes".** Previously there were multiple types of errors that were thrown and you could differentiate between them with the `error.code` property. But the other properties of the error already let you infer the code, so having multiple types of errors made for a larger API surface without much benefit. | ||
--- | ||
### `0.2.0` — November 30, 2017 | ||
@@ -12,0 +24,0 @@ |
@@ -57,3 +57,3 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Superstruct = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ | ||
},{"for-own":3,"is-plain-object":5,"kind-of":7,"shallow-clone":9}],2:[function(require,module,exports){ | ||
},{"for-own":3,"is-plain-object":6,"kind-of":8,"shallow-clone":10}],2:[function(require,module,exports){ | ||
/*! | ||
@@ -98,2 +98,55 @@ * for-in <https://github.com/jonschlinkert/for-in> | ||
},{"for-in":2}],4:[function(require,module,exports){ | ||
/** | ||
* Copyright 2013-2015, Facebook, Inc. | ||
* All rights reserved. | ||
* | ||
* This source code is licensed under the BSD-style license found in the | ||
* LICENSE file in the root directory of this source tree. An additional grant | ||
* of patent rights can be found in the PATENTS file in the same directory. | ||
*/ | ||
'use strict'; | ||
/** | ||
* Use invariant() to assert state which your program assumes to be true. | ||
* | ||
* Provide sprintf-style format (only %s is supported) and arguments | ||
* to provide information about what broke and what you were | ||
* expecting. | ||
* | ||
* The invariant message will be stripped in production, but the invariant | ||
* will remain to ensure logic does not differ in production. | ||
*/ | ||
var invariant = function(condition, format, a, b, c, d, e, f) { | ||
if ("production" !== 'production') { | ||
if (format === undefined) { | ||
throw new Error('invariant requires an error message argument'); | ||
} | ||
} | ||
if (!condition) { | ||
var error; | ||
if (format === undefined) { | ||
error = new Error( | ||
'Minified exception occurred; use the non-minified dev environment ' + | ||
'for the full error message and additional helpful warnings.' | ||
); | ||
} else { | ||
var args = [a, b, c, d, e, f]; | ||
var argIndex = 0; | ||
error = new Error( | ||
format.replace(/%s/g, function() { return args[argIndex++]; }) | ||
); | ||
error.name = 'Invariant Violation'; | ||
} | ||
error.framesToPop = 1; // we don't care about invariant's own frame | ||
throw error; | ||
} | ||
}; | ||
module.exports = invariant; | ||
},{}],5:[function(require,module,exports){ | ||
/*! | ||
@@ -114,3 +167,3 @@ * is-extendable <https://github.com/jonschlinkert/is-extendable> | ||
},{"is-plain-object":5}],5:[function(require,module,exports){ | ||
},{"is-plain-object":6}],6:[function(require,module,exports){ | ||
/*! | ||
@@ -154,3 +207,3 @@ * is-plain-object <https://github.com/jonschlinkert/is-plain-object> | ||
},{"isobject":6}],6:[function(require,module,exports){ | ||
},{"isobject":7}],7:[function(require,module,exports){ | ||
/*! | ||
@@ -169,3 +222,3 @@ * isobject <https://github.com/jonschlinkert/isobject> | ||
},{}],7:[function(require,module,exports){ | ||
},{}],8:[function(require,module,exports){ | ||
var toString = Object.prototype.toString; | ||
@@ -301,3 +354,3 @@ | ||
},{}],8:[function(require,module,exports){ | ||
},{}],9:[function(require,module,exports){ | ||
'use strict'; | ||
@@ -339,3 +392,3 @@ | ||
},{"for-in":2,"is-extendable":4}],9:[function(require,module,exports){ | ||
},{"for-in":2,"is-extendable":5}],10:[function(require,module,exports){ | ||
/*! | ||
@@ -407,3 +460,3 @@ * shallow-clone <https://github.com/jonschlinkert/shallow-clone> | ||
},{"is-extendable":4,"kind-of":7,"mixin-object":8}],10:[function(require,module,exports){ | ||
},{"is-extendable":5,"kind-of":8,"mixin-object":9}],11:[function(require,module,exports){ | ||
'use strict'; | ||
@@ -415,40 +468,33 @@ | ||
var _kindOf = require('kind-of'); | ||
var _kindOf2 = _interopRequireDefault(_kindOf); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
* Type strings. | ||
* Define a struct error. | ||
* | ||
* @type {Array} | ||
* @type {StructError} | ||
*/ | ||
const TYPES = ['arguments', 'array', 'boolean', 'buffer', 'date', 'float32array', 'float64array', 'function', 'generatorfunction', 'int16array', 'int32array', 'int8array', 'map', 'null', 'number', 'object', 'regexp', 'set', 'string', 'symbol', 'uint16array', 'uint32array', 'uint8array', 'uint8clampedarray', 'undefined', 'weakmap', 'weakset']; | ||
class StructError extends TypeError { | ||
/** | ||
* Default types. | ||
* | ||
* @type {Object} | ||
*/ | ||
constructor(attrs) { | ||
const { data, value, type, path = [] } = attrs; | ||
const message = `Expected a value of type "${type}" ${path.length ? `for \`${path.join('.')}\`` : ''} but received \`${value}\`.`; | ||
super(message); | ||
this.data = data; | ||
this.path = path; | ||
this.value = value; | ||
this.type = type; | ||
this.errors = [this]; | ||
Error.captureStackTrace(this, this.constructor); | ||
} | ||
const DEFAULT_TYPES = { | ||
any: value => value !== undefined, | ||
error: value => Object.prototype.toString.call(value) === '[object Error]' | ||
}; | ||
} | ||
TYPES.forEach(type => { | ||
DEFAULT_TYPES[type] = value => (0, _kindOf2.default)(value) === type; | ||
}); | ||
/** | ||
* Export. | ||
* | ||
* @type {Object} | ||
* @type {StructError} | ||
*/ | ||
exports.default = DEFAULT_TYPES; | ||
exports.default = StructError; | ||
},{"kind-of":7}],11:[function(require,module,exports){ | ||
},{}],12:[function(require,module,exports){ | ||
'use strict'; | ||
@@ -461,5 +507,5 @@ | ||
var _structError = require('./struct-error'); | ||
var _error = require('./error'); | ||
var _structError2 = _interopRequireDefault(_structError); | ||
var _error2 = _interopRequireDefault(_error); | ||
@@ -488,5 +534,5 @@ var _superstruct = require('./superstruct'); | ||
exports.superstruct = _superstruct2.default; | ||
exports.StructError = _structError2.default; | ||
exports.StructError = _error2.default; | ||
},{"./struct-error":12,"./superstruct":13}],12:[function(require,module,exports){ | ||
},{"./error":11,"./superstruct":14}],13:[function(require,module,exports){ | ||
'use strict'; | ||
@@ -498,41 +544,2 @@ | ||
/** | ||
* Define a struct error. | ||
* | ||
* @type {StructError} | ||
*/ | ||
class StructError extends TypeError { | ||
constructor(attrs) { | ||
const { data, path, value, type } = attrs; | ||
const message = `Expected a value of type "${type}" ${path.length ? `for \`${path.join('.')}\`` : ''} but received \`${value}\`.`; | ||
super(message); | ||
this.data = data; | ||
this.path = path; | ||
this.value = value; | ||
this.type = type; | ||
this.errors = [this]; | ||
Error.captureStackTrace(this, this.constructor); | ||
} | ||
} | ||
/** | ||
* Export. | ||
* | ||
* @type {StructError} | ||
*/ | ||
exports.default = StructError; | ||
},{}],13:[function(require,module,exports){ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
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 _cloneDeep = require('clone-deep'); | ||
@@ -546,9 +553,9 @@ | ||
var _defaultTypes = require('./default-types'); | ||
var _invariant = require('invariant'); | ||
var _defaultTypes2 = _interopRequireDefault(_defaultTypes); | ||
var _invariant2 = _interopRequireDefault(_invariant); | ||
var _structError = require('./struct-error'); | ||
var _error = require('./error'); | ||
var _structError2 = _interopRequireDefault(_structError); | ||
var _error2 = _interopRequireDefault(_error); | ||
@@ -558,160 +565,93 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
* A private string to identify structs by. | ||
* Schema. | ||
* | ||
* @type {String} | ||
* @type {Schema} | ||
*/ | ||
const IS_STRUCT = '@@__STRUCT__@@'; | ||
class Schema { | ||
/** | ||
* Public properties for struct functions. | ||
* | ||
* @type {Array} | ||
*/ | ||
/** | ||
* Create a schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
const STRUCT_PROPERTIES = ['schema', 'defaults', 'options']; | ||
constructor(schema, defaults, options = {}) { | ||
this.schema = schema; | ||
this.defaults = defaults; | ||
this.options = options; | ||
} | ||
/** | ||
* Public methods for struct functions. | ||
* | ||
* @type {Array} | ||
*/ | ||
/** | ||
* Assert that a `value` is valid, throwing if not. | ||
* | ||
* @param {Any} value | ||
* @return {Any|StructError} | ||
*/ | ||
const STRUCT_METHODS = ['assert', 'default', 'test', 'validate']; | ||
assert(value) { | ||
const [error, result] = this.validate(value); | ||
if (error) throw error; | ||
return result; | ||
} | ||
/** | ||
* The diffrent Kinds of struct schemas. | ||
* | ||
* @type {Array} | ||
*/ | ||
/** | ||
* Get the defaulted value, given an initial `value`. | ||
* | ||
* @param {Any} value | ||
* @return {Any} | ||
*/ | ||
const STRUCT_KINDS = ['scalar', 'function', 'object', 'list']; | ||
default(value) { | ||
if (value !== undefined) return value; | ||
const { defaults } = this; | ||
return typeof defaults === 'function' ? defaults() : (0, _cloneDeep2.default)(defaults); | ||
} | ||
/** | ||
* Convenience flags for the struct factory. | ||
* | ||
* @type {Array} | ||
*/ | ||
const STRUCT_FLAGS = ['required']; | ||
/** | ||
* Create a struct factory with a `config`. | ||
* | ||
* @param {Object} config | ||
* @return {Function} | ||
*/ | ||
function superstruct(config = {}) { | ||
const TYPES = _extends({}, _defaultTypes2.default, config.types || {}); | ||
/** | ||
* Base schema. | ||
* Test that a `value` is valid. | ||
* | ||
* @type {Schema} | ||
* @param {Any} value | ||
* @return {Boolean} | ||
*/ | ||
class Schema { | ||
/** | ||
* Create a schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
constructor(schema, defaults, options = {}) { | ||
this.schema = schema; | ||
this.defaults = defaults; | ||
this.options = options; | ||
} | ||
/** | ||
* Assert that a `value` is valid, throwing if not. | ||
* | ||
* @param {Any} value | ||
* @return {Any|StructError} | ||
*/ | ||
assert(value) { | ||
const [error, result] = this.validate(value); | ||
if (error) throw error; | ||
return result; | ||
} | ||
/** | ||
* Get the defaulted value, given an initial `value`. | ||
* | ||
* @param {Any} value | ||
* @return {Any} | ||
*/ | ||
default(value) { | ||
if (value !== undefined) return value; | ||
const { defaults } = this; | ||
return typeof defaults === 'function' ? defaults() : (0, _cloneDeep2.default)(defaults); | ||
} | ||
/** | ||
* Test that a `value` is valid. | ||
* | ||
* @param {Any} value | ||
* @return {Boolean} | ||
*/ | ||
test(value) { | ||
const [error] = this.validate(value); | ||
return !error; | ||
} | ||
/** | ||
* Validate a `value`, returning an error or the value with defaults. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
value = this.default(value); | ||
return [undefined, value]; | ||
} | ||
test(value) { | ||
const [error] = this.validate(value); | ||
return !error; | ||
} | ||
/** | ||
* Function schema. | ||
* Validate a `value`, returning an error or the value with defaults. | ||
* | ||
* @type {FunctionSchema} | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
class FunctionSchema extends Schema { | ||
validate(value) { | ||
value = this.default(value); | ||
return this.check(value); | ||
} | ||
/** | ||
* Create a function schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
} | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
this.type = '<function>'; | ||
} | ||
/** | ||
* Function schema. | ||
* | ||
* @type {FunctionSchema} | ||
*/ | ||
/** | ||
* Validate a `value`, returning an error or the value with defaults. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
class FunctionSchema extends Schema { | ||
validate(value) { | ||
const { options, type, schema } = this; | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
value = this.default(value); | ||
const type = '<function>'; | ||
this.kind = 'Function'; | ||
this.type = type; | ||
this.check = value => { | ||
if (options.required && value === undefined || value !== undefined && !schema(value)) { | ||
const error = new _structError2.default({ type, value, data: value, path: [] }); | ||
const error = new _error2.default({ type, value, data: value }); | ||
return [error]; | ||
@@ -721,53 +661,34 @@ } | ||
return [undefined, value]; | ||
} | ||
}; | ||
} | ||
/** | ||
* Scalar schema. | ||
* | ||
* @type {ScalarSchema} | ||
*/ | ||
} | ||
class ScalarSchema extends Schema { | ||
/** | ||
* Scalar schema. | ||
* | ||
* @type {ScalarSchema} | ||
*/ | ||
/** | ||
* Create a scalar schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
class ScalarSchema extends Schema { | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
const required = !schema.endsWith('?'); | ||
const type = required ? schema : schema.slice(0, -1); | ||
const types = type.split(/\s*\|\s*/g); | ||
const validators = types.map(t => { | ||
const fn = TYPES[t]; | ||
if (typeof fn === 'function') return fn; | ||
throw new Error(`No struct validator function found for type "${t}".`); | ||
}); | ||
const { types } = options; | ||
const required = !schema.endsWith('?'); | ||
const type = required ? schema : schema.slice(0, -1); | ||
const ts = type.split(/\s*\|\s*/g); | ||
const validators = ts.map(t => { | ||
const fn = types[t]; | ||
!(typeof fn === 'function') ? "production" !== 'production' ? (0, _invariant2.default)(false, `No struct validator function found for type "${t}".`) : (0, _invariant2.default)(false) : void 0; | ||
return fn; | ||
}); | ||
this.options.required = required; | ||
this.type = type; | ||
this.validators = validators; | ||
} | ||
/** | ||
* Validate a `value`, returning an error or the value with defaults. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
const { options, type, validators } = this; | ||
value = this.default(value); | ||
this.kind = 'Scalar'; | ||
this.type = type; | ||
this.options.required = required; | ||
this.check = value => { | ||
if (options.required && value === undefined || value !== undefined && !validators.some(fn => fn(value))) { | ||
const error = new _structError2.default({ type, value, data: value, path: [] }); | ||
const error = new _error2.default({ type, value, data: value }); | ||
return [error]; | ||
@@ -777,49 +698,27 @@ } | ||
return [undefined, value]; | ||
} | ||
}; | ||
} | ||
/** | ||
* List schema. | ||
* | ||
* @type {ListSchema} | ||
*/ | ||
} | ||
class ListSchema extends Schema { | ||
/** | ||
* List schema. | ||
* | ||
* @type {ListSchema} | ||
*/ | ||
/** | ||
* Create a list schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
class ListSchema extends Schema { | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
if (schema.length !== 1) { | ||
throw new Error(`List structs must be defined as an array with a single element, but you passed ${schema.length} elements.`); | ||
} | ||
!(schema.length === 1) ? "production" !== 'production' ? (0, _invariant2.default)(false, `List structs must be defined as an array with a single element, but you passed ${schema.length} elements.`) : (0, _invariant2.default)(false) : void 0; | ||
const type = options.required ? 'array' : 'array?'; | ||
const valueStruct = struct(type); | ||
const elementStruct = struct(schema[0]); | ||
const { struct } = options; | ||
const type = options.required ? 'array' : 'array?'; | ||
const valueStruct = struct(type); | ||
const elementStruct = struct(schema[0]); | ||
this.type = type; | ||
this.valueStruct = valueStruct; | ||
this.elementStruct = elementStruct; | ||
} | ||
/** | ||
* Validate a list `value`. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
const { options, elementStruct, valueStruct } = this; | ||
value = this.default(value); | ||
this.type = type; | ||
this.check = value => { | ||
const [error] = valueStruct.validate(value); | ||
@@ -854,71 +753,45 @@ if (error) return [error]; | ||
return [undefined, ret]; | ||
} | ||
}; | ||
} | ||
} | ||
/** | ||
* Object schema. | ||
* | ||
* @type {ObjectSchema} | ||
*/ | ||
class ObjectSchema extends Schema { | ||
/** | ||
* Object schema. | ||
* Create an object schema with `schema`, `defaults` and `options`. | ||
* | ||
* @type {ObjectSchema} | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
class ObjectSchema extends Schema { | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
/** | ||
* Create an object schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
!((0, _kindOf2.default)(schema) === 'object') ? "production" !== 'production' ? (0, _invariant2.default)(false, `Object structs must be defined as an object, but you passed: ${schema}`) : (0, _invariant2.default)(false) : void 0; | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
const { struct } = options; | ||
const propertyStructs = {}; | ||
const propertyStructs = {}; | ||
for (const key in schema) { | ||
const s = struct(schema[key]); | ||
propertyStructs[key] = s; | ||
for (const key in schema) { | ||
const s = struct(schema[key]); | ||
propertyStructs[key] = s; | ||
if (s.options.required) { | ||
this.options.required = true; | ||
} | ||
if (s.options.required) { | ||
this.options.required = true; | ||
} | ||
const type = this.options.required ? 'object' : 'object?'; | ||
const valueStruct = struct(type); | ||
this.type = type; | ||
this.valueStruct = valueStruct; | ||
this.propertyStructs = propertyStructs; | ||
} | ||
/** | ||
* Get the defaulted value, given an initial `value`. | ||
* | ||
* @param {Object|Void} value | ||
* @return {Object|Void} | ||
*/ | ||
const type = this.options.required ? 'object' : 'object?'; | ||
const valueStruct = struct(type); | ||
default(value) { | ||
const { defaults } = this; | ||
if (value !== undefined || defaults === undefined) return value; | ||
const defs = typeof defaults === 'function' ? defaults() : (0, _cloneDeep2.default)(defaults); | ||
const ret = Object.assign({}, value, defs); | ||
return ret; | ||
} | ||
/** | ||
* Validate a list `value`. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
const { options, propertyStructs, valueStruct } = this; | ||
value = this.default(value); | ||
this.type = type; | ||
this.check = value => { | ||
const [error] = valueStruct.validate(value); | ||
@@ -940,6 +813,6 @@ if (error) return [error]; | ||
const v = value[k]; | ||
const s = this.propertyStructs[k]; | ||
const s = propertyStructs[k]; | ||
if (!s) { | ||
const e = new _structError2.default({ data: value, path: [k], value: v }); | ||
const e = new _error2.default({ data: value, path: [k], value: v }); | ||
errors.push(e); | ||
@@ -971,6 +844,96 @@ return; | ||
return [undefined, ret]; | ||
} | ||
}; | ||
} | ||
/** | ||
* Get the defaulted value, given an initial `value`. | ||
* | ||
* @param {Object|Void} value | ||
* @return {Object|Void} | ||
*/ | ||
default(value) { | ||
const { defaults } = this; | ||
if (value !== undefined || defaults === undefined) return value; | ||
const defs = typeof defaults === 'function' ? defaults() : (0, _cloneDeep2.default)(defaults); | ||
const ret = Object.assign({}, value, defs); | ||
return ret; | ||
} | ||
} | ||
/** | ||
* Export. | ||
* | ||
* @type {Function} | ||
*/ | ||
exports.default = { | ||
Function: FunctionSchema, | ||
List: ListSchema, | ||
Object: ObjectSchema, | ||
Scalar: ScalarSchema | ||
}; | ||
},{"./error":11,"clone-deep":1,"invariant":4,"kind-of":8}],14:[function(require,module,exports){ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
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 _kindOf = require('kind-of'); | ||
var _kindOf2 = _interopRequireDefault(_kindOf); | ||
var _invariant = require('invariant'); | ||
var _invariant2 = _interopRequireDefault(_invariant); | ||
var _types = require('./types'); | ||
var _types2 = _interopRequireDefault(_types); | ||
var _schemas = require('./schemas'); | ||
var _schemas2 = _interopRequireDefault(_schemas); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
* A private string to identify structs by. | ||
* | ||
* @type {String} | ||
*/ | ||
const IS_STRUCT = '@@__STRUCT__@@'; | ||
/** | ||
* Public properties for struct functions. | ||
* | ||
* @type {Array} | ||
*/ | ||
const STRUCT_PROPERTIES = ['kind', 'type', 'schema', 'defaults', 'options']; | ||
/** | ||
* Public methods for struct functions. | ||
* | ||
* @type {Array} | ||
*/ | ||
const STRUCT_METHODS = ['assert', 'default', 'test', 'validate']; | ||
/** | ||
* Create a struct factory with a `config`. | ||
* | ||
* @param {Object} config | ||
* @return {Function} | ||
*/ | ||
function superstruct(config = {}) { | ||
const types = _extends({}, _types2.default, config.types || {}); | ||
/** | ||
@@ -986,35 +949,19 @@ * Create a `kind` struct with schema `definition`, `defaults` and `options`. | ||
function createStruct(kind, definition, defaults, options) { | ||
function createStruct(kind, definition, defaults, options = {}) { | ||
if (isStruct(definition)) { | ||
return definition; | ||
definition = definition.schema; | ||
} | ||
const args = [definition, defaults, options]; | ||
let schema; | ||
const Schema = _schemas2.default[kind]; | ||
const schema = new Schema(definition, defaults, _extends({}, options, { types, struct })); | ||
if (kind === 'function') { | ||
schema = new FunctionSchema(...args); | ||
} else if (kind === 'scalar') { | ||
schema = new ScalarSchema(...args); | ||
} else if (kind === 'list') { | ||
schema = new ListSchema(...args); | ||
} else if (kind === 'object') { | ||
schema = new ObjectSchema(...args); | ||
} else { | ||
throw new Error(`Unrecognized struct kind: ${kind}`); | ||
} | ||
// Define the struct creator function. | ||
function Struct(data) { | ||
if (this instanceof Struct) { | ||
throw new Error('The `Struct` creation function should not be used with the `new` keyword.'); | ||
} | ||
!!(this instanceof Struct) ? "production" !== 'production' ? (0, _invariant2.default)(false, 'The `Struct` creation function should not be used with the `new` keyword.') : (0, _invariant2.default)(false) : void 0; | ||
return schema.assert(data); | ||
} | ||
// Add a private property for identifying struct functions. | ||
Struct[IS_STRUCT] = true; | ||
Struct.kind = kind; | ||
// Mix in the public struct properties. | ||
STRUCT_PROPERTIES.forEach(prop => { | ||
@@ -1024,3 +971,2 @@ Struct[prop] = schema[prop]; | ||
// Mix in the public struct methods. | ||
STRUCT_METHODS.forEach(method => { | ||
@@ -1043,6 +989,3 @@ Struct[method] = (...a) => schema[method](...a); | ||
function struct(definition, defaults, options) { | ||
if (isStruct(definition)) { | ||
return definition; | ||
} | ||
if (isStruct(definition)) return definition; | ||
const kind = getKind(definition); | ||
@@ -1054,11 +997,10 @@ const Struct = createStruct(kind, definition, defaults, options); | ||
// Mix in a factory for each kind of struct. | ||
STRUCT_KINDS.forEach(kind => { | ||
struct[kind] = (...args) => createStruct(kind, ...args); | ||
Object.keys(_schemas2.default).forEach(kind => { | ||
const lower = kind.toLowerCase(); | ||
struct[lower] = (...args) => createStruct(kind, ...args); | ||
}); | ||
// Mix in the convenience properties for option flags. | ||
STRUCT_FLAGS.forEach(flag => { | ||
Object.defineProperty(struct, flag, { | ||
get: () => (s, d, o = {}) => struct(s, d, _extends({}, o, { [flag]: true })) | ||
}); | ||
// Mix in the `required` convenience flag. | ||
Object.defineProperty(struct, 'required', { | ||
get: () => (s, d, o = {}) => struct(s, d, _extends({}, o, { required: true })) | ||
}); | ||
@@ -1094,12 +1036,12 @@ | ||
case 'function': | ||
return 'function'; | ||
return 'Function'; | ||
case 'string': | ||
return 'scalar'; | ||
return 'Scalar'; | ||
case 'array': | ||
return 'list'; | ||
return 'List'; | ||
case 'object': | ||
return 'object'; | ||
return 'Object'; | ||
default: | ||
{ | ||
throw new Error(`A struct schema definition must be a string, array or object, but you passed: ${definition}`); | ||
!false ? "production" !== 'production' ? (0, _invariant2.default)(false, `A struct schema definition must be a string, array or object, but you passed: ${definition}`) : (0, _invariant2.default)(false) : void 0; | ||
} | ||
@@ -1117,3 +1059,47 @@ } | ||
},{"./default-types":10,"./struct-error":12,"clone-deep":1,"kind-of":7}]},{},[11])(11) | ||
},{"./schemas":13,"./types":15,"invariant":4,"kind-of":8}],15:[function(require,module,exports){ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
var _kindOf = require('kind-of'); | ||
var _kindOf2 = _interopRequireDefault(_kindOf); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
/** | ||
* The types that `kind-of` supports.. | ||
* | ||
* @type {Array} | ||
*/ | ||
const KIND_OF_TYPES = ['arguments', 'array', 'boolean', 'buffer', 'date', 'float32array', 'float64array', 'function', 'generatorfunction', 'int16array', 'int32array', 'int8array', 'map', 'null', 'number', 'object', 'regexp', 'set', 'string', 'symbol', 'uint16array', 'uint32array', 'uint8array', 'uint8clampedarray', 'undefined', 'weakmap', 'weakset']; | ||
/** | ||
* The default types that Superstruct ships with. | ||
* | ||
* @type {Object} | ||
*/ | ||
const TYPES = { | ||
any: value => value !== undefined, | ||
error: value => Object.prototype.toString.call(value) === '[object Error]' | ||
}; | ||
KIND_OF_TYPES.forEach(type => { | ||
TYPES[type] = value => (0, _kindOf2.default)(value) === type; | ||
}); | ||
/** | ||
* Export. | ||
* | ||
* @type {Object} | ||
*/ | ||
exports.default = TYPES; | ||
},{"kind-of":8}]},{},[12])(12) | ||
}); |
@@ -1,1 +0,1 @@ | ||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Superstruct=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";var isObject=require("is-plain-object");var clone=require("shallow-clone");var typeOf=require("kind-of");var forOwn=require("for-own");function cloneDeep(val,instanceClone){switch(typeOf(val)){case"object":return cloneObjectDeep(val,instanceClone);case"array":return cloneArrayDeep(val,instanceClone);default:{return clone(val)}}}function cloneObjectDeep(obj,instanceClone){if(isObject(obj)||instanceClone===true&&typeOf(obj)==="object"){var res={};forOwn(obj,function(val,key){this[key]=cloneDeep(val,instanceClone)},res);return res}if(typeof instanceClone==="function"){return instanceClone(obj)}return obj}function cloneArrayDeep(arr,instanceClone){var res=[];for(var i=0;i<arr.length;i++){res[i]=cloneDeep(arr[i],instanceClone)}return res}module.exports=cloneDeep},{"for-own":3,"is-plain-object":5,"kind-of":7,"shallow-clone":9}],2:[function(require,module,exports){"use strict";module.exports=function forIn(obj,fn,thisArg){for(var key in obj){if(fn.call(thisArg,obj[key],key,obj)===false){break}}}},{}],3:[function(require,module,exports){"use strict";var forIn=require("for-in");var hasOwn=Object.prototype.hasOwnProperty;module.exports=function forOwn(obj,fn,thisArg){forIn(obj,function(val,key){if(hasOwn.call(obj,key)){return fn.call(thisArg,obj[key],key,obj)}})}},{"for-in":2}],4:[function(require,module,exports){"use strict";var isPlainObject=require("is-plain-object");module.exports=function isExtendable(val){return isPlainObject(val)||typeof val==="function"||Array.isArray(val)}},{"is-plain-object":5}],5:[function(require,module,exports){"use strict";var isObject=require("isobject");function isObjectObject(o){return isObject(o)===true&&Object.prototype.toString.call(o)==="[object Object]"}module.exports=function isPlainObject(o){var ctor,prot;if(isObjectObject(o)===false)return false;ctor=o.constructor;if(typeof ctor!=="function")return false;prot=ctor.prototype;if(isObjectObject(prot)===false)return false;if(prot.hasOwnProperty("isPrototypeOf")===false){return false}return true}},{isobject:6}],6:[function(require,module,exports){"use strict";module.exports=function isObject(val){return val!=null&&typeof val==="object"&&Array.isArray(val)===false}},{}],7:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function kindOf(val){if(val===void 0)return"undefined";if(val===null)return"null";var type=typeof val;if(type==="boolean")return"boolean";if(type==="string")return"string";if(type==="number")return"number";if(type==="symbol")return"symbol";if(type==="function"){return isGeneratorFn(val)?"generatorfunction":"function"}if(isArray(val))return"array";if(isBuffer(val))return"buffer";if(isArguments(val))return"arguments";if(isDate(val))return"date";if(isError(val))return"error";if(isRegexp(val))return"regexp";switch(ctorName(val)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(isGeneratorObj(val)){return"generator"}type=toString.call(val);switch(type){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return type.slice(8,-1).toLowerCase().replace(/\s/g,"")};function ctorName(val){return val.constructor?val.constructor.name:null}function isArray(val){if(Array.isArray)return Array.isArray(val);return val instanceof Array}function isError(val){return val instanceof Error||typeof val.message==="string"&&val.constructor&&typeof val.constructor.stackTraceLimit==="number"}function isDate(val){if(val instanceof Date)return true;return typeof val.toDateString==="function"&&typeof val.getDate==="function"&&typeof val.setDate==="function"}function isRegexp(val){if(val instanceof RegExp)return true;return typeof val.flags==="string"&&typeof val.ignoreCase==="boolean"&&typeof val.multiline==="boolean"&&typeof val.global==="boolean"}function isGeneratorFn(name,val){return ctorName(name)==="GeneratorFunction"}function isGeneratorObj(val){return typeof val.throw==="function"&&typeof val.return==="function"&&typeof val.next==="function"}function isArguments(val){try{if(typeof val.length==="number"&&typeof val.callee==="function"){return true}}catch(err){if(err.message.indexOf("callee")!==-1){return true}}return false}function isBuffer(val){if(val.constructor&&typeof val.constructor.isBuffer==="function"){return val.constructor.isBuffer(val)}return false}},{}],8:[function(require,module,exports){"use strict";var isObject=require("is-extendable");var forIn=require("for-in");module.exports=function mixin(target,objects){if(!isObject(target)){throw new TypeError("expected the first argument to be an object")}var len=arguments.length;var idx=0;while(++idx<len){copy(target,arguments[idx])}return target};function copy(target,obj){if(isObject(obj)){forIn(obj,function(value,key){target[key]=value})}}},{"for-in":2,"is-extendable":4}],9:[function(require,module,exports){"use strict";var isObject=require("is-extendable");var mixin=require("mixin-object");var typeOf=require("kind-of");function clone(val){var type=typeOf(val);if(clone.hasOwnProperty(type)){return clone[type](val)}return val}clone.array=function cloneArray(arr){return arr.slice()};clone.date=function cloneDate(date){return new Date(+date)};clone.object=function cloneObject(obj){if(isObject(obj)){return mixin({},obj)}else{return obj}};clone.map=function cloneMap(val){return new Map(val)};clone.regexp=function cloneRegExp(re){var flags="";flags+=re.multiline?"m":"";flags+=re.global?"g":"";flags+=re.ignorecase?"i":"";return new RegExp(re.source,flags)};clone.set=function cloneSet(val){return new Set(val)};module.exports=clone},{"is-extendable":4,"kind-of":7,"mixin-object":8}],10:[function(require,module,exports){"use strict";function _interopRequireDefault(r){return r&&r.__esModule?r:{default:r}}Object.defineProperty(exports,"__esModule",{value:!0});var _kindOf=require("kind-of"),_kindOf2=_interopRequireDefault(_kindOf);const TYPES=["arguments","array","boolean","buffer","date","float32array","float64array","function","generatorfunction","int16array","int32array","int8array","map","null","number","object","regexp","set","string","symbol","uint16array","uint32array","uint8array","uint8clampedarray","undefined","weakmap","weakset"],DEFAULT_TYPES={any:r=>void 0!==r,error:r=>"[object Error]"===Object.prototype.toString.call(r)};TYPES.forEach(r=>{DEFAULT_TYPES[r]=(e=>(0,_kindOf2.default)(e)===r)}),exports.default=DEFAULT_TYPES},{"kind-of":7}],11:[function(require,module,exports){"use strict";function _interopRequireDefault(r){return r&&r.__esModule?r:{default:r}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.StructError=exports.superstruct=exports.struct=void 0;var _structError=require("./struct-error"),_structError2=_interopRequireDefault(_structError),_superstruct=require("./superstruct"),_superstruct2=_interopRequireDefault(_superstruct);const struct=(0,_superstruct2.default)();exports.struct=struct,exports.superstruct=_superstruct2.default,exports.StructError=_structError2.default},{"./struct-error":12,"./superstruct":13}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class StructError extends TypeError{constructor(t){const{data:r,path:e,value:s,type:o}=t;super(`Expected a value of type "${o}" ${e.length?`for \`${e.join(".")}\``:""} but received \`${s}\`.`),this.data=r,this.path=e,this.value=s,this.type=o,this.errors=[this],Error.captureStackTrace(this,this.constructor)}}exports.default=StructError},{}],13:[function(require,module,exports){"use strict";function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}function superstruct(t={}){function e(t,e,r,s){function n(t){if(this instanceof n)throw new Error("The `Struct` creation function should not be used with the `new` keyword.");return d.assert(t)}if(isStruct(e))return e;const c=[e,r,s];let d;if("function"===t)d=new o(...c);else if("scalar"===t)d=new i(...c);else if("list"===t)d=new u(...c);else{if("object"!==t)throw new Error(`Unrecognized struct kind: ${t}`);d=new a(...c)}return n[IS_STRUCT]=!0,STRUCT_PROPERTIES.forEach(t=>{n[t]=d[t]}),STRUCT_METHODS.forEach(t=>{n[t]=((...e)=>d[t](...e))}),n}function r(t,r,s){if(isStruct(t))return t;return e(getKind(t),t,r,s)}const s=_extends({},_defaultTypes2.default,t.types||{});class n{constructor(t,e,r={}){this.schema=t,this.defaults=e,this.options=r}assert(t){const[e,r]=this.validate(t);if(e)throw e;return r}default(t){if(void 0!==t)return t;const{defaults:e}=this;return"function"==typeof e?e():(0,_cloneDeep2.default)(e)}test(t){const[e]=this.validate(t);return!e}validate(t){return t=this.default(t),[void 0,t]}}class o extends n{constructor(t,e,r={}){super(t,e,r),this.type="<function>"}validate(t){const{options:e,type:r,schema:s}=this;if(t=this.default(t),e.required&&void 0===t||void 0!==t&&!s(t)){return[new _structError2.default({type:r,value:t,data:t,path:[]})]}return[void 0,t]}}class i extends n{constructor(t,e,r={}){super(t,e,r);const n=!t.endsWith("?"),o=n?t:t.slice(0,-1),i=o.split(/\s*\|\s*/g).map(t=>{const e=s[t];if("function"==typeof e)return e;throw new Error(`No struct validator function found for type "${t}".`)});this.options.required=n,this.type=o,this.validators=i}validate(t){const{options:e,type:r,validators:s}=this;if(t=this.default(t),e.required&&void 0===t||void 0!==t&&!s.some(e=>e(t))){return[new _structError2.default({type:r,value:t,data:t,path:[]})]}return[void 0,t]}}class u extends n{constructor(t,e,s={}){if(super(t,e,s),1!==t.length)throw new Error(`List structs must be defined as an array with a single element, but you passed ${t.length} elements.`);const n=s.required?"array":"array?",o=r(n),i=r(t[0]);this.type=n,this.valueStruct=o,this.elementStruct=i}validate(t){const{options:e,elementStruct:r,valueStruct:s}=this;t=this.default(t);const[n]=s.validate(t);if(n)return[n];const o=[],i=[],u=!e.required&&void 0===t;if((t=u?[]:t).forEach((e,s)=>{const[n,u]=r.validate(e);if(n)return n.path=[s].concat(n.path),n.data=t,void o.push(n);i.push(u)}),o.length){const t=o[0];return t.errors=o,[t]}return[void 0,u&&!i.length?void 0:i]}}class a extends n{constructor(t,e,s={}){super(t,e,s);const n={};for(const e in t){const s=r(t[e]);n[e]=s,s.options.required&&(this.options.required=!0)}const o=this.options.required?"object":"object?",i=r(o);this.type=o,this.valueStruct=i,this.propertyStructs=n}default(t){const{defaults:e}=this;if(void 0!==t||void 0===e)return t;const r="function"==typeof e?e():(0,_cloneDeep2.default)(e);return Object.assign({},t,r)}validate(t){const{options:e,propertyStructs:r,valueStruct:s}=this;t=this.default(t);const[n]=s.validate(t);if(n)return[n];const o=[],i={},u=!e.required&&void 0===t;t=u?{}:t;const a=Object.keys(t),c=Object.keys(r),d=new Set(a.concat(c)),f=!!a.length;if(d.forEach(e=>{const r=t[e],s=this.propertyStructs[e];if(!s){const s=new _structError2.default({data:t,path:[e],value:r});return void o.push(s)}const[n,u]=s.validate(r);if(n)return n.path=[e].concat(n.path),n.data=t,void o.push(n);e in t&&(i[e]=u)}),o.length){const t=o[0];return t.errors=o,[t]}return[void 0,u&&!f?void 0:i]}}return STRUCT_KINDS.forEach(t=>{r[t]=((...r)=>e(t,...r))}),STRUCT_FLAGS.forEach(t=>{Object.defineProperty(r,t,{get:()=>(e,s,n={})=>r(e,s,_extends({},n,{[t]:!0}))})}),r}function isStruct(t){return!(!t||!t[IS_STRUCT])}function getKind(t){switch((0,_kindOf2.default)(t)){case"function":return"function";case"string":return"scalar";case"array":return"list";case"object":return"object";default:throw new Error(`A struct schema definition must be a string, array or object, but you passed: ${t}`)}}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])}return t},_cloneDeep=require("clone-deep"),_cloneDeep2=_interopRequireDefault(_cloneDeep),_kindOf=require("kind-of"),_kindOf2=_interopRequireDefault(_kindOf),_defaultTypes=require("./default-types"),_defaultTypes2=_interopRequireDefault(_defaultTypes),_structError=require("./struct-error"),_structError2=_interopRequireDefault(_structError);const IS_STRUCT="@@__STRUCT__@@",STRUCT_PROPERTIES=["schema","defaults","options"],STRUCT_METHODS=["assert","default","test","validate"],STRUCT_KINDS=["scalar","function","object","list"],STRUCT_FLAGS=["required"];exports.default=superstruct},{"./default-types":10,"./struct-error":12,"clone-deep":1,"kind-of":7}]},{},[11])(11)}); | ||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Superstruct=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";var isObject=require("is-plain-object");var clone=require("shallow-clone");var typeOf=require("kind-of");var forOwn=require("for-own");function cloneDeep(val,instanceClone){switch(typeOf(val)){case"object":return cloneObjectDeep(val,instanceClone);case"array":return cloneArrayDeep(val,instanceClone);default:{return clone(val)}}}function cloneObjectDeep(obj,instanceClone){if(isObject(obj)||instanceClone===true&&typeOf(obj)==="object"){var res={};forOwn(obj,function(val,key){this[key]=cloneDeep(val,instanceClone)},res);return res}if(typeof instanceClone==="function"){return instanceClone(obj)}return obj}function cloneArrayDeep(arr,instanceClone){var res=[];for(var i=0;i<arr.length;i++){res[i]=cloneDeep(arr[i],instanceClone)}return res}module.exports=cloneDeep},{"for-own":3,"is-plain-object":6,"kind-of":8,"shallow-clone":10}],2:[function(require,module,exports){"use strict";module.exports=function forIn(obj,fn,thisArg){for(var key in obj){if(fn.call(thisArg,obj[key],key,obj)===false){break}}}},{}],3:[function(require,module,exports){"use strict";var forIn=require("for-in");var hasOwn=Object.prototype.hasOwnProperty;module.exports=function forOwn(obj,fn,thisArg){forIn(obj,function(val,key){if(hasOwn.call(obj,key)){return fn.call(thisArg,obj[key],key,obj)}})}},{"for-in":2}],4:[function(require,module,exports){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if("production"!=="production"){if(format===undefined){throw new Error("invariant requires an error message argument")}}if(!condition){var error;if(format===undefined){error=new Error("Minified exception occurred; use the non-minified dev environment "+"for the full error message and additional helpful warnings.")}else{var args=[a,b,c,d,e,f];var argIndex=0;error=new Error(format.replace(/%s/g,function(){return args[argIndex++]}));error.name="Invariant Violation"}error.framesToPop=1;throw error}};module.exports=invariant},{}],5:[function(require,module,exports){"use strict";var isPlainObject=require("is-plain-object");module.exports=function isExtendable(val){return isPlainObject(val)||typeof val==="function"||Array.isArray(val)}},{"is-plain-object":6}],6:[function(require,module,exports){"use strict";var isObject=require("isobject");function isObjectObject(o){return isObject(o)===true&&Object.prototype.toString.call(o)==="[object Object]"}module.exports=function isPlainObject(o){var ctor,prot;if(isObjectObject(o)===false)return false;ctor=o.constructor;if(typeof ctor!=="function")return false;prot=ctor.prototype;if(isObjectObject(prot)===false)return false;if(prot.hasOwnProperty("isPrototypeOf")===false){return false}return true}},{isobject:7}],7:[function(require,module,exports){"use strict";module.exports=function isObject(val){return val!=null&&typeof val==="object"&&Array.isArray(val)===false}},{}],8:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function kindOf(val){if(val===void 0)return"undefined";if(val===null)return"null";var type=typeof val;if(type==="boolean")return"boolean";if(type==="string")return"string";if(type==="number")return"number";if(type==="symbol")return"symbol";if(type==="function"){return isGeneratorFn(val)?"generatorfunction":"function"}if(isArray(val))return"array";if(isBuffer(val))return"buffer";if(isArguments(val))return"arguments";if(isDate(val))return"date";if(isError(val))return"error";if(isRegexp(val))return"regexp";switch(ctorName(val)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(isGeneratorObj(val)){return"generator"}type=toString.call(val);switch(type){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return type.slice(8,-1).toLowerCase().replace(/\s/g,"")};function ctorName(val){return val.constructor?val.constructor.name:null}function isArray(val){if(Array.isArray)return Array.isArray(val);return val instanceof Array}function isError(val){return val instanceof Error||typeof val.message==="string"&&val.constructor&&typeof val.constructor.stackTraceLimit==="number"}function isDate(val){if(val instanceof Date)return true;return typeof val.toDateString==="function"&&typeof val.getDate==="function"&&typeof val.setDate==="function"}function isRegexp(val){if(val instanceof RegExp)return true;return typeof val.flags==="string"&&typeof val.ignoreCase==="boolean"&&typeof val.multiline==="boolean"&&typeof val.global==="boolean"}function isGeneratorFn(name,val){return ctorName(name)==="GeneratorFunction"}function isGeneratorObj(val){return typeof val.throw==="function"&&typeof val.return==="function"&&typeof val.next==="function"}function isArguments(val){try{if(typeof val.length==="number"&&typeof val.callee==="function"){return true}}catch(err){if(err.message.indexOf("callee")!==-1){return true}}return false}function isBuffer(val){if(val.constructor&&typeof val.constructor.isBuffer==="function"){return val.constructor.isBuffer(val)}return false}},{}],9:[function(require,module,exports){"use strict";var isObject=require("is-extendable");var forIn=require("for-in");module.exports=function mixin(target,objects){if(!isObject(target)){throw new TypeError("expected the first argument to be an object")}var len=arguments.length;var idx=0;while(++idx<len){copy(target,arguments[idx])}return target};function copy(target,obj){if(isObject(obj)){forIn(obj,function(value,key){target[key]=value})}}},{"for-in":2,"is-extendable":5}],10:[function(require,module,exports){"use strict";var isObject=require("is-extendable");var mixin=require("mixin-object");var typeOf=require("kind-of");function clone(val){var type=typeOf(val);if(clone.hasOwnProperty(type)){return clone[type](val)}return val}clone.array=function cloneArray(arr){return arr.slice()};clone.date=function cloneDate(date){return new Date(+date)};clone.object=function cloneObject(obj){if(isObject(obj)){return mixin({},obj)}else{return obj}};clone.map=function cloneMap(val){return new Map(val)};clone.regexp=function cloneRegExp(re){var flags="";flags+=re.multiline?"m":"";flags+=re.global?"g":"";flags+=re.ignorecase?"i":"";return new RegExp(re.source,flags)};clone.set=function cloneSet(val){return new Set(val)};module.exports=clone},{"is-extendable":5,"kind-of":8,"mixin-object":9}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class StructError extends TypeError{constructor(t){const{data:r,value:e,type:s,path:o=[]}=t;super(`Expected a value of type "${s}" ${o.length?`for \`${o.join(".")}\``:""} but received \`${e}\`.`),this.data=r,this.path=o,this.value=e,this.type=s,this.errors=[this],Error.captureStackTrace(this,this.constructor)}}exports.default=StructError},{}],12:[function(require,module,exports){"use strict";function _interopRequireDefault(r){return r&&r.__esModule?r:{default:r}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.StructError=exports.superstruct=exports.struct=void 0;var _error=require("./error"),_error2=_interopRequireDefault(_error),_superstruct=require("./superstruct"),_superstruct2=_interopRequireDefault(_superstruct);const struct=(0,_superstruct2.default)();exports.struct=struct,exports.superstruct=_superstruct2.default,exports.StructError=_error2.default},{"./error":11,"./superstruct":14}],13:[function(require,module,exports){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0});var _cloneDeep=require("clone-deep"),_cloneDeep2=_interopRequireDefault(_cloneDeep),_kindOf=require("kind-of"),_kindOf2=_interopRequireDefault(_kindOf),_invariant=require("invariant"),_invariant2=_interopRequireDefault(_invariant),_error=require("./error"),_error2=_interopRequireDefault(_error);class Schema{constructor(e,t,r={}){this.schema=e,this.defaults=t,this.options=r}assert(e){const[t,r]=this.validate(e);if(t)throw t;return r}default(e){if(void 0!==e)return e;const{defaults:t}=this;return"function"==typeof t?t():(0,_cloneDeep2.default)(t)}test(e){const[t]=this.validate(e);return!t}validate(e){return e=this.default(e),this.check(e)}}class FunctionSchema extends Schema{constructor(e,t,r={}){super(e,t,r);this.kind="Function",this.type="<function>",this.check=(t=>{if(r.required&&void 0===t||void 0!==t&&!e(t)){return[new _error2.default({type:"<function>",value:t,data:t})]}return[void 0,t]})}}class ScalarSchema extends Schema{constructor(e,t,r={}){super(e,t,r);const{types:i}=r,n=!e.endsWith("?"),o=n?e:e.slice(0,-1),a=o.split(/\s*\|\s*/g).map(e=>{const t=i[e];return"function"!=typeof t&&(0,_invariant2.default)(!1),t});this.kind="Scalar",this.type=o,this.options.required=n,this.check=(e=>{if(r.required&&void 0===e||void 0!==e&&!a.some(t=>t(e))){return[new _error2.default({type:o,value:e,data:e})]}return[void 0,e]})}}class ListSchema extends Schema{constructor(e,t,r={}){super(e,t,r),1!==e.length&&(0,_invariant2.default)(!1);const{struct:i}=r,n=r.required?"array":"array?",o=i(n),a=i(e[0]);this.type=n,this.check=(e=>{const[t]=o.validate(e);if(t)return[t];const i=[],n=[],s=!r.required&&void 0===e;if((e=s?[]:e).forEach((t,r)=>{const[o,s]=a.validate(t);if(o)return o.path=[r].concat(o.path),o.data=e,void i.push(o);n.push(s)}),i.length){const e=i[0];return e.errors=i,[e]}return[void 0,s&&!n.length?void 0:n]})}}class ObjectSchema extends Schema{constructor(e,t,r={}){super(e,t,r),"object"!==(0,_kindOf2.default)(e)&&(0,_invariant2.default)(!1);const{struct:i}=r,n={};for(const t in e){const r=i(e[t]);n[t]=r,r.options.required&&(this.options.required=!0)}const o=this.options.required?"object":"object?",a=i(o);this.type=o,this.check=(e=>{const[t]=a.validate(e);if(t)return[t];const i=[],o={},s=!r.required&&void 0===e;e=s?{}:e;const c=Object.keys(e),u=Object.keys(n),d=new Set(c.concat(u)),h=!!c.length;if(d.forEach(t=>{const r=e[t],a=n[t];if(!a){const n=new _error2.default({data:e,path:[t],value:r});return void i.push(n)}const[s,c]=a.validate(r);if(s)return s.path=[t].concat(s.path),s.data=e,void i.push(s);t in e&&(o[t]=c)}),i.length){const e=i[0];return e.errors=i,[e]}return[void 0,s&&!h?void 0:o]})}default(e){const{defaults:t}=this;if(void 0!==e||void 0===t)return e;const r="function"==typeof t?t():(0,_cloneDeep2.default)(t);return Object.assign({},e,r)}}exports.default={Function:FunctionSchema,List:ListSchema,Object:ObjectSchema,Scalar:ScalarSchema}},{"./error":11,"clone-deep":1,invariant:4,"kind-of":8}],14:[function(require,module,exports){"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function superstruct(e={}){function t(e,t,i,s={}){function a(e){return this instanceof a&&(0,_invariant2.default)(!1),u.assert(e)}isStruct(t)&&(t=t.schema);const u=new(0,_schemas2.default[e])(t,i,_extends({},s,{types:n,struct:r}));return a[IS_STRUCT]=!0,a.kind=e,STRUCT_PROPERTIES.forEach(e=>{a[e]=u[e]}),STRUCT_METHODS.forEach(e=>{a[e]=((...t)=>u[e](...t))}),a}function r(e,r,n){if(isStruct(e))return e;return t(getKind(e),e,r,n)}const n=_extends({},_types2.default,e.types||{});return Object.keys(_schemas2.default).forEach(e=>{r[e.toLowerCase()]=((...r)=>t(e,...r))}),Object.defineProperty(r,"required",{get:()=>(e,t,n={})=>r(e,t,_extends({},n,{required:!0}))}),r}function isStruct(e){return!(!e||!e[IS_STRUCT])}function getKind(e){switch((0,_kindOf2.default)(e)){case"function":return"Function";case"string":return"Scalar";case"array":return"List";case"object":return"Object";default:(0,_invariant2.default)(!1)}}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},_kindOf=require("kind-of"),_kindOf2=_interopRequireDefault(_kindOf),_invariant=require("invariant"),_invariant2=_interopRequireDefault(_invariant),_types=require("./types"),_types2=_interopRequireDefault(_types),_schemas=require("./schemas"),_schemas2=_interopRequireDefault(_schemas);const IS_STRUCT="@@__STRUCT__@@",STRUCT_PROPERTIES=["kind","type","schema","defaults","options"],STRUCT_METHODS=["assert","default","test","validate"];exports.default=superstruct},{"./schemas":13,"./types":15,invariant:4,"kind-of":8}],15:[function(require,module,exports){"use strict";function _interopRequireDefault(r){return r&&r.__esModule?r:{default:r}}Object.defineProperty(exports,"__esModule",{value:!0});var _kindOf=require("kind-of"),_kindOf2=_interopRequireDefault(_kindOf);const KIND_OF_TYPES=["arguments","array","boolean","buffer","date","float32array","float64array","function","generatorfunction","int16array","int32array","int8array","map","null","number","object","regexp","set","string","symbol","uint16array","uint32array","uint8array","uint8clampedarray","undefined","weakmap","weakset"],TYPES={any:r=>void 0!==r,error:r=>"[object Error]"===Object.prototype.toString.call(r)};KIND_OF_TYPES.forEach(r=>{TYPES[r]=(e=>(0,_kindOf2.default)(e)===r)}),exports.default=TYPES},{"kind-of":8}]},{},[12])(12)}); |
@@ -8,5 +8,5 @@ 'use strict'; | ||
var _structError = require('./struct-error'); | ||
var _error = require('./error'); | ||
var _structError2 = _interopRequireDefault(_structError); | ||
var _error2 = _interopRequireDefault(_error); | ||
@@ -35,2 +35,2 @@ var _superstruct = require('./superstruct'); | ||
exports.superstruct = _superstruct2.default; | ||
exports.StructError = _structError2.default; | ||
exports.StructError = _error2.default; |
@@ -9,6 +9,2 @@ 'use strict'; | ||
var _cloneDeep = require('clone-deep'); | ||
var _cloneDeep2 = _interopRequireDefault(_cloneDeep); | ||
var _kindOf = require('kind-of'); | ||
@@ -18,10 +14,14 @@ | ||
var _defaultTypes = require('./default-types'); | ||
var _invariant = require('invariant'); | ||
var _defaultTypes2 = _interopRequireDefault(_defaultTypes); | ||
var _invariant2 = _interopRequireDefault(_invariant); | ||
var _structError = require('./struct-error'); | ||
var _types = require('./types'); | ||
var _structError2 = _interopRequireDefault(_structError); | ||
var _types2 = _interopRequireDefault(_types); | ||
var _schemas = require('./schemas'); | ||
var _schemas2 = _interopRequireDefault(_schemas); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -43,3 +43,3 @@ | ||
const STRUCT_PROPERTIES = ['schema', 'defaults', 'options']; | ||
const STRUCT_PROPERTIES = ['kind', 'type', 'schema', 'defaults', 'options']; | ||
@@ -55,18 +55,2 @@ /** | ||
/** | ||
* The diffrent Kinds of struct schemas. | ||
* | ||
* @type {Array} | ||
*/ | ||
const STRUCT_KINDS = ['scalar', 'function', 'object', 'list']; | ||
/** | ||
* Convenience flags for the struct factory. | ||
* | ||
* @type {Array} | ||
*/ | ||
const STRUCT_FLAGS = ['required']; | ||
/** | ||
* Create a struct factory with a `config`. | ||
@@ -79,368 +63,5 @@ * | ||
function superstruct(config = {}) { | ||
const TYPES = _extends({}, _defaultTypes2.default, config.types || {}); | ||
const types = _extends({}, _types2.default, config.types || {}); | ||
/** | ||
* Base schema. | ||
* | ||
* @type {Schema} | ||
*/ | ||
class Schema { | ||
/** | ||
* Create a schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
constructor(schema, defaults, options = {}) { | ||
this.schema = schema; | ||
this.defaults = defaults; | ||
this.options = options; | ||
} | ||
/** | ||
* Assert that a `value` is valid, throwing if not. | ||
* | ||
* @param {Any} value | ||
* @return {Any|StructError} | ||
*/ | ||
assert(value) { | ||
const [error, result] = this.validate(value); | ||
if (error) throw error; | ||
return result; | ||
} | ||
/** | ||
* Get the defaulted value, given an initial `value`. | ||
* | ||
* @param {Any} value | ||
* @return {Any} | ||
*/ | ||
default(value) { | ||
if (value !== undefined) return value; | ||
const { defaults } = this; | ||
return typeof defaults === 'function' ? defaults() : (0, _cloneDeep2.default)(defaults); | ||
} | ||
/** | ||
* Test that a `value` is valid. | ||
* | ||
* @param {Any} value | ||
* @return {Boolean} | ||
*/ | ||
test(value) { | ||
const [error] = this.validate(value); | ||
return !error; | ||
} | ||
/** | ||
* Validate a `value`, returning an error or the value with defaults. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
value = this.default(value); | ||
return [undefined, value]; | ||
} | ||
} | ||
/** | ||
* Function schema. | ||
* | ||
* @type {FunctionSchema} | ||
*/ | ||
class FunctionSchema extends Schema { | ||
/** | ||
* Create a function schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
this.type = '<function>'; | ||
} | ||
/** | ||
* Validate a `value`, returning an error or the value with defaults. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
const { options, type, schema } = this; | ||
value = this.default(value); | ||
if (options.required && value === undefined || value !== undefined && !schema(value)) { | ||
const error = new _structError2.default({ type, value, data: value, path: [] }); | ||
return [error]; | ||
} | ||
return [undefined, value]; | ||
} | ||
} | ||
/** | ||
* Scalar schema. | ||
* | ||
* @type {ScalarSchema} | ||
*/ | ||
class ScalarSchema extends Schema { | ||
/** | ||
* Create a scalar schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
const required = !schema.endsWith('?'); | ||
const type = required ? schema : schema.slice(0, -1); | ||
const types = type.split(/\s*\|\s*/g); | ||
const validators = types.map(t => { | ||
const fn = TYPES[t]; | ||
if (typeof fn === 'function') return fn; | ||
throw new Error(`No struct validator function found for type "${t}".`); | ||
}); | ||
this.options.required = required; | ||
this.type = type; | ||
this.validators = validators; | ||
} | ||
/** | ||
* Validate a `value`, returning an error or the value with defaults. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
const { options, type, validators } = this; | ||
value = this.default(value); | ||
if (options.required && value === undefined || value !== undefined && !validators.some(fn => fn(value))) { | ||
const error = new _structError2.default({ type, value, data: value, path: [] }); | ||
return [error]; | ||
} | ||
return [undefined, value]; | ||
} | ||
} | ||
/** | ||
* List schema. | ||
* | ||
* @type {ListSchema} | ||
*/ | ||
class ListSchema extends Schema { | ||
/** | ||
* Create a list schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
if (schema.length !== 1) { | ||
throw new Error(`List structs must be defined as an array with a single element, but you passed ${schema.length} elements.`); | ||
} | ||
const type = options.required ? 'array' : 'array?'; | ||
const valueStruct = struct(type); | ||
const elementStruct = struct(schema[0]); | ||
this.type = type; | ||
this.valueStruct = valueStruct; | ||
this.elementStruct = elementStruct; | ||
} | ||
/** | ||
* Validate a list `value`. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
const { options, elementStruct, valueStruct } = this; | ||
value = this.default(value); | ||
const [error] = valueStruct.validate(value); | ||
if (error) return [error]; | ||
const errors = []; | ||
const values = []; | ||
const isUndefined = !options.required && value === undefined; | ||
value = isUndefined ? [] : value; | ||
value.forEach((element, index) => { | ||
const [e, r] = elementStruct.validate(element); | ||
if (e) { | ||
e.path = [index].concat(e.path); | ||
e.data = value; | ||
errors.push(e); | ||
return; | ||
} | ||
values.push(r); | ||
}); | ||
if (errors.length) { | ||
const first = errors[0]; | ||
first.errors = errors; | ||
return [first]; | ||
} | ||
const ret = isUndefined && !values.length ? undefined : values; | ||
return [undefined, ret]; | ||
} | ||
} | ||
/** | ||
* Object schema. | ||
* | ||
* @type {ObjectSchema} | ||
*/ | ||
class ObjectSchema extends Schema { | ||
/** | ||
* Create an object schema with `schema`, `defaults` and `options`. | ||
* | ||
* @param {Any} schema | ||
* @param {Any} defaults | ||
* @param {Object} options | ||
*/ | ||
constructor(schema, defaults, options = {}) { | ||
super(schema, defaults, options); | ||
const propertyStructs = {}; | ||
for (const key in schema) { | ||
const s = struct(schema[key]); | ||
propertyStructs[key] = s; | ||
if (s.options.required) { | ||
this.options.required = true; | ||
} | ||
} | ||
const type = this.options.required ? 'object' : 'object?'; | ||
const valueStruct = struct(type); | ||
this.type = type; | ||
this.valueStruct = valueStruct; | ||
this.propertyStructs = propertyStructs; | ||
} | ||
/** | ||
* Get the defaulted value, given an initial `value`. | ||
* | ||
* @param {Object|Void} value | ||
* @return {Object|Void} | ||
*/ | ||
default(value) { | ||
const { defaults } = this; | ||
if (value !== undefined || defaults === undefined) return value; | ||
const defs = typeof defaults === 'function' ? defaults() : (0, _cloneDeep2.default)(defaults); | ||
const ret = Object.assign({}, value, defs); | ||
return ret; | ||
} | ||
/** | ||
* Validate a list `value`. | ||
* | ||
* @param {Any} value | ||
* @return {Array} | ||
*/ | ||
validate(value) { | ||
const { options, propertyStructs, valueStruct } = this; | ||
value = this.default(value); | ||
const [error] = valueStruct.validate(value); | ||
if (error) return [error]; | ||
const errors = []; | ||
const values = {}; | ||
const isUndefined = !options.required && value === undefined; | ||
value = isUndefined ? {} : value; | ||
const valueKeys = Object.keys(value); | ||
const schemaKeys = Object.keys(propertyStructs); | ||
const keys = new Set(valueKeys.concat(schemaKeys)); | ||
const hasKeys = !!valueKeys.length; | ||
keys.forEach(k => { | ||
const v = value[k]; | ||
const s = this.propertyStructs[k]; | ||
if (!s) { | ||
const e = new _structError2.default({ data: value, path: [k], value: v }); | ||
errors.push(e); | ||
return; | ||
} | ||
const [e, r] = s.validate(v); | ||
if (e) { | ||
e.path = [k].concat(e.path); | ||
e.data = value; | ||
errors.push(e); | ||
return; | ||
} | ||
if (k in value) { | ||
values[k] = r; | ||
} | ||
}); | ||
if (errors.length) { | ||
const first = errors[0]; | ||
first.errors = errors; | ||
return [first]; | ||
} | ||
const ret = isUndefined && !hasKeys ? undefined : values; | ||
return [undefined, ret]; | ||
} | ||
} | ||
/** | ||
* Create a `kind` struct with schema `definition`, `defaults` and `options`. | ||
@@ -455,35 +76,19 @@ * | ||
function createStruct(kind, definition, defaults, options) { | ||
function createStruct(kind, definition, defaults, options = {}) { | ||
if (isStruct(definition)) { | ||
return definition; | ||
definition = definition.schema; | ||
} | ||
const args = [definition, defaults, options]; | ||
let schema; | ||
const Schema = _schemas2.default[kind]; | ||
const schema = new Schema(definition, defaults, _extends({}, options, { types, struct })); | ||
if (kind === 'function') { | ||
schema = new FunctionSchema(...args); | ||
} else if (kind === 'scalar') { | ||
schema = new ScalarSchema(...args); | ||
} else if (kind === 'list') { | ||
schema = new ListSchema(...args); | ||
} else if (kind === 'object') { | ||
schema = new ObjectSchema(...args); | ||
} else { | ||
throw new Error(`Unrecognized struct kind: ${kind}`); | ||
} | ||
// Define the struct creator function. | ||
function Struct(data) { | ||
if (this instanceof Struct) { | ||
throw new Error('The `Struct` creation function should not be used with the `new` keyword.'); | ||
} | ||
!!(this instanceof Struct) ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, 'The `Struct` creation function should not be used with the `new` keyword.') : (0, _invariant2.default)(false) : void 0; | ||
return schema.assert(data); | ||
} | ||
// Add a private property for identifying struct functions. | ||
Struct[IS_STRUCT] = true; | ||
Struct.kind = kind; | ||
// Mix in the public struct properties. | ||
STRUCT_PROPERTIES.forEach(prop => { | ||
@@ -493,3 +98,2 @@ Struct[prop] = schema[prop]; | ||
// Mix in the public struct methods. | ||
STRUCT_METHODS.forEach(method => { | ||
@@ -512,6 +116,3 @@ Struct[method] = (...a) => schema[method](...a); | ||
function struct(definition, defaults, options) { | ||
if (isStruct(definition)) { | ||
return definition; | ||
} | ||
if (isStruct(definition)) return definition; | ||
const kind = getKind(definition); | ||
@@ -523,11 +124,10 @@ const Struct = createStruct(kind, definition, defaults, options); | ||
// Mix in a factory for each kind of struct. | ||
STRUCT_KINDS.forEach(kind => { | ||
struct[kind] = (...args) => createStruct(kind, ...args); | ||
Object.keys(_schemas2.default).forEach(kind => { | ||
const lower = kind.toLowerCase(); | ||
struct[lower] = (...args) => createStruct(kind, ...args); | ||
}); | ||
// Mix in the convenience properties for option flags. | ||
STRUCT_FLAGS.forEach(flag => { | ||
Object.defineProperty(struct, flag, { | ||
get: () => (s, d, o = {}) => struct(s, d, _extends({}, o, { [flag]: true })) | ||
}); | ||
// Mix in the `required` convenience flag. | ||
Object.defineProperty(struct, 'required', { | ||
get: () => (s, d, o = {}) => struct(s, d, _extends({}, o, { required: true })) | ||
}); | ||
@@ -563,12 +163,12 @@ | ||
case 'function': | ||
return 'function'; | ||
return 'Function'; | ||
case 'string': | ||
return 'scalar'; | ||
return 'Scalar'; | ||
case 'array': | ||
return 'list'; | ||
return 'List'; | ||
case 'object': | ||
return 'object'; | ||
return 'Object'; | ||
default: | ||
{ | ||
throw new Error(`A struct schema definition must be a string, array or object, but you passed: ${definition}`); | ||
!false ? process.env.NODE_ENV !== 'production' ? (0, _invariant2.default)(false, `A struct schema definition must be a string, array or object, but you passed: ${definition}`) : (0, _invariant2.default)(false) : void 0; | ||
} | ||
@@ -575,0 +175,0 @@ } |
{ | ||
"name": "superstruct", | ||
"description": "A simple, expressive way to validate data in Javascript.", | ||
"version": "0.3.0", | ||
"version": "0.3.1", | ||
"license": "MIT", | ||
@@ -14,2 +14,3 @@ "repository": "git://github.com/ianstormtaylor/superstruct.git", | ||
"clone-deep": "^2.0.1", | ||
"invariant": "^2.2.2", | ||
"kind-of": "^6.0.1" | ||
@@ -21,2 +22,3 @@ }, | ||
"babel-eslint": "^8.0.2", | ||
"babel-plugin-dev-expression": "^0.2.1", | ||
"babel-plugin-transform-async-to-generator": "^6.24.1", | ||
@@ -23,0 +25,0 @@ "babel-plugin-transform-es2015-modules-commonjs": "^6.26.0", |
@@ -26,9 +26,9 @@ | ||
<a href="https://unpkg.com/superstruct/dist/superstruct.min.js"> | ||
<img src="http://img.badgesize.io/https://unpkg.com/superstruct/dist/superstruct.min.js?compression=gzip&label=size&maxAge=3600"> | ||
<img src="http://img.badgesize.io/https://unpkg.com/superstruct/dist/superstruct.min.js?compression=gzip&label=size&maxAge=300"> | ||
</a> | ||
<a href="./packages/superstruct/package.json"> | ||
<img src="https://img.shields.io/npm/v/superstruct.svg?maxAge=3600&label=version&colorB=007ec6&maxAge=3600"> | ||
<img src="https://img.shields.io/npm/v/superstruct.svg?maxAge=300&label=version&colorB=007ec6&maxAge=300"> | ||
</a> | ||
<a href="./License.md"> | ||
<img src="https://img.shields.io/npm/l/slate.svg?maxAge=3600"> | ||
<img src="https://img.shields.io/npm/l/slate.svg?maxAge=300"> | ||
</a> | ||
@@ -35,0 +35,0 @@ </p> |
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
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
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
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
68823
11
0
3
20
1379
10
+ Addedinvariant@^2.2.2
+ Addedinvariant@2.2.4(transitive)
+ Addedjs-tokens@4.0.0(transitive)
+ Addedloose-envify@1.4.0(transitive)