Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

superstruct

Package Overview
Dependencies
Maintainers
1
Versions
90
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

superstruct - npm Package Compare versions

Comparing version 0.4.12 to 0.5.0

16

Changelog.md

@@ -10,2 +10,18 @@

### `0.5.0` — December 21, 2017
###### BREAKING
- **Validators must now return `true`, `false` or an error reason string.** Previously any truthy value would be considered valid. Now you can provide more information for the thrown errors by providing a string which will be attached as `error.reason`. However, this means that truthy string values now equate to invalid, not valid.
- **Property validators now receive `data` as their second argument.** Previously you only had access to the property `value`, but now you also have access to the entire object's `data`.
###### NEW
- **Errors can now contain reason information.** Validator functions can now return string instead of a boolean, denoting the reason a value was invalid. This can then be used to create more helpful error messages.
---
### `0.4.0` — December 1, 2017

@@ -12,0 +28,0 @@

26

lib/index.es.js

@@ -10,3 +10,3 @@ /**

constructor(attrs) {
const { data, value, type, path, errors = [] } = attrs;
const { data, value, type, path, reason, errors = [] } = attrs;
const message = `Expected a value of type \`${type}\`${path.length ? ` for \`${path.join('.')}\`` : ''} but received \`${JSON.stringify(value)}\`.`;

@@ -18,2 +18,3 @@ super(message);

this.type = type;
this.reason = reason;
this.errors = errors;

@@ -413,4 +414,19 @@ if (!errors.length) errors.push(this);

const type = '<function>';
const validate = (value = resolveDefaults(defaults)) => {
return schema(value) ? [undefined, value] : [{ type, value, data: value, path: [] }];
const validate = (value = resolveDefaults(defaults), data) => {
const result = schema(value, data);
const isReason = kindOf(result) === 'string';
const isBoolean = kindOf(result) === 'boolean';
if (!isReason && !isBoolean) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(`Validator functions must return a boolean or an error reason string, but you passed: ${schema}`);
} else {
throw new Error(`Invalid result: ${result}`);
}
}
const isValid = isReason ? false : result;
const reason = isReason ? result : undefined;
return isValid ? [undefined, value] : [{ type, value, data: value, path: [], reason }];
};

@@ -665,3 +681,3 @@

const [e, r] = kind.validate(v);
const [e, r] = kind.validate(v, value);

@@ -754,3 +770,3 @@ if (e) {

const [e, r] = kind.validate(v);
const [e, r] = kind.validate(v, value);

@@ -757,0 +773,0 @@ if (e) {

@@ -14,3 +14,3 @@ 'use strict';

constructor(attrs) {
const { data, value, type, path, errors = [] } = attrs;
const { data, value, type, path, reason, errors = [] } = attrs;
const message = `Expected a value of type \`${type}\`${path.length ? ` for \`${path.join('.')}\`` : ''} but received \`${JSON.stringify(value)}\`.`;

@@ -22,2 +22,3 @@ super(message);

this.type = type;
this.reason = reason;
this.errors = errors;

@@ -417,4 +418,19 @@ if (!errors.length) errors.push(this);

const type = '<function>';
const validate = (value = resolveDefaults(defaults)) => {
return schema(value) ? [undefined, value] : [{ type, value, data: value, path: [] }];
const validate = (value = resolveDefaults(defaults), data) => {
const result = schema(value, data);
const isReason = kindOf(result) === 'string';
const isBoolean = kindOf(result) === 'boolean';
if (!isReason && !isBoolean) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(`Validator functions must return a boolean or an error reason string, but you passed: ${schema}`);
} else {
throw new Error(`Invalid result: ${result}`);
}
}
const isValid = isReason ? false : result;
const reason = isReason ? result : undefined;
return isValid ? [undefined, value] : [{ type, value, data: value, path: [], reason }];
};

@@ -669,3 +685,3 @@

const [e, r] = kind.validate(v);
const [e, r] = kind.validate(v, value);

@@ -758,3 +774,3 @@ if (e) {

const [e, r] = kind.validate(v);
const [e, r] = kind.validate(v, value);

@@ -761,0 +777,0 @@ if (e) {

8

package.json
{
"name": "superstruct",
"description": "A simple, expressive way to validate data in JavaScript.",
"version": "0.4.12",
"version": "0.5.0",
"license": "MIT",

@@ -43,4 +43,4 @@ "repository": "git://github.com/ianstormtaylor/superstruct.git",

"rollup-plugin-replace": "^2.0.0",
"uglifyify": "^4.0.5",
"watchify": "^3.7.0"
"rollup-plugin-uglify": "^2.0.1",
"uglify-es": "^3.2.2"
},

@@ -52,3 +52,3 @@ "scripts": {

"build:max": "rollup --config ./config/rollup-umd.js",
"build:min": "NODE_ENV=production rollup --config ./config/rollup-umd-min.js | uglifyjs > ./umd/superstruct.min.js",
"build:min": "rollup --config ./config/rollup-umd-min.js",
"clean": "rm -rf ./lib ./umd ./node_modules",

@@ -55,0 +55,0 @@ "lint": "eslint src/* test/*",

@@ -16,3 +16,3 @@ (function (global, factory) {

constructor(attrs) {
const { data, value, type, path, errors = [] } = attrs;
const { data, value, type, path, reason, errors = [] } = attrs;
const message = `Expected a value of type \`${type}\`${path.length ? ` for \`${path.join('.')}\`` : ''} but received \`${JSON.stringify(value)}\`.`;

@@ -24,2 +24,3 @@ super(message);

this.type = type;
this.reason = reason;
this.errors = errors;

@@ -277,6 +278,4 @@ if (!errors.length) errors.push(this);

if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`A schema definition must be an object, array, string or function, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -295,6 +294,4 @@ }

if (kindOf(schema) !== 'array' || schema.length !== 2) {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Dict structs must be defined as an array with two elements, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -365,6 +362,4 @@ }

if (kindOf(schema) !== 'array') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Enum structs must be defined as an array, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -413,6 +408,4 @@ }

if (kindOf(schema) !== 'function') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Function structs must be defined as a function, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -423,4 +416,17 @@ }

const type = '<function>';
const validate = (value = resolveDefaults(defaults)) => {
return schema(value) ? [undefined, value] : [{ type, value, data: value, path: [] }];
const validate = (value = resolveDefaults(defaults), data) => {
const result = schema(value, data);
const isReason = kindOf(result) === 'string';
const isBoolean = kindOf(result) === 'boolean';
if (!isReason && !isBoolean) {
{
throw new Error(`Validator functions must return a boolean or an error reason string, but you passed: ${schema}`);
}
}
const isValid = isReason ? false : result;
const reason = isReason ? result : undefined;
return isValid ? [undefined, value] : [{ type, value, data: value, path: [], reason }];
};

@@ -459,6 +465,4 @@

if (kindOf(schema) !== 'object') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Interface structs must be defined as an object, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -517,6 +521,4 @@ }

if (kindOf(schema) !== 'function') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Lazy structs must be defined as an function that returns a schema, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -551,6 +553,4 @@ }

if (kindOf(schema) !== 'array' || schema.length !== 1) {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`List structs must be defined as an array with a single element, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -629,6 +629,4 @@ }

if (kindOf(schema) !== 'object') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Object structs must be defined as an object, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -679,3 +677,3 @@ }

const [e, r] = kind.validate(v);
const [e, r] = kind.validate(v, value);

@@ -728,6 +726,4 @@ if (e) {

if (kindOf(schema) !== 'object') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Partial structs must be defined as an object, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -769,3 +765,3 @@ }

const [e, r] = kind.validate(v);
const [e, r] = kind.validate(v, value);

@@ -806,6 +802,4 @@ if (e) {

if (kindOf(schema) !== 'string') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Scalar structs must be defined as a string, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -818,6 +812,4 @@ }

if (kindOf(fn) !== 'function') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`No struct validator function found for type "${schema}".`);
} else {
throw new Error(`Invalid type: ${schema}`);
}

@@ -853,6 +845,4 @@ }

if (kindOf(schema) !== 'array') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Tuple structs must be defined as an array, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -921,6 +911,4 @@ }

if (kindOf(schema) !== 'array') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Union structs must be defined as an array, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -958,6 +946,4 @@ }

if (kindOf(schema) !== 'array') {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error(`Intersection structs must be defined as an array, but you passed: ${schema}`);
} else {
throw new Error(`Invalid schema: ${schema}`);
}

@@ -1086,6 +1072,4 @@ }

if (this instanceof Struct) {
if (process.env.NODE_ENV !== 'production') {
{
throw new Error('The `Struct` creation function should not be used with the `new` keyword.');
} else {
throw new Error('Invalid `new` keyword!');
}

@@ -1092,0 +1076,0 @@ }

@@ -1,1 +0,1 @@

(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):factory(global.Superstruct={})})(this,function(exports){"use strict";class StructError extends TypeError{constructor(attrs){const{data:data,value:value,type:type,path:path,errors:errors=[]}=attrs;const message=`Expected a value of type \`${type}\`${path.length?` for \`${path.join(".")}\``:""} but received \`${JSON.stringify(value)}\`.`;super(message);this.data=data;this.path=path;this.value=value;this.type=type;this.errors=errors;if(!errors.length)errors.push(this);if(Error.captureStackTrace){Error.captureStackTrace(this,this.constructor)}else{this.stack=(new Error).stack}}}var toString=Object.prototype.toString;var kindOf=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}const IS_STRUCT="@@__STRUCT__@@";const KIND="@@__KIND__@@";function isStruct(value){return!!(value&&value[IS_STRUCT])}function resolveDefaults(defaults,value){return typeof defaults==="function"?defaults(value):defaults}class Kind{constructor(name,type,validate){this.name=name;this.type=type;this.validate=validate}}function any(schema,defaults,options){if(isStruct(schema))return schema[KIND];if(schema instanceof Kind)return schema;switch(kindOf(schema)){case"array":{return schema.length>1?tuple(schema,defaults,options):list(schema,defaults,options)}case"function":{return func(schema,defaults,options)}case"object":{return object(schema,defaults,options)}case"string":{let required=true;let type;if(schema.endsWith("?")){required=false;schema=schema.slice(0,-1)}if(schema.includes("|")){const scalars=schema.split(/\s*\|\s*/g);type=union(scalars,defaults,options)}else if(schema.includes("&")){const scalars=schema.split(/\s*&\s*/g);type=intersection(scalars,defaults,options)}else{type=scalar(schema,defaults,options)}if(!required){type=optional(type,undefined,options)}return type}}{throw new Error(`Invalid schema: ${schema}`)}}function dict(schema,defaults,options){if(kindOf(schema)!=="array"||schema.length!==2){{throw new Error(`Invalid schema: ${schema}`)}}const obj=scalar("object",undefined,options);const keys=any(schema[0],undefined,options);const values=any(schema[1],undefined,options);const name="dict";const type=`dict<${keys.type},${values.type}>`;const validate=(value=resolveDefaults(defaults))=>{const[error]=obj.validate(value);if(error){error.type=type;return[error]}const ret={};const errors=[];for(let k in value){const v=value[k];const[e,r]=keys.validate(k);if(e){e.path=[k].concat(e.path);e.data=value;errors.push(e);continue}k=r;const[e2,r2]=values.validate(v);if(e2){e2.path=[k].concat(e2.path);e2.data=value;errors.push(e2);continue}ret[k]=r2}if(errors.length){const first=errors[0];first.errors=errors;return[first]}return[undefined,ret]};return new Kind(name,type,validate)}function en(schema,defaults,options){if(kindOf(schema)!=="array"){{throw new Error(`Invalid schema: ${schema}`)}}const name="enum";const type=schema.map(s=>{try{return JSON.stringify(s)}catch(e){return String(s)}}).join(" | ");const validate=(value=resolveDefaults(defaults))=>{return schema.includes(value)?[undefined,value]:[{data:value,path:[],value:value,type:type}]};return new Kind(name,type,validate)}function enums(schema,defaults,options){const e=en(schema,undefined,options);const l=list([e],defaults,options);return l}function func(schema,defaults,options){if(kindOf(schema)!=="function"){{throw new Error(`Invalid schema: ${schema}`)}}const name="function";const type="<function>";const validate=(value=resolveDefaults(defaults))=>{return schema(value)?[undefined,value]:[{type:type,value:value,data:value,path:[]}]};return new Kind(name,type,validate)}function instance(schema,defaults,options){const name="instance";const type=`instance<${schema.name}>`;const validate=(value=resolveDefaults(defaults))=>{return value instanceof schema?[undefined,value]:[{data:value,path:[],value:value,type:type}]};return new Kind(name,type,validate)}function inter(schema,defaults,options){if(kindOf(schema)!=="object"){{throw new Error(`Invalid schema: ${schema}`)}}const ks=[];const properties={};for(const key in schema){ks.push(key);const s=schema[key];const kind=any(s,undefined,options);properties[key]=kind}const name="interface";const type=`{${ks.join()}}`;const validate=(value=resolveDefaults(defaults))=>{const errors=[];for(const key in properties){const v=value[key];const kind=properties[key];const[e]=kind.validate(v);if(e){e.path=[key].concat(e.path);e.data=value;errors.push(e);continue}}if(errors.length){const first=errors[0];first.errors=errors;return[first]}return[undefined,value]};return new Kind(name,type,validate)}function lazy(schema,defaults,options){if(kindOf(schema)!=="function"){{throw new Error(`Invalid schema: ${schema}`)}}let kind;let struct;const name="lazy";const type=`lazy...`;const compile=value=>{struct=schema();kind.name=struct.kind;kind.type=struct.type;kind.validate=struct.validate;return kind.validate(value)};kind=new Kind(name,type,compile);return kind}function list(schema,defaults,options){if(kindOf(schema)!=="array"||schema.length!==1){{throw new Error(`Invalid schema: ${schema}`)}}const array=scalar("array",undefined,options);const element=any(schema[0],undefined,options);const name="list";const type=`[${element.type}]`;const validate=(value=resolveDefaults(defaults))=>{const[error,result]=array.validate(value);if(error){error.type=type;return[error]}value=result;const errors=[];const ret=[];for(let i=0;i<value.length;i++){const v=value[i];const[e,r]=element.validate(v);if(e){e.path=[i].concat(e.path);e.data=value;errors.push(e);continue}ret[i]=r}if(errors.length){const first=errors[0];first.errors=errors;return[first]}return[undefined,ret]};return new Kind(name,type,validate)}function literal(schema,defaults,options){const name="literal";const type=`literal: ${JSON.stringify(schema)}`;const validate=(value=resolveDefaults(defaults))=>{return value===schema?[undefined,value]:[{data:value,path:[],value:value,type:type}]};return new Kind(name,type,validate)}function object(schema,defaults,options){if(kindOf(schema)!=="object"){{throw new Error(`Invalid schema: ${schema}`)}}const obj=scalar("object",undefined,options);const ks=[];const properties={};for(const key in schema){ks.push(key);const s=schema[key];const kind=any(s,undefined,options);properties[key]=kind}const name="object";const type=`{${ks.join()}}`;const validate=(value=resolveDefaults(defaults))=>{const[error]=obj.validate(value);if(error){error.type=type;return[error]}const errors=[];const ret={};const valueKeys=Object.keys(value);const propertiesKeys=Object.keys(properties);const keys=new Set(valueKeys.concat(propertiesKeys));keys.forEach(key=>{let v=value[key];const kind=properties[key];if(v===undefined){const d=defaults&&defaults[key];v=resolveDefaults(d,value)}if(!kind){const e={data:value,path:[key],value:v};errors.push(e);return}const[e,r]=kind.validate(v);if(e){e.path=[key].concat(e.path);e.data=value;errors.push(e);return}if(key in value||r!==undefined){ret[key]=r}});if(errors.length){const first=errors[0];first.errors=errors;return[first]}return[undefined,ret]};return new Kind(name,type,validate)}function optional(schema,defaults,options){return union([schema,"undefined"],defaults,options)}function partial(schema,defaults,options){if(kindOf(schema)!=="object"){{throw new Error(`Invalid schema: ${schema}`)}}const obj=scalar("object",undefined,options);const ks=[];const properties={};for(const key in schema){ks.push(key);const s=schema[key];const kind=any(s,undefined,options);properties[key]=kind}const name="partial";const type=`{${ks.join()},...}`;const validate=(value=resolveDefaults(defaults))=>{const[error]=obj.validate(value);if(error){error.type=type;return[error]}const errors=[];const ret={};for(const key in properties){let v=value[key];const kind=properties[key];if(v===undefined){const d=defaults&&defaults[key];v=resolveDefaults(d,value)}const[e,r]=kind.validate(v);if(e){e.path=[key].concat(e.path);e.data=value;errors.push(e);continue}if(key in value||r!==undefined){ret[key]=r}}if(errors.length){const first=errors[0];first.errors=errors;return[first]}return[undefined,ret]};return new Kind(name,type,validate)}function scalar(schema,defaults,options){if(kindOf(schema)!=="string"){{throw new Error(`Invalid schema: ${schema}`)}}const{types:types}=options;const fn=types[schema];if(kindOf(fn)!=="function"){{throw new Error(`Invalid type: ${schema}`)}}const kind=func(fn,defaults,options);const name="scalar";const type=schema;const validate=value=>{const[error,result]=kind.validate(value);if(error){error.type=type;return[error]}return[undefined,result]};return new Kind(name,type,validate)}function tuple(schema,defaults,options){if(kindOf(schema)!=="array"){{throw new Error(`Invalid schema: ${schema}`)}}const kinds=schema.map(s=>any(s,undefined,options));const array=scalar("array",undefined,options);const name="tuple";const type=`[${kinds.map(k=>k.type).join()}]`;const validate=(value=resolveDefaults(defaults))=>{const[error]=array.validate(value);if(error){error.type=type;return[error]}const ret=[];const errors=[];const length=Math.max(value.length,kinds.length);for(let i=0;i<length;i++){const kind=kinds[i];const v=value[i];if(!kind){const e={data:value,path:[i],value:v};errors.push(e);continue}const[e,r]=kind.validate(v);if(e){e.path=[i].concat(e.path);e.data=value;errors.push(e);continue}ret[i]=r}if(errors.length){const first=errors[0];first.errors=errors;return[first]}return[undefined,ret]};return new Kind(name,type,validate)}function union(schema,defaults,options){if(kindOf(schema)!=="array"){{throw new Error(`Invalid schema: ${schema}`)}}const kinds=schema.map(s=>any(s,undefined,options));const name="union";const type=kinds.map(k=>k.type).join(" | ");const validate=(value=resolveDefaults(defaults))=>{let error;for(const k of kinds){const[e,r]=k.validate(value);if(!e)return[undefined,r];error=e}error.type=type;return[error]};return new Kind(name,type,validate)}function intersection(schema,defaults,options){if(kindOf(schema)!=="array"){{throw new Error(`Invalid schema: ${schema}`)}}const types=schema.map(s=>any(s,undefined,options));const name="intersection";const type=types.map(t=>t.type).join(" & ");const validate=(value=resolveDefaults(defaults))=>{let v=value;for(const t of types){const[e,r]=t.validate(v);if(e){e.type=type;return[e]}v=r}return[undefined,v]};return new Kind(name,type,validate)}const Kinds={any:any,dict:dict,enum:en,enums:enums,function:func,instance:instance,interface:inter,lazy:lazy,list:list,literal:literal,object:object,optional:optional,partial:partial,scalar:scalar,tuple:tuple,union:union,intersection:intersection};const TYPES=["arguments","array","boolean","buffer","date","error","float32array","float64array","function","generatorfunction","int16array","int32array","int8array","map","null","number","object","promise","regexp","set","string","symbol","uint16array","uint32array","uint8array","uint8clampedarray","undefined","weakmap","weakset"];const Types={any:value=>value!==undefined};TYPES.forEach(type=>{Types[type]=(value=>kindOf(value)===type)});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};function superstruct(config={}){const types=_extends({},Types,config.types||{});function struct(schema,defaults$$1,options={}){if(isStruct(schema)){schema=schema.schema}const kind=Kinds.any(schema,defaults$$1,_extends({},options,{types:types}));function Struct(data){if(this instanceof Struct){{throw new Error("Invalid `new` keyword!")}}return Struct.assert(data)}Object.defineProperty(Struct,IS_STRUCT,{value:true});Object.defineProperty(Struct,KIND,{value:kind});Struct.kind=kind.name;Struct.type=kind.type;Struct.schema=schema;Struct.defaults=defaults$$1;Struct.options=options;Struct.assert=(value=>{const[error,result]=kind.validate(value);if(error)throw new StructError(error);return result});Struct.test=(value=>{const[error]=kind.validate(value);return!error});Struct.validate=(value=>{const[error,result]=kind.validate(value);if(error)return[new StructError(error)];return[undefined,result]});return Struct}Object.keys(Kinds).forEach(name=>{const kind=Kinds[name];struct[name]=((schema,defaults$$1,options)=>{const type=kind(schema,defaults$$1,_extends({},options,{types:types}));const s=struct(type,defaults$$1,options);return s})});return struct}const struct=superstruct();exports.struct=struct;exports.superstruct=superstruct;exports.isStruct=isStruct;exports.StructError=StructError;Object.defineProperty(exports,"__esModule",{value:true})});
!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(t.Superstruct={})}(this,function(t){"use strict";function r(t){return t.constructor?t.constructor.name:null}function e(t){return!(!t||!t[w])}function n(t,r){return"function"==typeof t?t(r):t}function o(t,r,n){if(e(t))return t[m];if(t instanceof g)return t;switch(v(t)){case"array":return t.length>1?d(t,r,n):s(t,r,n);case"function":return i(t,r,n);case"object":return u(t,r,n);case"string":{let e,o=!0;if(t.endsWith("?")&&(o=!1,t=t.slice(0,-1)),t.includes("|")){e=p(t.split(/\s*\|\s*/g),r,n)}else if(t.includes("&")){e=l(t.split(/\s*&\s*/g),r,n)}else e=f(t,r,n);return o||(e=c(e,void 0,n)),e}}throw new Error(`A schema definition must be an object, array, string or function, but you passed: ${t}`)}function a(t,r,e){if("array"!==v(t))throw new Error(`Enum structs must be defined as an array, but you passed: ${t}`);const o=t.map(t=>{try{return JSON.stringify(t)}catch(r){return String(t)}}).join(" | ");return new g("enum",o,(e=n(r))=>t.includes(e)?[void 0,e]:[{data:e,path:[],value:e,type:o}])}function i(t,r,e){if("function"!==v(t))throw new Error(`Function structs must be defined as a function, but you passed: ${t}`);return new g("function","<function>",(e=n(r),o)=>{const a=t(e,o),i="string"===v(a),s="boolean"===v(a);if(!i&&!s)throw new Error(`Validator functions must return a boolean or an error reason string, but you passed: ${t}`);return!i&&a?[void 0,e]:[{type:"<function>",value:e,data:e,path:[],reason:i?a:void 0}]})}function s(t,r,e){if("array"!==v(t)||1!==t.length)throw new Error(`List structs must be defined as an array with a single element, but you passed: ${t}`);const a=f("array",void 0,e),i=o(t[0],void 0,e),s=`[${i.type}]`;return new g("list",s,(t=n(r))=>{const[e,o]=a.validate(t);if(e)return e.type=s,[e];t=o;const u=[],c=[];for(let r=0;r<t.length;r++){const e=t[r],[n,o]=i.validate(e);n?(n.path=[r].concat(n.path),n.data=t,u.push(n)):c[r]=o}if(u.length){const t=u[0];return t.errors=u,[t]}return[void 0,c]})}function u(t,r,e){if("object"!==v(t))throw new Error(`Object structs must be defined as an object, but you passed: ${t}`);const a=f("object",void 0,e),i=[],s={};for(const r in t){i.push(r);const n=o(t[r],void 0,e);s[r]=n}const u=`{${i.join()}}`;return new g("object",u,(t=n(r))=>{const[e]=a.validate(t);if(e)return e.type=u,[e];const o=[],i={},c=Object.keys(t),f=Object.keys(s);if(new Set(c.concat(f)).forEach(e=>{let a=t[e];const u=s[e];if(void 0===a&&(a=n(r&&r[e],t)),!u){const r={data:t,path:[e],value:a};return void o.push(r)}const[c,f]=u.validate(a,t);if(c)return c.path=[e].concat(c.path),c.data=t,void o.push(c);(e in t||void 0!==f)&&(i[e]=f)}),o.length){const t=o[0];return t.errors=o,[t]}return[void 0,i]})}function c(t,r,e){return p([t,"undefined"],r,e)}function f(t,r,e){if("string"!==v(t))throw new Error(`Scalar structs must be defined as a string, but you passed: ${t}`);const{types:n}=e,o=n[t];if("function"!==v(o))throw new Error(`No struct validator function found for type "${t}".`);const a=i(o,r),s=t;return new g("scalar",s,t=>{const[r,e]=a.validate(t);return r?(r.type=s,[r]):[void 0,e]})}function d(t,r,e){if("array"!==v(t))throw new Error(`Tuple structs must be defined as an array, but you passed: ${t}`);const a=t.map(t=>o(t,void 0,e)),i=f("array",void 0,e),s=`[${a.map(t=>t.type).join()}]`;return new g("tuple",s,(t=n(r))=>{const[e]=i.validate(t);if(e)return e.type=s,[e];const o=[],u=[],c=Math.max(t.length,a.length);for(let r=0;r<c;r++){const e=a[r],n=t[r];if(!e){const e={data:t,path:[r],value:n};u.push(e);continue}const[i,s]=e.validate(n);i?(i.path=[r].concat(i.path),i.data=t,u.push(i)):o[r]=s}if(u.length){const t=u[0];return t.errors=u,[t]}return[void 0,o]})}function p(t,r,e){if("array"!==v(t))throw new Error(`Union structs must be defined as an array, but you passed: ${t}`);const a=t.map(t=>o(t,void 0,e)),i=a.map(t=>t.type).join(" | ");return new g("union",i,(t=n(r))=>{let e;for(const r of a){const[n,o]=r.validate(t);if(!n)return[void 0,o];e=n}return e.type=i,[e]})}function l(t,r,e){if("array"!==v(t))throw new Error(`Intersection structs must be defined as an array, but you passed: ${t}`);const a=t.map(t=>o(t,void 0,e)),i=a.map(t=>t.type).join(" & ");return new g("intersection",i,(t=n(r))=>{let e=t;for(const t of a){const[r,n]=t.validate(e);if(r)return r.type=i,[r];e=n}return[void 0,e]})}function y(t={}){function r(t,r,o={}){function a(t){if(this instanceof a)throw new Error("The `Struct` creation function should not be used with the `new` keyword.");return a.assert(t)}e(t)&&(t=t.schema);const i=j.any(t,r,$({},o,{types:n}));return Object.defineProperty(a,w,{value:!0}),Object.defineProperty(a,m,{value:i}),a.kind=i.name,a.type=i.type,a.schema=t,a.defaults=r,a.options=o,a.assert=(t=>{const[r,e]=i.validate(t);if(r)throw new h(r);return e}),a.test=(t=>{const[r]=i.validate(t);return!r}),a.validate=(t=>{const[r,e]=i.validate(t);return r?[new h(r)]:[void 0,e]}),a}const n=$({},E,t.types||{});return Object.keys(j).forEach(t=>{const e=j[t];r[t]=((t,o,a)=>{return r(e(t,o,$({},a,{types:n})),o,a)})}),r}class h extends TypeError{constructor(t){const{data:r,value:e,type:n,path:o,reason:a,errors:i=[]}=t;super(`Expected a value of type \`${n}\`${o.length?` for \`${o.join(".")}\``:""} but received \`${JSON.stringify(e)}\`.`),this.data=r,this.path=o,this.value=e,this.type=n,this.reason=a,this.errors=i,i.length||i.push(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack}}var b=Object.prototype.toString,v=function(t){if(void 0===t)return"undefined";if(null===t)return"null";var e=typeof t;if("boolean"===e)return"boolean";if("string"===e)return"string";if("number"===e)return"number";if("symbol"===e)return"symbol";if("function"===e)return function(t,e){return"GeneratorFunction"===r(t)}(t)?"generatorfunction":"function";if(function(t){return Array.isArray?Array.isArray(t):t instanceof Array}(t))return"array";if(function(t){return!(!t.constructor||"function"!=typeof t.constructor.isBuffer)&&t.constructor.isBuffer(t)}(t))return"buffer";if(function(t){try{if("number"==typeof t.length&&"function"==typeof t.callee)return!0}catch(t){if(-1!==t.message.indexOf("callee"))return!0}return!1}(t))return"arguments";if(function(t){return t instanceof Date||"function"==typeof t.toDateString&&"function"==typeof t.getDate&&"function"==typeof t.setDate}(t))return"date";if(function(t){return t instanceof Error||"string"==typeof t.message&&t.constructor&&"number"==typeof t.constructor.stackTraceLimit}(t))return"error";if(function(t){return t instanceof RegExp||"string"==typeof t.flags&&"boolean"==typeof t.ignoreCase&&"boolean"==typeof t.multiline&&"boolean"==typeof t.global}(t))return"regexp";switch(r(t)){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(function(t){return"function"==typeof t.throw&&"function"==typeof t.return&&"function"==typeof t.next}(t))return"generator";switch(e=b.call(t)){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 e.slice(8,-1).toLowerCase().replace(/\s/g,"")};const w="@@__STRUCT__@@",m="@@__KIND__@@";class g{constructor(t,r,e){this.name=t,this.type=r,this.validate=e}}const j={any:o,dict:function(t,r,e){if("array"!==v(t)||2!==t.length)throw new Error(`Dict structs must be defined as an array with two elements, but you passed: ${t}`);const a=f("object",void 0,e),i=o(t[0],void 0,e),s=o(t[1],void 0,e),u=`dict<${i.type},${s.type}>`;return new g("dict",u,(t=n(r))=>{const[e]=a.validate(t);if(e)return e.type=u,[e];const o={},c=[];for(let r in t){const e=t[r],[n,a]=i.validate(r);if(n){n.path=[r].concat(n.path),n.data=t,c.push(n);continue}r=a;const[u,f]=s.validate(e);u?(u.path=[r].concat(u.path),u.data=t,c.push(u)):o[r]=f}if(c.length){const t=c[0];return t.errors=c,[t]}return[void 0,o]})},enum:a,enums:function(t,r,e){return s([a(t,void 0)],r,e)},function:i,instance:function(t,r,e){const o=`instance<${t.name}>`;return new g("instance",o,(e=n(r))=>e instanceof t?[void 0,e]:[{data:e,path:[],value:e,type:o}])},interface:function(t,r,e){if("object"!==v(t))throw new Error(`Interface structs must be defined as an object, but you passed: ${t}`);const a=[],i={};for(const r in t){a.push(r);const n=o(t[r],void 0,e);i[r]=n}const s=`{${a.join()}}`;return new g("interface",s,(t=n(r))=>{const e=[];for(const r in i){const n=t[r],o=i[r],[a]=o.validate(n);a&&(a.path=[r].concat(a.path),a.data=t,e.push(a))}if(e.length){const t=e[0];return t.errors=e,[t]}return[void 0,t]})},lazy:function(t,r,e){if("function"!==v(t))throw new Error(`Lazy structs must be defined as an function that returns a schema, but you passed: ${t}`);let n,o;return n=new g("lazy","lazy...",r=>(o=t(),n.name=o.kind,n.type=o.type,n.validate=o.validate,n.validate(r)))},list:s,literal:function(t,r,e){const o=`literal: ${JSON.stringify(t)}`;return new g("literal",o,(e=n(r))=>e===t?[void 0,e]:[{data:e,path:[],value:e,type:o}])},object:u,optional:c,partial:function(t,r,e){if("object"!==v(t))throw new Error(`Partial structs must be defined as an object, but you passed: ${t}`);const a=f("object",void 0,e),i=[],s={};for(const r in t){i.push(r);const n=o(t[r],void 0,e);s[r]=n}const u=`{${i.join()},...}`;return new g("partial",u,(t=n(r))=>{const[e]=a.validate(t);if(e)return e.type=u,[e];const o=[],i={};for(const e in s){let a=t[e];const u=s[e];void 0===a&&(a=n(r&&r[e],t));const[c,f]=u.validate(a,t);c?(c.path=[e].concat(c.path),c.data=t,o.push(c)):(e in t||void 0!==f)&&(i[e]=f)}if(o.length){const t=o[0];return t.errors=o,[t]}return[void 0,i]})},scalar:f,tuple:d,union:p,intersection:l},E={any:t=>void 0!==t};["arguments","array","boolean","buffer","date","error","float32array","float64array","function","generatorfunction","int16array","int32array","int8array","map","null","number","object","promise","regexp","set","string","symbol","uint16array","uint32array","uint8array","uint8clampedarray","undefined","weakmap","weakset"].forEach(t=>{E[t]=(r=>v(r)===t)});var $=Object.assign||function(t){for(var r=1;r<arguments.length;r++){var e=arguments[r];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])}return t};const S=y();t.struct=S,t.superstruct=y,t.isStruct=e,t.StructError=h,Object.defineProperty(t,"__esModule",{value:!0})});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc