actn-db 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/db/__setup.sql ADDED
@@ -0,0 +1,37 @@
1
+ -- Extensions
2
+
3
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
4
+ CREATE EXTENSION IF NOT EXISTS "plv8";
5
+ CREATE EXTENSION IF NOT EXISTS "plcoffee";
6
+
7
+
8
+
9
+
10
+
11
+ -- Js Libs
12
+
13
+ CREATE TABLE plv8_modules(modname text primary key, load_on_start boolean, code text);
14
+
15
+ CREATE OR REPLACE FUNCTION plv8_startup() RETURNS void AS $$
16
+
17
+ load_module = (modname) ->
18
+ rows = plv8.execute("SELECT code from public.plv8_modules " + " where modname = $1", [modname])
19
+ r = 0
20
+
21
+ while r < rows.length
22
+ code = rows[r].code
23
+ eval("(function(){" + code + "})")()
24
+ r++
25
+ return
26
+
27
+
28
+ # now load all the modules marked for loading on start
29
+ rows = plv8.execute("SELECT modname, code from public.plv8_modules where load_on_start")
30
+ r = 0
31
+
32
+ while r < rows.length
33
+ code = rows[r].code
34
+ eval("(function(){" + code + "})")()
35
+ r++
36
+
37
+ $$ LANGUAGE plcoffee STABLE STRICT;
data/db/lib/_0_actn.js ADDED
@@ -0,0 +1,23 @@
1
+ global = (function() {
2
+ return this;
3
+ }).call(null);
4
+
5
+ var Actn = (function() {
6
+ function Actn() {}
7
+
8
+ Actn.prototype.valueAt = function(data, key) {
9
+ var i, keys;
10
+ keys = key.split(".");
11
+ for (i in keys) {
12
+ if (data != null) {
13
+ data = data[keys[i]];
14
+ }
15
+ }
16
+ return data;
17
+ };
18
+
19
+ return Actn;
20
+
21
+ })();
22
+
23
+ global.actn = new Actn();
@@ -0,0 +1 @@
1
+ (function(){var root=this;var previousUnderscore=root._;var ArrayProto=Array.prototype,ObjProto=Object.prototype,FuncProto=Function.prototype;var push=ArrayProto.push,slice=ArrayProto.slice,concat=ArrayProto.concat,toString=ObjProto.toString,hasOwnProperty=ObjProto.hasOwnProperty;var nativeIsArray=Array.isArray,nativeKeys=Object.keys,nativeBind=FuncProto.bind;var _=function(obj){if(obj instanceof _)return obj;if(!(this instanceof _))return new _(obj);this._wrapped=obj};if(typeof exports!=='undefined'){if(typeof module!=='undefined'&&module.exports){exports=module.exports=_}exports._=_}else{root._=_}_.VERSION='1.7.0';var createCallback=function(func,context,argCount){if(context===void 0)return func;switch(argCount==null?3:argCount){case 1:return function(value){return func.call(context,value)};case 2:return function(value,other){return func.call(context,value,other)};case 3:return function(value,index,collection){return func.call(context,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(context,accumulator,value,index,collection)}}return function(){return func.apply(context,arguments)}};_.iteratee=function(value,context,argCount){if(value==null)return _.identity;if(_.isFunction(value))return createCallback(value,context,argCount);if(_.isObject(value))return _.matches(value);return _.property(value)};_.each=_.forEach=function(obj,iteratee,context){if(obj==null)return obj;iteratee=createCallback(iteratee,context);var i,length=obj.length;if(length===+length){for(i=0;i<length;i++){iteratee(obj[i],i,obj)}}else{var keys=_.keys(obj);for(i=0,length=keys.length;i<length;i++){iteratee(obj[keys[i]],keys[i],obj)}}return obj};_.map=_.collect=function(obj,iteratee,context){if(obj==null)return[];iteratee=_.iteratee(iteratee,context);var keys=obj.length!==+obj.length&&_.keys(obj),length=(keys||obj).length,results=Array(length),currentKey;for(var index=0;index<length;index++){currentKey=keys?keys[index]:index;results[index]=iteratee(obj[currentKey],currentKey,obj)}return results};var reduceError='Reduce of empty array with no initial value';_.reduce=_.foldl=_.inject=function(obj,iteratee,memo,context){if(obj==null)obj=[];iteratee=createCallback(iteratee,context,4);var keys=obj.length!==+obj.length&&_.keys(obj),length=(keys||obj).length,index=0,currentKey;if(arguments.length<3){if(!length)throw new TypeError(reduceError);memo=obj[keys?keys[index++]:index++]}for(;index<length;index++){currentKey=keys?keys[index]:index;memo=iteratee(memo,obj[currentKey],currentKey,obj)}return memo};_.reduceRight=_.foldr=function(obj,iteratee,memo,context){if(obj==null)obj=[];iteratee=createCallback(iteratee,context,4);var keys=obj.length!==+obj.length&&_.keys(obj),index=(keys||obj).length,currentKey;if(arguments.length<3){if(!index)throw new TypeError(reduceError);memo=obj[keys?keys[--index]:--index]}while(index--){currentKey=keys?keys[index]:index;memo=iteratee(memo,obj[currentKey],currentKey,obj)}return memo};_.find=_.detect=function(obj,predicate,context){var result;predicate=_.iteratee(predicate,context);_.some(obj,function(value,index,list){if(predicate(value,index,list)){result=value;return true}});return result};_.filter=_.select=function(obj,predicate,context){var results=[];if(obj==null)return results;predicate=_.iteratee(predicate,context);_.each(obj,function(value,index,list){if(predicate(value,index,list))results.push(value)});return results};_.reject=function(obj,predicate,context){return _.filter(obj,_.negate(_.iteratee(predicate)),context)};_.every=_.all=function(obj,predicate,context){if(obj==null)return true;predicate=_.iteratee(predicate,context);var keys=obj.length!==+obj.length&&_.keys(obj),length=(keys||obj).length,index,currentKey;for(index=0;index<length;index++){currentKey=keys?keys[index]:index;if(!predicate(obj[currentKey],currentKey,obj))return false}return true};_.some=_.any=function(obj,predicate,context){if(obj==null)return false;predicate=_.iteratee(predicate,context);var keys=obj.length!==+obj.length&&_.keys(obj),length=(keys||obj).length,index,currentKey;for(index=0;index<length;index++){currentKey=keys?keys[index]:index;if(predicate(obj[currentKey],currentKey,obj))return true}return false};_.contains=_.include=function(obj,target){if(obj==null)return false;if(obj.length!==+obj.length)obj=_.values(obj);return _.indexOf(obj,target)>=0};_.invoke=function(obj,method){var args=slice.call(arguments,2);var isFunc=_.isFunction(method);return _.map(obj,function(value){return(isFunc?method:value[method]).apply(value,args)})};_.pluck=function(obj,key){return _.map(obj,_.property(key))};_.where=function(obj,attrs){return _.filter(obj,_.matches(attrs))};_.findWhere=function(obj,attrs){return _.find(obj,_.matches(attrs))};_.max=function(obj,iteratee,context){var result=-Infinity,lastComputed=-Infinity,value,computed;if(iteratee==null&&obj!=null){obj=obj.length===+obj.length?obj:_.values(obj);for(var i=0,length=obj.length;i<length;i++){value=obj[i];if(value>result){result=value}}}else{iteratee=_.iteratee(iteratee,context);_.each(obj,function(value,index,list){computed=iteratee(value,index,list);if(computed>lastComputed||computed===-Infinity&&result===-Infinity){result=value;lastComputed=computed}})}return result};_.min=function(obj,iteratee,context){var result=Infinity,lastComputed=Infinity,value,computed;if(iteratee==null&&obj!=null){obj=obj.length===+obj.length?obj:_.values(obj);for(var i=0,length=obj.length;i<length;i++){value=obj[i];if(value<result){result=value}}}else{iteratee=_.iteratee(iteratee,context);_.each(obj,function(value,index,list){computed=iteratee(value,index,list);if(computed<lastComputed||computed===Infinity&&result===Infinity){result=value;lastComputed=computed}})}return result};_.shuffle=function(obj){var set=obj&&obj.length===+obj.length?obj:_.values(obj);var length=set.length;var shuffled=Array(length);for(var index=0,rand;index<length;index++){rand=_.random(0,index);if(rand!==index)shuffled[index]=shuffled[rand];shuffled[rand]=set[index]}return shuffled};_.sample=function(obj,n,guard){if(n==null||guard){if(obj.length!==+obj.length)obj=_.values(obj);return obj[_.random(obj.length-1)]}return _.shuffle(obj).slice(0,Math.max(0,n))};_.sortBy=function(obj,iteratee,context){iteratee=_.iteratee(iteratee,context);return _.pluck(_.map(obj,function(value,index,list){return{value:value,index:index,criteria:iteratee(value,index,list)}}).sort(function(left,right){var a=left.criteria;var b=right.criteria;if(a!==b){if(a>b||a===void 0)return 1;if(a<b||b===void 0)return-1}return left.index-right.index}),'value')};var group=function(behavior){return function(obj,iteratee,context){var result={};iteratee=_.iteratee(iteratee,context);_.each(obj,function(value,index){var key=iteratee(value,index,obj);behavior(result,value,key)});return result}};_.groupBy=group(function(result,value,key){if(_.has(result,key))result[key].push(value);else result[key]=[value]});_.indexBy=group(function(result,value,key){result[key]=value});_.countBy=group(function(result,value,key){if(_.has(result,key))result[key]++;else result[key]=1});_.sortedIndex=function(array,obj,iteratee,context){iteratee=_.iteratee(iteratee,context,1);var value=iteratee(obj);var low=0,high=array.length;while(low<high){var mid=low+high>>>1;if(iteratee(array[mid])<value)low=mid+1;else high=mid}return low};_.toArray=function(obj){if(!obj)return[];if(_.isArray(obj))return slice.call(obj);if(obj.length===+obj.length)return _.map(obj,_.identity);return _.values(obj)};_.size=function(obj){if(obj==null)return 0;return obj.length===+obj.length?obj.length:_.keys(obj).length};_.partition=function(obj,predicate,context){predicate=_.iteratee(predicate,context);var pass=[],fail=[];_.each(obj,function(value,key,obj){(predicate(value,key,obj)?pass:fail).push(value)});return[pass,fail]};_.first=_.head=_.take=function(array,n,guard){if(array==null)return void 0;if(n==null||guard)return array[0];return _.initial(array,array.length-n)};_.initial=function(array,n,guard){return slice.call(array,0,Math.max(0,array.length-(n==null||guard?1:n)))};_.last=function(array,n,guard){if(array==null)return void 0;if(n==null||guard)return array[array.length-1];return _.rest(array,Math.max(0,array.length-n))};_.rest=_.tail=_.drop=function(array,n,guard){return slice.call(array,n==null||guard?1:n)};_.compact=function(array){return _.filter(array,_.identity)};var flatten=function(input,shallow,strict,output){if(shallow&&_.every(input,_.isArray)){return concat.apply(output,input)}for(var i=0,length=input.length;i<length;i++){var value=input[i];if(!_.isArray(value)&&!_.isArguments(value)){if(!strict)output.push(value)}else if(shallow){push.apply(output,value)}else{flatten(value,shallow,strict,output)}}return output};_.flatten=function(array,shallow){return flatten(array,shallow,false,[])};_.without=function(array){return _.difference(array,slice.call(arguments,1))};_.uniq=_.unique=function(array,isSorted,iteratee,context){if(array==null)return[];if(!_.isBoolean(isSorted)){context=iteratee;iteratee=isSorted;isSorted=false}if(iteratee!=null)iteratee=_.iteratee(iteratee,context);var result=[];var seen=[];for(var i=0,length=array.length;i<length;i++){var value=array[i];if(isSorted){if(!i||seen!==value)result.push(value);seen=value}else if(iteratee){var computed=iteratee(value,i,array);if(_.indexOf(seen,computed)<0){seen.push(computed);result.push(value)}}else if(_.indexOf(result,value)<0){result.push(value)}}return result};_.union=function(){return _.uniq(flatten(arguments,true,true,[]))};_.intersection=function(array){if(array==null)return[];var result=[];var argsLength=arguments.length;for(var i=0,length=array.length;i<length;i++){var item=array[i];if(_.contains(result,item))continue;for(var j=1;j<argsLength;j++){if(!_.contains(arguments[j],item))break}if(j===argsLength)result.push(item)}return result};_.difference=function(array){var rest=flatten(slice.call(arguments,1),true,true,[]);return _.filter(array,function(value){return!_.contains(rest,value)})};_.zip=function(array){if(array==null)return[];var length=_.max(arguments,'length').length;var results=Array(length);while(length-->0){results[length]=_.pluck(arguments,length)}return results};_.unzip=function(array){return _.zip.apply(null,array)};_.object=function(list,values){if(list==null)return{};var result={};for(var i=0,length=list.length;i<length;i++){if(values){result[list[i]]=values[i]}else{result[list[i][0]]=list[i][1]}}return result};_.indexOf=function(array,item,isSorted){if(array==null)return-1;var i=0,length=array.length;if(isSorted){if(typeof isSorted=='number'){i=isSorted<0?Math.max(0,length+isSorted):isSorted}else{i=_.sortedIndex(array,item);return array[i]===item?i:-1}}for(;i<length;i++)if(array[i]===item)return i;return-1};_.lastIndexOf=function(array,item,from){if(array==null)return-1;var idx=array.length;if(typeof from=='number'){idx=from<0?idx+from+1:Math.min(idx,from+1)}while(--idx>=0)if(array[idx]===item)return idx;return-1};_.range=function(start,stop,step){if(arguments.length<=1){stop=start||0;start=0}step=step||1;var length=Math.max(Math.ceil((stop-start)/step),0);var range=Array(length);for(var idx=0;idx<length;idx++,start+=step){range[idx]=start}return range};var Ctor=function(){};_.bind=function(func,context){var args,bound;if(nativeBind&&func.bind===nativeBind)return nativeBind.apply(func,slice.call(arguments,1));if(!_.isFunction(func))throw new TypeError('Bind must be called on a function');args=slice.call(arguments,2);bound=function(){if(!(this instanceof bound))return func.apply(context,args.concat(slice.call(arguments)));Ctor.prototype=func.prototype;var self=new Ctor;Ctor.prototype=null;var result=func.apply(self,args.concat(slice.call(arguments)));if(_.isObject(result))return result;return self};return bound};_.partial=function(func){var boundArgs=slice.call(arguments,1);return function(){var position=0;var args=boundArgs.slice();for(var i=0,length=args.length;i<length;i++){if(args[i]===_)args[i]=arguments[position++]}while(position<arguments.length)args.push(arguments[position++]);return func.apply(this,args)}};_.bindAll=function(obj){var i,length=arguments.length,key;if(length<=1)throw new Error('bindAll must be passed function names');for(i=1;i<length;i++){key=arguments[i];obj[key]=_.bind(obj[key],obj)}return obj};_.memoize=function(func,hasher){var memoize=function(key){var cache=memoize.cache;var address=''+(hasher?hasher.apply(this,arguments):key);if(!_.has(cache,address))cache[address]=func.apply(this,arguments);return cache[address]};memoize.cache={};return memoize};_.delay=function(func,wait){var args=slice.call(arguments,2);return setTimeout(function(){return func.apply(null,args)},wait)};_.defer=function(func){return _.delay.apply(_,[func,1].concat(slice.call(arguments,1)))};_.throttle=function(func,wait,options){var context,args,result;var timeout=null;var previous=0;if(!options)options={};var later=function(){previous=options.leading===false?0:_.now();timeout=null;result=func.apply(context,args);if(!timeout)context=args=null};return function(){var now=_.now();if(!previous&&options.leading===false)previous=now;var remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0||remaining>wait){if(timeout){clearTimeout(timeout);timeout=null}previous=now;result=func.apply(context,args);if(!timeout)context=args=null}else if(!timeout&&options.trailing!==false){timeout=setTimeout(later,remaining)}return result}};_.debounce=function(func,wait,immediate){var timeout,args,context,timestamp,result;var later=function(){var last=_.now()-timestamp;if(last<wait&&last>=0){timeout=setTimeout(later,wait-last)}else{timeout=null;if(!immediate){result=func.apply(context,args);if(!timeout)context=args=null}}};return function(){context=this;args=arguments;timestamp=_.now();var callNow=immediate&&!timeout;if(!timeout)timeout=setTimeout(later,wait);if(callNow){result=func.apply(context,args);context=args=null}return result}};_.wrap=function(func,wrapper){return _.partial(wrapper,func)};_.negate=function(predicate){return function(){return!predicate.apply(this,arguments)}};_.compose=function(){var args=arguments;var start=args.length-1;return function(){var i=start;var result=args[start].apply(this,arguments);while(i--)result=args[i].call(this,result);return result}};_.after=function(times,func){return function(){if(--times<1){return func.apply(this,arguments)}}};_.before=function(times,func){var memo;return function(){if(--times>0){memo=func.apply(this,arguments)}else{func=null}return memo}};_.once=_.partial(_.before,2);var hasEnumBug=!({toString:null}).propertyIsEnumerable('toString');var nonEnumerableProps=['constructor','valueOf','isPrototypeOf','toString','propertyIsEnumerable','hasOwnProperty','toLocaleString'];_.keys=function(obj){if(!_.isObject(obj))return[];if(nativeKeys)return nativeKeys(obj);var keys=[];for(var key in obj)if(_.has(obj,key))keys.push(key);if(hasEnumBug){var nonEnumIdx=nonEnumerableProps.length;while(nonEnumIdx--){var prop=nonEnumerableProps[nonEnumIdx];if(_.has(obj,prop)&&!_.contains(keys,prop))keys.push(prop)}}return keys};_.values=function(obj){var keys=_.keys(obj);var length=keys.length;var values=Array(length);for(var i=0;i<length;i++){values[i]=obj[keys[i]]}return values};_.pairs=function(obj){var keys=_.keys(obj);var length=keys.length;var pairs=Array(length);for(var i=0;i<length;i++){pairs[i]=[keys[i],obj[keys[i]]]}return pairs};_.invert=function(obj){var result={};var keys=_.keys(obj);for(var i=0,length=keys.length;i<length;i++){result[obj[keys[i]]]=keys[i]}return result};_.functions=_.methods=function(obj){var names=[];for(var key in obj){if(_.isFunction(obj[key]))names.push(key)}return names.sort()};_.extend=function(obj){if(!_.isObject(obj))return obj;var source,prop;for(var i=1,length=arguments.length;i<length;i++){source=arguments[i];for(prop in source){obj[prop]=source[prop]}}return obj};_.pick=function(obj,iteratee,context){var result={},key;if(obj==null)return result;if(_.isFunction(iteratee)){iteratee=createCallback(iteratee,context);for(key in obj){var value=obj[key];if(iteratee(value,key,obj))result[key]=value}}else{var keys=concat.apply([],slice.call(arguments,1));obj=new Object(obj);for(var i=0,length=keys.length;i<length;i++){key=keys[i];if(key in obj)result[key]=obj[key]}}return result};_.omit=function(obj,iteratee,context){if(_.isFunction(iteratee)){iteratee=_.negate(iteratee)}else{var keys=_.map(concat.apply([],slice.call(arguments,1)),String);iteratee=function(value,key){return!_.contains(keys,key)}}return _.pick(obj,iteratee,context)};_.defaults=function(obj){if(!_.isObject(obj))return obj;for(var i=1,length=arguments.length;i<length;i++){var source=arguments[i];for(var prop in source){if(obj[prop]===void 0)obj[prop]=source[prop]}}return obj};_.clone=function(obj){if(!_.isObject(obj))return obj;return _.isArray(obj)?obj.slice():_.extend({},obj)};_.tap=function(obj,interceptor){interceptor(obj);return obj};var eq=function(a,b,aStack,bStack){if(a===b)return a!==0||1/a===1/b;if(a==null||b==null)return a===b;if(a instanceof _)a=a._wrapped;if(b instanceof _)b=b._wrapped;var className=toString.call(a);if(className!==toString.call(b))return false;switch(className){case'[object RegExp]':case'[object String]':return''+a===''+b;case'[object Number]':if(+a!==+a)return+b!==+b;return+a===0?1/+a===1/b:+a===+b;case'[object Date]':case'[object Boolean]':return+a===+b}var areArrays=className==='[object Array]';if(!areArrays){if(typeof a!='object'||typeof b!='object')return false;var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(_.isFunction(aCtor)&&aCtor instanceof aCtor&&_.isFunction(bCtor)&&bCtor instanceof bCtor)&&('constructor'in a&&'constructor'in b)){return false}}var length=aStack.length;while(length--){if(aStack[length]===a)return bStack[length]===b}aStack.push(a);bStack.push(b);var size,result;if(areArrays){size=a.length;result=size===b.length;if(result){while(size--){if(!(result=eq(a[size],b[size],aStack,bStack)))break}}}else{var keys=_.keys(a),key;size=keys.length;result=_.keys(b).length===size;if(result){while(size--){key=keys[size];if(!(result=_.has(b,key)&&eq(a[key],b[key],aStack,bStack)))break}}}aStack.pop();bStack.pop();return result};_.isEqual=function(a,b){return eq(a,b,[],[])};_.isEmpty=function(obj){if(obj==null)return true;if(_.isArray(obj)||_.isString(obj)||_.isArguments(obj))return obj.length===0;for(var key in obj)if(_.has(obj,key))return false;return true};_.isElement=function(obj){return!!(obj&&obj.nodeType===1)};_.isArray=nativeIsArray||function(obj){return toString.call(obj)==='[object Array]'};_.isObject=function(obj){var type=typeof obj;return type==='function'||type==='object'&&!!obj};_.each(['Arguments','Function','String','Number','Date','RegExp','Error'],function(name){_['is'+name]=function(obj){return toString.call(obj)==='[object '+name+']'}});if(!_.isArguments(arguments)){_.isArguments=function(obj){return _.has(obj,'callee')}}if(typeof/./!=='function'){_.isFunction=function(obj){return typeof obj=='function'||false}}_.isFinite=function(obj){return isFinite(obj)&&!isNaN(parseFloat(obj))};_.isNaN=function(obj){return _.isNumber(obj)&&obj!==+obj};_.isBoolean=function(obj){return obj===true||obj===false||toString.call(obj)==='[object Boolean]'};_.isNull=function(obj){return obj===null};_.isUndefined=function(obj){return obj===void 0};_.has=function(obj,key){return obj!=null&&hasOwnProperty.call(obj,key)};_.noConflict=function(){root._=previousUnderscore;return this};_.identity=function(value){return value};_.constant=function(value){return function(){return value}};_.noop=function(){};_.property=function(key){return function(obj){return obj==null?void 0:obj[key]}};_.matches=function(attrs){var pairs=_.pairs(attrs),length=pairs.length;return function(obj){if(obj==null)return!length;obj=new Object(obj);for(var i=0;i<length;i++){var pair=pairs[i],key=pair[0];if(pair[1]!==obj[key]||!(key in obj))return false}return true}};_.times=function(n,iteratee,context){var accum=Array(Math.max(0,n));iteratee=createCallback(iteratee,context,1);for(var i=0;i<n;i++)accum[i]=iteratee(i);return accum};_.random=function(min,max){if(max==null){max=min;min=0}return min+Math.floor(Math.random()*(max-min+1))};_.now=Date.now||function(){return new Date().getTime()};var escapeMap={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#x27;','`':'&#x60;'};var unescapeMap=_.invert(escapeMap);var createEscaper=function(map){var escaper=function(match){return map[match]};var source='(?:'+_.keys(map).join('|')+')';var testRegexp=RegExp(source);var replaceRegexp=RegExp(source,'g');return function(string){string=string==null?'':''+string;return testRegexp.test(string)?string.replace(replaceRegexp,escaper):string}};_.escape=createEscaper(escapeMap);_.unescape=createEscaper(unescapeMap);_.result=function(object,property,fallback){var value=object==null?void 0:object[property];if(value===void 0){return fallback}return _.isFunction(value)?object[property]():value};var idCounter=0;_.uniqueId=function(prefix){var id=++idCounter+'';return prefix?prefix+id:id};_.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var noMatch=/(.)^/;var escapes={"'":"'",'\\':'\\','\r':'r','\n':'n','\u2028':'u2028','\u2029':'u2029'};var escaper=/\\|'|\r|\n|\u2028|\u2029/g;var escapeChar=function(match){return'\\'+escapes[match]};_.template=function(text,settings,oldSettings){if(!settings&&oldSettings)settings=oldSettings;settings=_.defaults({},settings,_.templateSettings);var matcher=RegExp([(settings.escape||noMatch).source,(settings.interpolate||noMatch).source,(settings.evaluate||noMatch).source].join('|')+'|$','g');var index=0;var source="__p+='";text.replace(matcher,function(match,escape,interpolate,evaluate,offset){source+=text.slice(index,offset).replace(escaper,escapeChar);index=offset+match.length;if(escape){source+="'+\n((__t=("+escape+"))==null?'':_.escape(__t))+\n'"}else if(interpolate){source+="'+\n((__t=("+interpolate+"))==null?'':__t)+\n'"}else if(evaluate){source+="';\n"+evaluate+"\n__p+='"}return match});source+="';\n";if(!settings.variable)source='with(obj||{}){\n'+source+'}\n';source="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+source+'return __p;\n';try{var render=new Function(settings.variable||'obj','_',source)}catch(e){e.source=source;throw e}var template=function(data){return render.call(this,data,_)};var argument=settings.variable||'obj';template.source='function('+argument+'){\n'+source+'}';return template};_.chain=function(obj){var instance=_(obj);instance._chain=true;return instance};var result=function(instance,obj){return instance._chain?_(obj).chain():obj};_.mixin=function(obj){_.each(_.functions(obj),function(name){var func=_[name]=obj[name];_.prototype[name]=function(){var args=[this._wrapped];push.apply(args,arguments);return result(this,func.apply(_,args))}})};_.mixin(_);_.each(['pop','push','reverse','shift','sort','splice','unshift'],function(name){var method=ArrayProto[name];_.prototype[name]=function(){var obj=this._wrapped;method.apply(obj,arguments);if((name==='shift'||name==='splice')&&obj.length===0)delete obj[0];return result(this,obj)}});_.each(['concat','join','slice'],function(name){var method=ArrayProto[name];_.prototype[name]=function(){return result(this,method.apply(this._wrapped,arguments))}});_.prototype.value=function(){return this._wrapped};if(typeof define==='function'&&define.amd){define('underscore',[],function(){return _})}}.call(this));
data/db/lib/_2_jjv.js ADDED
@@ -0,0 +1,739 @@
1
+ /* jshint proto: true */
2
+
3
+ /**
4
+ * jjv.js -- A javascript library to validate json input through a json-schema.
5
+ *
6
+ * Copyright (c) 2013 Alex Cornejo.
7
+ *
8
+ * Redistributable under a MIT-style open source license.
9
+ */
10
+
11
+ (function () {
12
+ var clone = function (obj) {
13
+ // Handle the 3 simple types (string, number, function), and null or undefined
14
+ if (obj === null || typeof obj !== 'object') return obj;
15
+ var copy;
16
+
17
+ // Handle Date
18
+ if (obj instanceof Date) {
19
+ copy = new Date();
20
+ copy.setTime(obj.getTime());
21
+ return copy;
22
+ }
23
+
24
+ // handle RegExp
25
+ if (obj instanceof RegExp) {
26
+ copy = new RegExp(obj);
27
+ return copy;
28
+ }
29
+
30
+ // Handle Array
31
+ if (obj instanceof Array) {
32
+ copy = [];
33
+ for (var i = 0, len = obj.length; i < len; i++)
34
+ copy[i] = clone(obj[i]);
35
+ return copy;
36
+ }
37
+
38
+ // Handle Object
39
+ if (obj instanceof Object) {
40
+ copy = {};
41
+ // copy = Object.create(Object.getPrototypeOf(obj));
42
+ for (var attr in obj) {
43
+ if (obj.hasOwnProperty(attr))
44
+ copy[attr] = clone(obj[attr]);
45
+ }
46
+ return copy;
47
+ }
48
+
49
+ throw new Error("Unable to clone object!");
50
+ };
51
+
52
+ var clone_stack = function (stack) {
53
+ var new_stack = [ clone(stack[0]) ], key = new_stack[0].key, obj = new_stack[0].object;
54
+ for (var i = 1, len = stack.length; i< len; i++) {
55
+ obj = obj[key];
56
+ key = stack[i].key;
57
+ new_stack.push({ object: obj, key: key });
58
+ }
59
+ return new_stack;
60
+ };
61
+
62
+ var copy_stack = function (new_stack, old_stack) {
63
+ var stack_last = new_stack.length-1, key = new_stack[stack_last].key;
64
+ old_stack[stack_last].object[key] = new_stack[stack_last].object[key];
65
+ };
66
+
67
+ var handled = {
68
+ 'type': true,
69
+ 'not': true,
70
+ 'anyOf': true,
71
+ 'allOf': true,
72
+ 'oneOf': true,
73
+ '$ref': true,
74
+ '$schema': true,
75
+ 'id': true,
76
+ 'exclusiveMaximum': true,
77
+ 'exclusiveMininum': true,
78
+ 'properties': true,
79
+ 'patternProperties': true,
80
+ 'additionalProperties': true,
81
+ 'items': true,
82
+ 'additionalItems': true,
83
+ 'required': true,
84
+ 'default': true,
85
+ 'title': true,
86
+ 'description': true,
87
+ 'definitions': true,
88
+ 'dependencies': true
89
+ };
90
+
91
+ var fieldType = {
92
+ 'null': function (x) {
93
+ return x === null;
94
+ },
95
+ 'string': function (x) {
96
+ return typeof x === 'string';
97
+ },
98
+ 'boolean': function (x) {
99
+ return typeof x === 'boolean';
100
+ },
101
+ 'number': function (x) {
102
+ // Use x === x instead of !isNaN(x) for speed
103
+ return typeof x === 'number' && x === x;
104
+ },
105
+ 'integer': function (x) {
106
+ return typeof x === 'number' && x%1 === 0;
107
+ },
108
+ 'object': function (x) {
109
+ return x && typeof x === 'object' && !Array.isArray(x);
110
+ },
111
+ 'array': function (x) {
112
+ return Array.isArray(x);
113
+ },
114
+ 'date': function (x) {
115
+ return x instanceof Date;
116
+ }
117
+ };
118
+
119
+ // missing: uri, date-time, ipv4, ipv6
120
+ var fieldFormat = {
121
+ 'alpha': function (v) {
122
+ return (/^[a-zA-Z]+$/).test(v);
123
+ },
124
+ 'alphanumeric': function (v) {
125
+ return (/^[a-zA-Z0-9]+$/).test(v);
126
+ },
127
+ 'identifier': function (v) {
128
+ return (/^[-_a-zA-Z0-9]+$/).test(v);
129
+ },
130
+ 'hexadecimal': function (v) {
131
+ return (/^[a-fA-F0-9]+$/).test(v);
132
+ },
133
+ 'numeric': function (v) {
134
+ return (/^[0-9]+$/).test(v);
135
+ },
136
+ 'date-time': function (v) {
137
+ return !isNaN(Date.parse(v)) && v.indexOf('/') === -1;
138
+ },
139
+ 'uppercase': function (v) {
140
+ return v === v.toUpperCase();
141
+ },
142
+ 'lowercase': function (v) {
143
+ return v === v.toLowerCase();
144
+ },
145
+ 'hostname': function (v) {
146
+ return v.length < 256 && (/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/).test(v);
147
+ },
148
+ 'uri': function (v) {
149
+ return (/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/).test(v);
150
+ },
151
+ 'email': function (v) { // email, ipv4 and ipv6 adapted from node-validator
152
+ return (/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/).test(v);
153
+ },
154
+ 'ipv4': function (v) {
155
+ if ((/^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$/).test(v)) {
156
+ var parts = v.split('.').sort();
157
+ if (parts[3] <= 255)
158
+ return true;
159
+ }
160
+ return false;
161
+ },
162
+ 'ipv6': function(v) {
163
+ return (/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/).test(v);
164
+ /* return (/^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$/).test(v); */
165
+ }
166
+ };
167
+
168
+ var fieldValidate = {
169
+ 'readOnly': function (v, p) {
170
+ return false;
171
+ },
172
+ // ****** numeric validation ********
173
+ 'minimum': function (v, p, schema) {
174
+ return !(v < p || schema.exclusiveMinimum && v <= p);
175
+ },
176
+ 'maximum': function (v, p, schema) {
177
+ return !(v > p || schema.exclusiveMaximum && v >= p);
178
+ },
179
+ 'multipleOf': function (v, p) {
180
+ return (v/p)%1 === 0 || typeof v !== 'number';
181
+ },
182
+ // ****** string validation ******
183
+ 'pattern': function (v, p) {
184
+ if (typeof v !== 'string')
185
+ return true;
186
+ var pattern, modifiers;
187
+ if (typeof p === 'string')
188
+ pattern=p;
189
+ else {
190
+ pattern=p[0];
191
+ modifiers=p[1];
192
+ }
193
+ var regex = new RegExp(pattern, modifiers);
194
+ return regex.test(v);
195
+ },
196
+ 'minLength': function (v, p) {
197
+ return v.length >= p || typeof v !== 'string';
198
+ },
199
+ 'maxLength': function (v, p) {
200
+ return v.length <= p || typeof v !== 'string';
201
+ },
202
+ // ***** array validation *****
203
+ 'minItems': function (v, p) {
204
+ return v.length >= p || !Array.isArray(v);
205
+ },
206
+ 'maxItems': function (v, p) {
207
+ return v.length <= p || !Array.isArray(v);
208
+ },
209
+ 'uniqueItems': function (v, p) {
210
+ var hash = {}, key;
211
+ for (var i = 0, len = v.length; i < len; i++) {
212
+ key = JSON.stringify(v[i]);
213
+ if (hash.hasOwnProperty(key))
214
+ return false;
215
+ else
216
+ hash[key] = true;
217
+ }
218
+ return true;
219
+ },
220
+ // ***** object validation ****
221
+ 'minProperties': function (v, p) {
222
+ if (typeof v !== 'object')
223
+ return true;
224
+ var count = 0;
225
+ for (var attr in v) if (v.hasOwnProperty(attr)) count = count + 1;
226
+ return count >= p;
227
+ },
228
+ 'maxProperties': function (v, p) {
229
+ if (typeof v !== 'object')
230
+ return true;
231
+ var count = 0;
232
+ for (var attr in v) if (v.hasOwnProperty(attr)) count = count + 1;
233
+ return count <= p;
234
+ },
235
+ // ****** all *****
236
+ 'constant': function (v, p) {
237
+ return JSON.stringify(v) == JSON.stringify(p);
238
+ },
239
+ 'enum': function (v, p) {
240
+ var i, len, vs;
241
+ if (typeof v === 'object') {
242
+ vs = JSON.stringify(v);
243
+ for (i = 0, len = p.length; i < len; i++)
244
+ if (vs === JSON.stringify(p[i]))
245
+ return true;
246
+ } else {
247
+ for (i = 0, len = p.length; i < len; i++)
248
+ if (v === p[i])
249
+ return true;
250
+ }
251
+ return false;
252
+ }
253
+ };
254
+
255
+ var normalizeID = function (id) {
256
+ return id.indexOf("://") === -1 ? id : id.split("#")[0];
257
+ };
258
+
259
+ var resolveURI = function (env, schema_stack, uri) {
260
+ var curschema, components, hash_idx, name;
261
+
262
+ hash_idx = uri.indexOf('#');
263
+
264
+ if (hash_idx === -1) {
265
+ if (!env.schema.hasOwnProperty(uri))
266
+ return null;
267
+ return [env.schema[uri]];
268
+ }
269
+
270
+ if (hash_idx > 0) {
271
+ name = uri.substr(0, hash_idx);
272
+ uri = uri.substr(hash_idx+1);
273
+ if (!env.schema.hasOwnProperty(name)) {
274
+ if (schema_stack && schema_stack[0].id === name)
275
+ schema_stack = [schema_stack[0]];
276
+ else
277
+ return null;
278
+ } else
279
+ schema_stack = [env.schema[name]];
280
+ } else {
281
+ if (!schema_stack)
282
+ return null;
283
+ uri = uri.substr(1);
284
+ }
285
+
286
+ if (uri === '')
287
+ return [schema_stack[0]];
288
+
289
+ if (uri.charAt(0) === '/') {
290
+ uri = uri.substr(1);
291
+ curschema = schema_stack[0];
292
+ components = uri.split('/');
293
+ while (components.length > 0) {
294
+ if (!curschema.hasOwnProperty(components[0]))
295
+ return null;
296
+ curschema = curschema[components[0]];
297
+ schema_stack.push(curschema);
298
+ components.shift();
299
+ }
300
+ return schema_stack;
301
+ } else // FIX: should look for subschemas whose id matches uri
302
+ return null;
303
+ };
304
+
305
+ var resolveObjectRef = function (object_stack, uri) {
306
+ var components, object, last_frame = object_stack.length-1, skip_frames, frame, m = /^(\d+)/.exec(uri);
307
+
308
+ if (m) {
309
+ uri = uri.substr(m[0].length);
310
+ skip_frames = parseInt(m[1], 10);
311
+ if (skip_frames < 0 || skip_frames > last_frame)
312
+ return;
313
+ frame = object_stack[last_frame-skip_frames];
314
+ if (uri === '#')
315
+ return frame.key;
316
+ } else
317
+ frame = object_stack[0];
318
+
319
+ object = frame.object[frame.key];
320
+
321
+ if (uri === '')
322
+ return object;
323
+
324
+ if (uri.charAt(0) === '/') {
325
+ uri = uri.substr(1);
326
+ components = uri.split('/');
327
+ while (components.length > 0) {
328
+ components[0] = components[0].replace(/~1/g, '/').replace(/~0/g, '~');
329
+ if (!object.hasOwnProperty(components[0]))
330
+ return;
331
+ object = object[components[0]];
332
+ components.shift();
333
+ }
334
+ return object;
335
+ } else
336
+ return;
337
+ };
338
+
339
+ var checkValidity = function (env, schema_stack, object_stack, options) {
340
+ var i, len, count, hasProp, hasPattern;
341
+ var p, v, malformed = false, objerrs = {}, objerr, props, matched;
342
+ var sl = schema_stack.length-1, schema = schema_stack[sl], new_stack;
343
+ var ol = object_stack.length-1, object = object_stack[ol].object, name = object_stack[ol].key, prop = object[name];
344
+ var errCount, minErrCount;
345
+
346
+ if (schema.hasOwnProperty('$ref')) {
347
+ schema_stack= resolveURI(env, schema_stack, schema.$ref);
348
+ if (!schema_stack)
349
+ return {'$ref': schema.$ref};
350
+ else
351
+ return checkValidity(env, schema_stack, object_stack, options);
352
+ }
353
+
354
+ if (schema.hasOwnProperty('type')) {
355
+ if (typeof schema.type === 'string') {
356
+ if (options.useCoerce && env.coerceType.hasOwnProperty(schema.type))
357
+ prop = object[name] = env.coerceType[schema.type](prop);
358
+ if (!env.fieldType[schema.type](prop))
359
+ return {'type': schema.type};
360
+ } else {
361
+ malformed = true;
362
+ for (i = 0, len = schema.type.length; i < len && malformed; i++)
363
+ if (env.fieldType[schema.type[i]](prop))
364
+ malformed = false;
365
+ if (malformed)
366
+ return {'type': schema.type};
367
+ }
368
+ }
369
+
370
+ if (schema.hasOwnProperty('allOf')) {
371
+ for (i = 0, len = schema.allOf.length; i < len; i++) {
372
+ objerr = checkValidity(env, schema_stack.concat(schema.allOf[i]), object_stack, options);
373
+ if (objerr)
374
+ return objerr;
375
+ }
376
+ }
377
+
378
+ if (!options.useCoerce && !options.useDefault && !options.removeAdditional) {
379
+ if (schema.hasOwnProperty('oneOf')) {
380
+ minErrCount = Infinity;
381
+ for (i = 0, len = schema.oneOf.length, count = 0; i < len; i++) {
382
+ objerr = checkValidity(env, schema_stack.concat(schema.oneOf[i]), object_stack, options);
383
+ if (!objerr) {
384
+ count = count + 1;
385
+ if (count > 1)
386
+ break;
387
+ } else {
388
+ errCount = objerr.schema ? Object.keys(objerr.schema).length : 1;
389
+ if (errCount < minErrCount) {
390
+ minErrCount = errCount;
391
+ objerrs = objerr;
392
+ }
393
+ }
394
+ }
395
+ if (count > 1)
396
+ return {'oneOf': true};
397
+ else if (count < 1)
398
+ return objerrs;
399
+ objerrs = {};
400
+ }
401
+
402
+ if (schema.hasOwnProperty('anyOf')) {
403
+ objerrs = null;
404
+ minErrCount = Infinity;
405
+ for (i = 0, len = schema.anyOf.length; i < len; i++) {
406
+ objerr = checkValidity(env, schema_stack.concat(schema.anyOf[i]), object_stack, options);
407
+ if (!objerr) {
408
+ objerrs = null;
409
+ break;
410
+ }
411
+ else {
412
+ errCount = objerr.schema ? Object.keys(objerr.schema).length : 1;
413
+ if (errCount < minErrCount) {
414
+ minErrCount = errCount;
415
+ objerrs = objerr;
416
+ }
417
+ }
418
+ }
419
+ if (objerrs)
420
+ return objerrs;
421
+ }
422
+
423
+ if (schema.hasOwnProperty('not')) {
424
+ objerr = checkValidity(env, schema_stack.concat(schema.not), object_stack, options);
425
+ if (!objerr)
426
+ return {'not': true};
427
+ }
428
+ } else {
429
+ if (schema.hasOwnProperty('oneOf')) {
430
+ minErrCount = Infinity;
431
+ for (i = 0, len = schema.oneOf.length, count = 0; i < len; i++) {
432
+ new_stack = clone_stack(object_stack);
433
+ objerr = checkValidity(env, schema_stack.concat(schema.oneOf[i]), new_stack, options);
434
+ if (!objerr) {
435
+ count = count + 1;
436
+ if (count > 1)
437
+ break;
438
+ else
439
+ copy_stack(new_stack, object_stack);
440
+ } else {
441
+ errCount = objerr.schema ? Object.keys(objerr.schema).length : 1;
442
+ if (errCount < minErrCount) {
443
+ minErrCount = errCount;
444
+ objerrs = objerr;
445
+ }
446
+ }
447
+ }
448
+ if (count > 1)
449
+ return {'oneOf': true};
450
+ else if (count < 1)
451
+ return objerrs;
452
+ objerrs = {};
453
+ }
454
+
455
+ if (schema.hasOwnProperty('anyOf')) {
456
+ objerrs = null;
457
+ minErrCount = Infinity;
458
+ for (i = 0, len = schema.anyOf.length; i < len; i++) {
459
+ new_stack = clone_stack(object_stack);
460
+ objerr = checkValidity(env, schema_stack.concat(schema.anyOf[i]), new_stack, options);
461
+ if (!objerr) {
462
+ copy_stack(new_stack, object_stack);
463
+ objerrs = null;
464
+ break;
465
+ }
466
+ else {
467
+ errCount = objerr.schema ? Object.keys(objerr.schema).length : 1;
468
+ if (errCount < minErrCount) {
469
+ minErrCount = errCount;
470
+ objerrs = objerr;
471
+ }
472
+ }
473
+ }
474
+ if (objerrs)
475
+ return objerrs;
476
+ }
477
+
478
+ if (schema.hasOwnProperty('not')) {
479
+ new_stack = clone_stack(object_stack);
480
+ objerr = checkValidity(env, schema_stack.concat(schema.not), new_stack, options);
481
+ if (!objerr)
482
+ return {'not': true};
483
+ }
484
+ }
485
+
486
+ if (schema.hasOwnProperty('dependencies')) {
487
+ for (p in schema.dependencies)
488
+ if (schema.dependencies.hasOwnProperty(p) && prop.hasOwnProperty(p)) {
489
+ if (Array.isArray(schema.dependencies[p])) {
490
+ for (i = 0, len = schema.dependencies[p].length; i < len; i++)
491
+ if (!prop.hasOwnProperty(schema.dependencies[p][i])) {
492
+ return {'dependencies': true};
493
+ }
494
+ } else {
495
+ objerr = checkValidity(env, schema_stack.concat(schema.dependencies[p]), object_stack, options);
496
+ if (objerr)
497
+ return objerr;
498
+ }
499
+ }
500
+ }
501
+
502
+ if (!Array.isArray(prop)) {
503
+ props = [];
504
+ objerrs = {};
505
+ for (p in prop)
506
+ if (prop.hasOwnProperty(p))
507
+ props.push(p);
508
+
509
+ if (options.checkRequired && schema.required) {
510
+ for (i = 0, len = schema.required.length; i < len; i++)
511
+ if (!prop.hasOwnProperty(schema.required[i])) {
512
+ objerrs[schema.required[i]] = {'required': true};
513
+ malformed = true;
514
+ }
515
+ }
516
+
517
+ hasProp = schema.hasOwnProperty('properties');
518
+ hasPattern = schema.hasOwnProperty('patternProperties');
519
+ if (hasProp || hasPattern) {
520
+ i = props.length;
521
+ while (i--) {
522
+ matched = false;
523
+ if (hasProp && schema.properties.hasOwnProperty(props[i])) {
524
+ matched = true;
525
+ objerr = checkValidity(env, schema_stack.concat(schema.properties[props[i]]), object_stack.concat({object: prop, key: props[i]}), options);
526
+ if (objerr !== null) {
527
+ objerrs[props[i]] = objerr;
528
+ malformed = true;
529
+ }
530
+ }
531
+ if (hasPattern) {
532
+ for (p in schema.patternProperties)
533
+ if (schema.patternProperties.hasOwnProperty(p) && props[i].match(p)) {
534
+ matched = true;
535
+ objerr = checkValidity(env, schema_stack.concat(schema.patternProperties[p]), object_stack.concat({object: prop, key: props[i]}), options);
536
+ if (objerr !== null) {
537
+ objerrs[props[i]] = objerr;
538
+ malformed = true;
539
+ }
540
+ }
541
+ }
542
+ if (matched)
543
+ props.splice(i, 1);
544
+ }
545
+ }
546
+
547
+ if (options.useDefault && hasProp && !malformed) {
548
+ for (p in schema.properties)
549
+ if (schema.properties.hasOwnProperty(p) && !prop.hasOwnProperty(p) && schema.properties[p].hasOwnProperty('default'))
550
+ prop[p] = schema.properties[p]['default'];
551
+ }
552
+
553
+ if (options.removeAdditional && hasProp && schema.additionalProperties !== true && typeof schema.additionalProperties !== 'object') {
554
+ for (i = 0, len = props.length; i < len; i++)
555
+ delete prop[props[i]];
556
+ } else {
557
+ if (schema.hasOwnProperty('additionalProperties')) {
558
+ if (typeof schema.additionalProperties === 'boolean') {
559
+ if (!schema.additionalProperties) {
560
+ for (i = 0, len = props.length; i < len; i++) {
561
+ objerrs[props[i]] = {'additional': true};
562
+ malformed = true;
563
+ }
564
+ }
565
+ } else {
566
+ for (i = 0, len = props.length; i < len; i++) {
567
+ objerr = checkValidity(env, schema_stack.concat(schema.additionalProperties), object_stack.concat({object: prop, key: props[i]}), options);
568
+ if (objerr !== null) {
569
+ objerrs[props[i]] = objerr;
570
+ malformed = true;
571
+ }
572
+ }
573
+ }
574
+ }
575
+ }
576
+ if (malformed)
577
+ return {'schema': objerrs};
578
+ } else {
579
+ if (schema.hasOwnProperty('items')) {
580
+ if (Array.isArray(schema.items)) {
581
+ for (i = 0, len = schema.items.length; i < len; i++) {
582
+ objerr = checkValidity(env, schema_stack.concat(schema.items[i]), object_stack.concat({object: prop, key: i}), options);
583
+ if (objerr !== null) {
584
+ objerrs[i] = objerr;
585
+ malformed = true;
586
+ }
587
+ }
588
+ if (prop.length > len && schema.hasOwnProperty('additionalItems')) {
589
+ if (typeof schema.additionalItems === 'boolean') {
590
+ if (!schema.additionalItems)
591
+ return {'additionalItems': true};
592
+ } else {
593
+ for (i = len, len = prop.length; i < len; i++) {
594
+ objerr = checkValidity(env, schema_stack.concat(schema.additionalItems), object_stack.concat({object: prop, key: i}), options);
595
+ if (objerr !== null) {
596
+ objerrs[i] = objerr;
597
+ malformed = true;
598
+ }
599
+ }
600
+ }
601
+ }
602
+ } else {
603
+ for (i = 0, len = prop.length; i < len; i++) {
604
+ objerr = checkValidity(env, schema_stack.concat(schema.items), object_stack.concat({object: prop, key: i}), options);
605
+ if (objerr !== null) {
606
+ objerrs[i] = objerr;
607
+ malformed = true;
608
+ }
609
+ }
610
+ }
611
+ } else if (schema.hasOwnProperty('additionalItems')) {
612
+ if (typeof schema.additionalItems !== 'boolean') {
613
+ for (i = 0, len = prop.length; i < len; i++) {
614
+ objerr = checkValidity(env, schema_stack.concat(schema.additionalItems), object_stack.concat({object: prop, key: i}), options);
615
+ if (objerr !== null) {
616
+ objerrs[i] = objerr;
617
+ malformed = true;
618
+ }
619
+ }
620
+ }
621
+ }
622
+ if (malformed)
623
+ return {'schema': objerrs};
624
+ }
625
+
626
+ for (v in schema) {
627
+ if (schema.hasOwnProperty(v) && !handled.hasOwnProperty(v)) {
628
+ if (v === 'format') {
629
+ if (env.fieldFormat.hasOwnProperty(schema[v]) && !env.fieldFormat[schema[v]](prop, schema, object_stack, options)) {
630
+ objerrs[v] = true;
631
+ malformed = true;
632
+ }
633
+ } else {
634
+ if (env.fieldValidate.hasOwnProperty(v) && !env.fieldValidate[v](prop, schema[v].hasOwnProperty('$data') ? resolveObjectRef(object_stack, schema[v].$data) : schema[v], schema, object_stack, options)) {
635
+ objerrs[v] = true;
636
+ malformed = true;
637
+ }
638
+ }
639
+ }
640
+ }
641
+
642
+ if (malformed)
643
+ return objerrs;
644
+ else
645
+ return null;
646
+ };
647
+
648
+ var defaultOptions = {
649
+ useDefault: false,
650
+ useCoerce: false,
651
+ checkRequired: true,
652
+ removeAdditional: false
653
+ };
654
+
655
+ function Environment() {
656
+ if (!(this instanceof Environment))
657
+ return new Environment();
658
+
659
+ this.coerceType = {};
660
+ this.fieldType = clone(fieldType);
661
+ this.fieldValidate = clone(fieldValidate);
662
+ this.fieldFormat = clone(fieldFormat);
663
+ this.defaultOptions = clone(defaultOptions);
664
+ this.schema = {};
665
+ }
666
+
667
+ Environment.prototype = {
668
+ validate: function (name, object, options) {
669
+ var schema_stack = [name], errors = null, object_stack = [{object: {'__root__': object}, key: '__root__'}];
670
+
671
+ if (typeof name === 'string') {
672
+ schema_stack = resolveURI(this, null, name);
673
+ if (!schema_stack)
674
+ throw new Error('jjv: could not find schema \'' + name + '\'.');
675
+ }
676
+
677
+ if (!options) {
678
+ options = this.defaultOptions;
679
+ } else {
680
+ for (var p in this.defaultOptions)
681
+ if (this.defaultOptions.hasOwnProperty(p) && !options.hasOwnProperty(p))
682
+ options[p] = this.defaultOptions[p];
683
+ }
684
+
685
+ errors = checkValidity(this, schema_stack, object_stack, options);
686
+
687
+ if (errors)
688
+ return {validation: errors.hasOwnProperty('schema') ? errors.schema : errors};
689
+ else
690
+ return null;
691
+ },
692
+
693
+ resolveRef: function (schema_stack, $ref) {
694
+ return resolveURI(this, schema_stack, $ref);
695
+ },
696
+
697
+ addType: function (name, func) {
698
+ this.fieldType[name] = func;
699
+ },
700
+
701
+ addTypeCoercion: function (type, func) {
702
+ this.coerceType[type] = func;
703
+ },
704
+
705
+ addCheck: function (name, func) {
706
+ this.fieldValidate[name] = func;
707
+ },
708
+
709
+ addFormat: function (name, func) {
710
+ this.fieldFormat[name] = func;
711
+ },
712
+
713
+ addSchema: function (name, schema) {
714
+ if (!schema && name) {
715
+ schema = name;
716
+ name = undefined;
717
+ }
718
+ if (schema.hasOwnProperty('id') && typeof schema.id === 'string' && schema.id !== name) {
719
+ if (schema.id.charAt(0) === '/')
720
+ throw new Error('jjv: schema id\'s starting with / are invalid.');
721
+ this.schema[normalizeID(schema.id)] = schema;
722
+ } else if (!name) {
723
+ throw new Error('jjv: schema needs either a name or id attribute.');
724
+ }
725
+ if (name)
726
+ this.schema[normalizeID(name)] = schema;
727
+ }
728
+ };
729
+
730
+ // Export for use in server and client.
731
+ if (typeof module !== 'undefined' && typeof module.exports !== 'undefined')
732
+ module.exports = Environment;
733
+ else if (typeof define === 'function' && define.amd)
734
+ define(function () {return Environment;});
735
+ else
736
+ this.jjv = Environment;
737
+ }).call(this);
738
+
739
+ global.actn.jjv = jjv();