Last active
November 8, 2015 22:51
-
-
Save rosswaycaster/9585844e03f99625507e to your computer and use it in GitHub Desktop.
Replace the contents of file "meteor-client-side.bundle.min.js" with the code below.. If using Ionic, it will be located here: www/lib/meteor-client-side/dist/meteor-client-side.bundle.min.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){var _,exports;(function(){exports={}}).call(this);(function(){(function(){var root=this;var previousUnderscore=root._;var breaker={};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 nativeForEach=ArrayProto.forEach,nativeMap=ArrayProto.map,nativeReduce=ArrayProto.reduce,nativeReduceRight=ArrayProto.reduceRight,nativeFilter=ArrayProto.filter,nativeEvery=ArrayProto.every,nativeSome=ArrayProto.some,nativeIndexOf=ArrayProto.indexOf,nativeLastIndexOf=ArrayProto.lastIndexOf,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.5.2";var _isArguments=function(obj){return toString.call(obj)==="[object Arguments]"};if(!_isArguments(arguments)){_isArguments=function(obj){return!!(obj&&hasOwnProperty.call(obj,"callee")&&typeof obj.callee==="function")}}var looksLikeArray=function(obj){return obj.length===+obj.length&&(_isArguments(obj)||obj.constructor!==Object)};var each=_.each=_.forEach=function(obj,iterator,context){if(obj==null)return;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context)}else if(looksLikeArray(obj)){for(var i=0,length=obj.length;i<length;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return}}else{var keys=_.keys(obj);for(var i=0,length=keys.length;i<length;i++){if(iterator.call(context,obj[keys[i]],keys[i],obj)===breaker)return}}};_.map=_.collect=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeMap&&obj.map===nativeMap)return obj.map(iterator,context);each(obj,function(value,index,list){results.push(iterator.call(context,value,index,list))});return results};var reduceError="Reduce of empty array with no initial value";_.reduce=_.foldl=_.inject=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduce&&obj.reduce===nativeReduce){if(context)iterator=_.bind(iterator,context);return initial?obj.reduce(iterator,memo):obj.reduce(iterator)}each(obj,function(value,index,list){if(!initial){memo=value;initial=true}else{memo=iterator.call(context,memo,value,index,list)}});if(!initial)throw new TypeError(reduceError);return memo};_.reduceRight=_.foldr=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduceRight&&obj.reduceRight===nativeReduceRight){if(context)iterator=_.bind(iterator,context);return initial?obj.reduceRight(iterator,memo):obj.reduceRight(iterator)}var length=obj.length;if(!looksLikeArray(obj)){var keys=_.keys(obj);length=keys.length}each(obj,function(value,index,list){index=keys?keys[--length]:--length;if(!initial){memo=obj[index];initial=true}else{memo=iterator.call(context,memo,obj[index],index,list)}});if(!initial)throw new TypeError(reduceError);return memo};_.find=_.detect=function(obj,iterator,context){var result;any(obj,function(value,index,list){if(iterator.call(context,value,index,list)){result=value;return true}});return result};_.filter=_.select=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeFilter&&obj.filter===nativeFilter)return obj.filter(iterator,context);each(obj,function(value,index,list){if(iterator.call(context,value,index,list))results.push(value)});return results};_.reject=function(obj,iterator,context){return _.filter(obj,function(value,index,list){return!iterator.call(context,value,index,list)},context)};_.every=_.all=function(obj,iterator,context){iterator||(iterator=_.identity);var result=true;if(obj==null)return result;if(nativeEvery&&obj.every===nativeEvery)return obj.every(iterator,context);each(obj,function(value,index,list){if(!(result=result&&iterator.call(context,value,index,list)))return breaker});return!!result};var any=_.some=_.any=function(obj,iterator,context){iterator||(iterator=_.identity);var result=false;if(obj==null)return result;if(nativeSome&&obj.some===nativeSome)return obj.some(iterator,context);each(obj,function(value,index,list){if(result||(result=iterator.call(context,value,index,list)))return breaker});return!!result};_.contains=_.include=function(obj,target){if(obj==null)return false;if(nativeIndexOf&&obj.indexOf===nativeIndexOf)return obj.indexOf(target)!=-1;return any(obj,function(value){return value===target})};_.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,function(value){return value[key]})};_.where=function(obj,attrs,first){if(_.isEmpty(attrs))return first?void 0:[];return _[first?"find":"filter"](obj,function(value){for(var key in attrs){if(attrs[key]!==value[key])return false}return true})};_.findWhere=function(obj,attrs){return _.where(obj,attrs,true)};_.max=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.max.apply(Math,obj)}if(!iterator&&_.isEmpty(obj))return-Infinity;var result={computed:-Infinity,value:-Infinity};each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;computed>result.computed&&(result={value:value,computed:computed})});return result.value};_.min=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.min.apply(Math,obj)}if(!iterator&&_.isEmpty(obj))return Infinity;var result={computed:Infinity,value:Infinity};each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;computed<result.computed&&(result={value:value,computed:computed})});return result.value};_.shuffle=function(obj){var rand;var index=0;var shuffled=[];each(obj,function(value){rand=_.random(index++);shuffled[index-1]=shuffled[rand];shuffled[rand]=value});return shuffled};_.sample=function(obj,n,guard){if(arguments.length<2||guard){return obj[_.random(obj.length-1)]}return _.shuffle(obj).slice(0,Math.max(0,n))};var lookupIterator=function(value){return _.isFunction(value)?value:function(obj){return obj[value]}};_.sortBy=function(obj,value,context){var iterator=lookupIterator(value);return _.pluck(_.map(obj,function(value,index,list){return{value:value,index:index,criteria:iterator.call(context,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,value,context){var result={};var iterator=value==null?_.identity:lookupIterator(value);each(obj,function(value,index){var key=iterator.call(context,value,index,obj);behavior(result,key,value)});return result}};_.groupBy=group(function(result,key,value){(_.has(result,key)?result[key]:result[key]=[]).push(value)});_.indexBy=group(function(result,key,value){result[key]=value});_.countBy=group(function(result,key){_.has(result,key)?result[key]++:result[key]=1});_.sortedIndex=function(array,obj,iterator,context){iterator=iterator==null?_.identity:lookupIterator(iterator);var value=iterator.call(context,obj);var low=0,high=array.length;while(low<high){var mid=low+high>>>1;iterator.call(context,array[mid])<value?low=mid+1:high=mid}return low};_.toArray=function(obj){if(!obj)return[];if(_.isArray(obj))return slice.call(obj);if(looksLikeArray(obj))return _.map(obj,_.identity);return _.values(obj)};_.size=function(obj){if(obj==null)return 0;return looksLikeArray(obj)?obj.length:_.keys(obj).length};_.first=_.head=_.take=function(array,n,guard){if(array==null)return void 0;return n==null||guard?array[0]:slice.call(array,0,n)};_.initial=function(array,n,guard){return slice.call(array,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]}else{return slice.call(array,Math.max(array.length-n,0))}};_.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,output){if(shallow&&_.every(input,_.isArray)){return concat.apply(output,input)}each(input,function(value){if(_.isArray(value)||_.isArguments(value)){shallow?push.apply(output,value):flatten(value,shallow,output)}else{output.push(value)}});return output};_.flatten=function(array,shallow){return flatten(array,shallow,[])};_.without=function(array){return _.difference(array,slice.call(arguments,1))};_.uniq=_.unique=function(array,isSorted,iterator,context){if(_.isFunction(isSorted)){context=iterator;iterator=isSorted;isSorted=false}var initial=iterator?_.map(array,iterator,context):array;var results=[];var seen=[];each(initial,function(value,index){if(isSorted?!index||seen[seen.length-1]!==value:!_.contains(seen,value)){seen.push(value);results.push(array[index])}});return results};_.union=function(){return _.uniq(_.flatten(arguments,true))};_.intersection=function(array){var rest=slice.call(arguments,1);return _.filter(_.uniq(array),function(item){return _.every(rest,function(other){return _.indexOf(other,item)>=0})})};_.difference=function(array){var rest=concat.apply(ArrayProto,slice.call(arguments,1));return _.filter(array,function(value){return!_.contains(rest,value)})};_.zip=function(){var length=_.max(_.pluck(arguments,"length").concat(0));var results=new Array(length);for(var i=0;i<length;i++){results[i]=_.pluck(arguments,""+i)}return results};_.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}}if(nativeIndexOf&&array.indexOf===nativeIndexOf)return array.indexOf(item,isSorted);for(;i<length;i++)if(array[i]===item)return i;return-1};_.lastIndexOf=function(array,item,from){if(array==null)return-1;var hasIndex=from!=null;if(nativeLastIndexOf&&array.lastIndexOf===nativeLastIndexOf){return hasIndex?array.lastIndexOf(item,from):array.lastIndexOf(item)}var i=hasIndex?from:array.length;while(i--)if(array[i]===item)return i;return-1};_.range=function(start,stop,step){if(arguments.length<=1){stop=start||0;start=0}step=arguments[2]||1;var length=Math.max(Math.ceil((stop-start)/step),0);var idx=0;var range=new Array(length);while(idx<length){range[idx++]=start;start+=step}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;args=slice.call(arguments,2);return 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(Object(result)===result)return result;return self}};_.partial=function(func){var args=slice.call(arguments,1);return function(){return func.apply(this,args.concat(slice.call(arguments)))}};_.bindAll=function(obj){var funcs=slice.call(arguments,1);if(funcs.length===0)throw new Error("bindAll must be passed function names");each(funcs,function(f){obj[f]=_.bind(obj[f],obj)});return obj};_.memoize=function(func,hasher){var memo={};hasher||(hasher=_.identity);return function(){var key=hasher.apply(this,arguments);return _.has(memo,key)?memo[key]:memo[key]=func.apply(this,arguments)}};_.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;options||(options={});var later=function(){previous=options.leading===false?0:new Date;timeout=null;result=func.apply(context,args)};return function(){var now=new Date;if(!previous&&options.leading===false)previous=now;var remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0){clearTimeout(timeout);timeout=null;previous=now;result=func.apply(context,args)}else if(!timeout&&options.trailing!==false){timeout=setTimeout(later,remaining)}return result}};_.debounce=function(func,wait,immediate){var timeout,args,context,timestamp,result;return function(){context=this;args=arguments;timestamp=new Date;var later=function(){var last=new Date-timestamp;if(last<wait){timeout=setTimeout(later,wait-last)}else{timeout=null;if(!immediate)result=func.apply(context,args)}};var callNow=immediate&&!timeout;if(!timeout){timeout=setTimeout(later,wait)}if(callNow)result=func.apply(context,args);return result}};_.once=function(func){var ran=false,memo;return function(){if(ran)return memo;ran=true;memo=func.apply(this,arguments);func=null;return memo}};_.wrap=function(func,wrapper){return function(){var args=[func];push.apply(args,arguments);return wrapper.apply(this,args)}};_.compose=function(){var funcs=arguments;return function(){var args=arguments;for(var i=funcs.length-1;i>=0;i--){args=[funcs[i].apply(this,args)]}return args[0]}};_.after=function(times,func){return function(){if(--times<1){return func.apply(this,arguments)}}};_.keys=nativeKeys||function(obj){if(obj!==Object(obj))throw new TypeError("Invalid object");var keys=[];for(var key in obj)if(_.has(obj,key))keys.push(key);return keys};_.values=function(obj){var keys=_.keys(obj);var length=keys.length;var values=new 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=new 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){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){obj[prop]=source[prop]}}});return obj};_.pick=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));each(keys,function(key){if(key in obj)copy[key]=obj[key]});return copy};_.omit=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));for(var key in obj){if(!_.contains(keys,key))copy[key]=obj[key]}return copy};_.defaults=function(obj){each(slice.call(arguments,1),function(source){if(source){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 String]":return a==String(b);case"[object Number]":return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case"[object Date]":case"[object Boolean]":return+a==+b;case"[object RegExp]":return a.source==b.source&&a.global==b.global&&a.multiline==b.multiline&&a.ignoreCase==b.ignoreCase}if(typeof a!="object"||typeof b!="object")return false;var length=aStack.length;while(length--){if(aStack[length]==a)return bStack[length]==b}var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(_.isFunction(aCtor)&&aCtor instanceof aCtor&&_.isFunction(bCtor)&&bCtor instanceof bCtor)){return false}aStack.push(a);bStack.push(b);var size=0,result=true;if(className=="[object Array]"){size=a.length;result=size==b.length;if(result){while(size--){if(!(result=eq(a[size],b[size],aStack,bStack)))break}}}else{for(var key in a){if(_.has(a,key)){size++;if(!(result=_.has(b,key)&&eq(a[key],b[key],aStack,bStack)))break}}if(result){for(key in b){if(_.has(b,key)&&!size--)break}result=!size}}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))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){return obj===Object(obj)};each(["Arguments","Function","String","Number","Date","RegExp"],function(name){_["is"+name]=function(obj){return toString.call(obj)=="[object "+name+"]"}});if(!_.isArguments(arguments)){_.isArguments=function(obj){return!!(obj&&_.has(obj,"callee"))}}if(typeof/./!=="function"){_.isFunction=function(obj){return typeof obj==="function"}}_.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 hasOwnProperty.call(obj,key)};_.noConflict=function(){root._=previousUnderscore;return this};_.identity=function(value){return value};_.times=function(n,iterator,context){var accum=Array(Math.max(0,n));for(var i=0;i<n;i++)accum[i]=iterator.call(context,i);return accum};_.random=function(min,max){if(max==null){max=min;min=0}return min+Math.floor(Math.random()*(max-min+1))};var entityMap={escape:{"&":"&","<":"<",">":">",'"':""","'":"'"}};entityMap.unescape=_.invert(entityMap.escape);var entityRegexes={escape:new RegExp("["+_.keys(entityMap.escape).join("")+"]","g"),unescape:new RegExp("("+_.keys(entityMap.unescape).join("|")+")","g")};_.each(["escape","unescape"],function(method){_[method]=function(string){if(string==null)return"";return(""+string).replace(entityRegexes[method],function(match){return entityMap[method][match]})}});_.result=function(object,property){if(object==null)return void 0;var value=object[property];return _.isFunction(value)?value.call(object):value};_.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.call(this,func.apply(_,args))}})};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"," ":"t","\u2028":"u2028","\u2029":"u2029"};var escaper=/\\|'|\r|\n|\t|\u2028|\u2029/g;_.template=function(text,data,settings){var render;settings=_.defaults({},settings,_.templateSettings);var matcher=new 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,function(match){return"\\"+escapes[match]});if(escape){source+="'+\n((__t=("+escape+"))==null?'':_.escape(__t))+\n'"}if(interpolate){source+="'+\n((__t=("+interpolate+"))==null?'':__t)+\n'"}if(evaluate){source+="';\n"+evaluate+"\n__p+='"}index=offset+match.length;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{render=new Function(settings.variable||"obj","_",source)}catch(e){e.source=source;throw e}if(data)return render(data,_);var template=function(data){return render.call(this,data,_)};template.source="function("+(settings.variable||"obj")+"){\n"+source+"}";return template};_.chain=function(obj){return _(obj).chain()};var result=function(obj){return this._chain?_(obj).chain():obj};_.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.call(this,obj)}});each(["concat","join","slice"],function(name){var method=ArrayProto[name];_.prototype[name]=function(){return result.call(this,method.apply(this._wrapped,arguments))}});_.extend(_.prototype,{chain:function(){this._chain=true;return this},value:function(){return this._wrapped}})}).call(this)}).call(this);(function(){_=exports._}).call(this);if(typeof Package==="undefined")Package={};Package.underscore={_:_}})();(function(){var _=Package.underscore._;var Meteor;(function(){Meteor={isClient:true,isServer:false,isCordova:false};if(typeof __meteor_runtime_config__==="object"&&__meteor_runtime_config__.PUBLIC_SETTINGS){Meteor.settings={"public":__meteor_runtime_config__.PUBLIC_SETTINGS}}}).call(this);(function(){if(Meteor.isServer)var Future=Npm.require("fibers/future");if(typeof __meteor_runtime_config__==="object"&&__meteor_runtime_config__.meteorRelease){Meteor.release=__meteor_runtime_config__.meteorRelease}_.extend(Meteor,{_get:function(obj){for(var i=1;i<arguments.length;i++){if(!(arguments[i]in obj))return undefined;obj=obj[arguments[i]]}return obj},_ensure:function(obj){for(var i=1;i<arguments.length;i++){var key=arguments[i];if(!(key in obj))obj[key]={};obj=obj[key]}return obj},_delete:function(obj){var stack=[obj];var leaf=true;for(var i=1;i<arguments.length-1;i++){var key=arguments[i];if(!(key in obj)){leaf=false;break}obj=obj[key];if(typeof obj!=="object")break;stack.push(obj)}for(var i=stack.length-1;i>=0;i--){var key=arguments[i+1];if(leaf)leaf=false;else for(var other in stack[i][key])return;delete stack[i][key]}},wrapAsync:function(fn,context){return function(){var self=context||this;var newArgs=_.toArray(arguments);var callback;for(var i=newArgs.length-1;i>=0;--i){var arg=newArgs[i];var type=typeof arg;if(type!=="undefined"){if(type==="function"){callback=arg}break}}if(!callback){if(Meteor.isClient){callback=logErr}else{var fut=new Future;callback=fut.resolver()}++i}newArgs[i]=Meteor.bindEnvironment(callback);var result=fn.apply(self,newArgs);return fut?fut.wait():result}},_inherits:function(Child,Parent){for(var key in Parent){if(_.has(Parent,key))Child[key]=Parent[key]}var Middle=function(){this.constructor=Child};Middle.prototype=Parent.prototype;Child.prototype=new Middle;Child.__super__=Parent.prototype;return Child}});var warnedAboutWrapAsync=false;Meteor._wrapAsync=function(fn,context){if(!warnedAboutWrapAsync){Meteor._debug("Meteor._wrapAsync has been renamed to Meteor.wrapAsync");warnedAboutWrapAsync=true}return Meteor.wrapAsync.apply(Meteor,arguments)};function logErr(err){if(err){return Meteor._debug("Exception in callback of async function",err.stack?err.stack:err)}}}).call(this);(function(){"use strict";var global=this;function useSetImmediate(){if(!global.setImmediate)return null;else{var setImmediate=function(fn){global.setImmediate(fn)};setImmediate.implementation="setImmediate";return setImmediate}}function usePostMessage(){if(!global.postMessage||global.importScripts){return null}var postMessageIsAsynchronous=true;var oldOnMessage=global.onmessage;global.onmessage=function(){postMessageIsAsynchronous=false};global.postMessage("","*");global.onmessage=oldOnMessage;if(!postMessageIsAsynchronous)return null;var funcIndex=0;var funcs={};var MESSAGE_PREFIX="Meteor._setImmediate."+Math.random()+".";function isStringAndStartsWith(string,putativeStart){return typeof string==="string"&&string.substring(0,putativeStart.length)===putativeStart}function onGlobalMessage(event){if(event.source===global&&isStringAndStartsWith(event.data,MESSAGE_PREFIX)){var index=event.data.substring(MESSAGE_PREFIX.length);try{if(funcs[index])funcs[index]()}finally{delete funcs[index]}}}if(global.addEventListener){global.addEventListener("message",onGlobalMessage,false)}else{global.attachEvent("onmessage",onGlobalMessage)}var setImmediate=function(fn){++funcIndex;funcs[funcIndex]=fn;global.postMessage(MESSAGE_PREFIX+funcIndex,"*")};setImmediate.implementation="postMessage";return setImmediate}function useTimeout(){var setImmediate=function(fn){global.setTimeout(fn,0)};setImmediate.implementation="setTimeout";return setImmediate}Meteor._setImmediate=useSetImmediate()||usePostMessage()||useTimeout()}).call(this);(function(){var withoutInvocation=function(f){if(Package.ddp){var _CurrentInvocation=Package.ddp.DDP._CurrentInvocation;if(_CurrentInvocation.get()&&_CurrentInvocation.get().isSimulation)throw new Error("Can't set timers inside simulations");return function(){_CurrentInvocation.withValue(null,f)}}else return f};var bindAndCatch=function(context,f){return Meteor.bindEnvironment(withoutInvocation(f),context)};_.extend(Meteor,{setTimeout:function(f,duration){return setTimeout(bindAndCatch("setTimeout callback",f),duration)},setInterval:function(f,duration){return setInterval(bindAndCatch("setInterval callback",f),duration)},clearInterval:function(x){return clearInterval(x)},clearTimeout:function(x){return clearTimeout(x)},defer:function(f){Meteor._setImmediate(bindAndCatch("defer callback",f))}})}).call(this);(function(){Meteor.makeErrorType=function(name,constructor){var errorClass=function(){var self=this;if(Error.captureStackTrace){Error.captureStackTrace(self,errorClass)}else{var e=new Error;e.__proto__=errorClass.prototype;if(e instanceof errorClass)self=e}constructor.apply(self,arguments);self.errorType=name;return self};Meteor._inherits(errorClass,Error);return errorClass};Meteor.Error=Meteor.makeErrorType("Meteor.Error",function(error,reason,details){var self=this;self.error=error;self.reason=reason;self.details=details;if(self.reason)self.message=self.reason+" ["+self.error+"]";else self.message="["+self.error+"]"});Meteor.Error.prototype.clone=function(){var self=this;return new Meteor.Error(self.error,self.reason,self.details)}}).call(this);(function(){Meteor._noYieldsAllowed=function(f){return f()};Meteor._SynchronousQueue=function(){var self=this;self._tasks=[];self._running=false;self._runTimeout=null};_.extend(Meteor._SynchronousQueue.prototype,{runTask:function(task){var self=this;if(!self.safeToRunTask())throw new Error("Could not synchronously run a task from a running task");self._tasks.push(task);var tasks=self._tasks;self._tasks=[];self._running=true;if(self._runTimeout){clearTimeout(self._runTimeout);self._runTimeout=null}try{while(!_.isEmpty(tasks)){var t=tasks.shift();try{t()}catch(e){if(_.isEmpty(tasks)){throw e}else{Meteor._debug("Exception in queued task: "+e.stack)}}}}finally{self._running=false}},queueTask:function(task){var self=this;self._tasks.push(task);if(!self._runTimeout){self._runTimeout=setTimeout(_.bind(self.flush,self),0)}},flush:function(){var self=this;self.runTask(function(){})},drain:function(){var self=this;if(!self.safeToRunTask())return;while(!_.isEmpty(self._tasks)){self.flush()}},safeToRunTask:function(){var self=this;return!self._running}})}).call(this);(function(){var queue=[];var loaded=!Meteor.isCordova&&(document.readyState==="loaded"||document.readyState=="complete");var awaitingEventsCount=1;var ready=function(){awaitingEventsCount--;if(awaitingEventsCount>0)return;loaded=true;var runStartupCallbacks=function(){if(Meteor.isCordova){if(!cordova.plugins||!cordova.plugins.CordovaUpdate){Meteor.setTimeout(runStartupCallbacks,20);return}}while(queue.length)queue.shift()()};runStartupCallbacks()};if(document.addEventListener){document.addEventListener("DOMContentLoaded",ready,false);if(Meteor.isCordova){awaitingEventsCount++;document.addEventListener("deviceready",ready,false)}window.addEventListener("load",ready,false)}else{document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete")ready()});window.attachEvent("load",ready)}Meteor.startup=function(cb){var doScroll=!document.addEventListener&&document.documentElement.doScroll;if(!doScroll||window!==top){if(loaded)cb();else queue.push(cb)}else{try{doScroll("left")}catch(e){setTimeout(function(){Meteor.startup(cb)},50);return}cb()}}}).call(this);(function(){var suppress=0;Meteor._debug=function(){if(suppress){suppress--;return}if(typeof console!=="undefined"&&typeof console.log!=="undefined"){if(arguments.length==0){console.log("")}else{if(typeof console.log.apply==="function"){var allArgumentsOfTypeString=true;for(var i=0;i<arguments.length;i++)if(typeof arguments[i]!=="string")allArgumentsOfTypeString=false;if(allArgumentsOfTypeString)console.log.apply(console,[Array.prototype.join.call(arguments," ")]);else console.log.apply(console,arguments)}else if(typeof Function.prototype.bind==="function"){var log=Function.prototype.bind.call(console.log,console);log.apply(console,arguments)}else{Function.prototype.call.call(console.log,console,Array.prototype.slice.call(arguments))}}}};Meteor._suppress_log=function(count){suppress+=count};Meteor._supressed_log_expected=function(){return suppress!==0}}).call(this);(function(){var nextSlot=0;var currentValues=[];Meteor.EnvironmentVariable=function(){this.slot=nextSlot++};_.extend(Meteor.EnvironmentVariable.prototype,{get:function(){return currentValues[this.slot]},getOrNullIfOutsideFiber:function(){return this.get()},withValue:function(value,func){var saved=currentValues[this.slot];try{currentValues[this.slot]=value;var ret=func()}finally{currentValues[this.slot]=saved}return ret}});Meteor.bindEnvironment=function(func,onException,_this){var boundValues=_.clone(currentValues);if(!onException||typeof onException==="string"){var description=onException||"callback of async function";onException=function(error){Meteor._debug("Exception in "+description+":",error&&error.stack||error)}}return function(){var savedValues=currentValues;try{currentValues=boundValues;var ret=func.apply(_this,_.toArray(arguments))}catch(e){onException(e)}finally{currentValues=savedValues}return ret}};Meteor._nodeCodeMustBeInFiber=function(){}}).call(this);(function(){Meteor.absoluteUrl=function(path,options){if(!options&&typeof path==="object"){options=path;path=undefined}options=_.extend({},Meteor.absoluteUrl.defaultOptions,options||{});var url=options.rootUrl;if(!url)throw new Error("Must pass options.rootUrl or set ROOT_URL in the server environment");if(!/^http[s]?:\/\//i.test(url))url="http://"+url;if(!/\/$/.test(url))url+="/";if(path)url+=path;if(options.secure&&/^http:/.test(url)&&!/http:\/\/localhost[:\/]/.test(url)&&!/http:\/\/127\.0\.0\.1[:\/]/.test(url))url=url.replace(/^http:/,"https:");if(options.replaceLocalhost)url=url.replace(/^http:\/\/localhost([:\/].*)/,"http://127.0.0.1$1");return url};Meteor.absoluteUrl.defaultOptions={};if(typeof __meteor_runtime_config__==="object"&&__meteor_runtime_config__.ROOT_URL)Meteor.absoluteUrl.defaultOptions.rootUrl=__meteor_runtime_config__.ROOT_URL;Meteor._relativeToSiteRootUrl=function(link){if(typeof __meteor_runtime_config__==="object"&&link.substr(0,1)==="/")link=(__meteor_runtime_config__.ROOT_URL_PATH_PREFIX||"")+link;return link}}).call(this);if(typeof Package==="undefined")Package={};Package.meteor={Meteor:Meteor}})();(function(){var Meteor=Package.meteor.Meteor;var Base64;(function(){var BASE_64_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var BASE_64_VALS={};for(var i=0;i<BASE_64_CHARS.length;i++){BASE_64_VALS[BASE_64_CHARS.charAt(i)]=i; | |
}Base64={};Base64.encode=function(array){if(typeof array==="string"){var str=array;array=Base64.newBinary(str.length);for(var i=0;i<str.length;i++){var ch=str.charCodeAt(i);if(ch>255){throw new Error("Not ascii. Base64.encode can only take ascii strings.")}array[i]=ch}}var answer=[];var a=null;var b=null;var c=null;var d=null;for(var i=0;i<array.length;i++){switch(i%3){case 0:a=array[i]>>2&63;b=(array[i]&3)<<4;break;case 1:b=b|array[i]>>4&15;c=(array[i]&15)<<2;break;case 2:c=c|array[i]>>6&3;d=array[i]&63;answer.push(getChar(a));answer.push(getChar(b));answer.push(getChar(c));answer.push(getChar(d));a=null;b=null;c=null;d=null;break}}if(a!=null){answer.push(getChar(a));answer.push(getChar(b));if(c==null)answer.push("=");else answer.push(getChar(c));if(d==null)answer.push("=")}return answer.join("")};var getChar=function(val){return BASE_64_CHARS.charAt(val)};var getVal=function(ch){if(ch==="="){return-1}return BASE_64_VALS[ch]};Base64.newBinary=function(len){if(typeof Uint8Array==="undefined"||typeof ArrayBuffer==="undefined"){var ret=[];for(var i=0;i<len;i++){ret.push(0)}ret.$Uint8ArrayPolyfill=true;return ret}return new Uint8Array(new ArrayBuffer(len))};Base64.decode=function(str){var len=Math.floor(str.length*3/4);if(str.charAt(str.length-1)=="="){len--;if(str.charAt(str.length-2)=="=")len--}var arr=Base64.newBinary(len);var one=null;var two=null;var three=null;var j=0;for(var i=0;i<str.length;i++){var c=str.charAt(i);var v=getVal(c);switch(i%4){case 0:if(v<0)throw new Error("invalid base64 string");one=v<<2;break;case 1:if(v<0)throw new Error("invalid base64 string");one=one|v>>4;arr[j++]=one;two=(v&15)<<4;break;case 2:if(v>=0){two=two|v>>2;arr[j++]=two;three=(v&3)<<6}break;case 3:if(v>=0){arr[j++]=three|v}break}}return arr}}).call(this);if(typeof Package==="undefined")Package={};Package.base64={Base64:Base64}})();(function(){var Meteor=Package.meteor.Meteor;var JSON;(function(){if(window.JSON)JSON=window.JSON}).call(this);(function(){if(typeof JSON!=="object"){JSON={}}(function(){"use strict";function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()}).call(this);if(typeof Package==="undefined")Package={};Package.json={JSON:JSON}})();(function(){var Meteor=Package.meteor.Meteor;var JSON=Package.json.JSON;var _=Package.underscore._;var Base64=Package.base64.Base64;var EJSON,EJSONTest;(function(){EJSON={};EJSONTest={};var customTypes={};EJSON.addType=function(name,factory){if(_.has(customTypes,name))throw new Error("Type "+name+" already present");customTypes[name]=factory};var isInfOrNan=function(obj){return _.isNaN(obj)||obj===Infinity||obj===-Infinity};var builtinConverters=[{matchJSONValue:function(obj){return _.has(obj,"$date")&&_.size(obj)===1},matchObject:function(obj){return obj instanceof Date},toJSONValue:function(obj){return{$date:obj.getTime()}},fromJSONValue:function(obj){return new Date(obj.$date)}},{matchJSONValue:function(obj){return _.has(obj,"$InfNaN")&&_.size(obj)===1},matchObject:isInfOrNan,toJSONValue:function(obj){var sign;if(_.isNaN(obj))sign=0;else if(obj===Infinity)sign=1;else sign=-1;return{$InfNaN:sign}},fromJSONValue:function(obj){return obj.$InfNaN/0}},{matchJSONValue:function(obj){return _.has(obj,"$binary")&&_.size(obj)===1},matchObject:function(obj){return typeof Uint8Array!=="undefined"&&obj instanceof Uint8Array||obj&&_.has(obj,"$Uint8ArrayPolyfill")},toJSONValue:function(obj){return{$binary:Base64.encode(obj)}},fromJSONValue:function(obj){return Base64.decode(obj.$binary)}},{matchJSONValue:function(obj){return _.has(obj,"$escape")&&_.size(obj)===1},matchObject:function(obj){if(_.isEmpty(obj)||_.size(obj)>2){return false}return _.any(builtinConverters,function(converter){return converter.matchJSONValue(obj)})},toJSONValue:function(obj){var newObj={};_.each(obj,function(value,key){newObj[key]=EJSON.toJSONValue(value)});return{$escape:newObj}},fromJSONValue:function(obj){var newObj={};_.each(obj.$escape,function(value,key){newObj[key]=EJSON.fromJSONValue(value)});return newObj}},{matchJSONValue:function(obj){return _.has(obj,"$type")&&_.has(obj,"$value")&&_.size(obj)===2},matchObject:function(obj){return EJSON._isCustomType(obj)},toJSONValue:function(obj){var jsonValue=Meteor._noYieldsAllowed(function(){return obj.toJSONValue()});return{$type:obj.typeName(),$value:jsonValue}},fromJSONValue:function(obj){var typeName=obj.$type;if(!_.has(customTypes,typeName))throw new Error("Custom EJSON type "+typeName+" is not defined");var converter=customTypes[typeName];return Meteor._noYieldsAllowed(function(){return converter(obj.$value)})}}];EJSON._isCustomType=function(obj){return obj&&typeof obj.toJSONValue==="function"&&typeof obj.typeName==="function"&&_.has(customTypes,obj.typeName())};var adjustTypesToJSONValue=EJSON._adjustTypesToJSONValue=function(obj){if(obj===null)return null;var maybeChanged=toJSONValueHelper(obj);if(maybeChanged!==undefined)return maybeChanged;if(typeof obj!=="object")return obj;_.each(obj,function(value,key){if(typeof value!=="object"&&value!==undefined&&!isInfOrNan(value))return;var changed=toJSONValueHelper(value);if(changed){obj[key]=changed;return}adjustTypesToJSONValue(value)});return obj};var toJSONValueHelper=function(item){for(var i=0;i<builtinConverters.length;i++){var converter=builtinConverters[i];if(converter.matchObject(item)){return converter.toJSONValue(item)}}return undefined};EJSON.toJSONValue=function(item){var changed=toJSONValueHelper(item);if(changed!==undefined)return changed;if(typeof item==="object"){item=EJSON.clone(item);adjustTypesToJSONValue(item)}return item};var adjustTypesFromJSONValue=EJSON._adjustTypesFromJSONValue=function(obj){if(obj===null)return null;var maybeChanged=fromJSONValueHelper(obj);if(maybeChanged!==obj)return maybeChanged;if(typeof obj!=="object")return obj;_.each(obj,function(value,key){if(typeof value==="object"){var changed=fromJSONValueHelper(value);if(value!==changed){obj[key]=changed;return}adjustTypesFromJSONValue(value)}});return obj};var fromJSONValueHelper=function(value){if(typeof value==="object"&&value!==null){if(_.size(value)<=2&&_.all(value,function(v,k){return typeof k==="string"&&k.substr(0,1)==="$"})){for(var i=0;i<builtinConverters.length;i++){var converter=builtinConverters[i];if(converter.matchJSONValue(value)){return converter.fromJSONValue(value)}}}}return value};EJSON.fromJSONValue=function(item){var changed=fromJSONValueHelper(item);if(changed===item&&typeof item==="object"){item=EJSON.clone(item);adjustTypesFromJSONValue(item);return item}else{return changed}};EJSON.stringify=function(item,options){var json=EJSON.toJSONValue(item);if(options&&(options.canonical||options.indent)){return EJSON._canonicalStringify(json,options)}else{return JSON.stringify(json)}};EJSON.parse=function(item){if(typeof item!=="string")throw new Error("EJSON.parse argument should be a string");return EJSON.fromJSONValue(JSON.parse(item))};EJSON.isBinary=function(obj){return!!(typeof Uint8Array!=="undefined"&&obj instanceof Uint8Array||obj&&obj.$Uint8ArrayPolyfill)};EJSON.equals=function(a,b,options){var i;var keyOrderSensitive=!!(options&&options.keyOrderSensitive);if(a===b)return true;if(_.isNaN(a)&&_.isNaN(b))return true;if(!a||!b)return false;if(!(typeof a==="object"&&typeof b==="object"))return false;if(a instanceof Date&&b instanceof Date)return a.valueOf()===b.valueOf();if(EJSON.isBinary(a)&&EJSON.isBinary(b)){if(a.length!==b.length)return false;for(i=0;i<a.length;i++){if(a[i]!==b[i])return false}return true}if(typeof a.equals==="function")return a.equals(b,options);if(typeof b.equals==="function")return b.equals(a,options);if(a instanceof Array){if(!(b instanceof Array))return false;if(a.length!==b.length)return false;for(i=0;i<a.length;i++){if(!EJSON.equals(a[i],b[i],options))return false}return true}switch(EJSON._isCustomType(a)+EJSON._isCustomType(b)){case 1:return false;case 2:return EJSON.equals(EJSON.toJSONValue(a),EJSON.toJSONValue(b))}var ret;if(keyOrderSensitive){var bKeys=[];_.each(b,function(val,x){bKeys.push(x)});i=0;ret=_.all(a,function(val,x){if(i>=bKeys.length){return false}if(x!==bKeys[i]){return false}if(!EJSON.equals(val,b[bKeys[i]],options)){return false}i++;return true});return ret&&i===bKeys.length}else{i=0;ret=_.all(a,function(val,key){if(!_.has(b,key)){return false}if(!EJSON.equals(val,b[key],options)){return false}i++;return true});return ret&&_.size(b)===i}};EJSON.clone=function(v){var ret;if(typeof v!=="object")return v;if(v===null)return null;if(v instanceof Date)return new Date(v.getTime());if(v instanceof RegExp)return v;if(EJSON.isBinary(v)){ret=EJSON.newBinary(v.length);for(var i=0;i<v.length;i++){ret[i]=v[i]}return ret}if(_.isArray(v)||_.isArguments(v)){ret=[];for(i=0;i<v.length;i++)ret[i]=EJSON.clone(v[i]);return ret}if(typeof v.clone==="function"){return v.clone()}if(EJSON._isCustomType(v)){return EJSON.fromJSONValue(EJSON.clone(EJSON.toJSONValue(v)),true)}ret={};_.each(v,function(value,key){ret[key]=EJSON.clone(value)});return ret};EJSON.newBinary=Base64.newBinary}).call(this);(function(){function quote(string){return JSON.stringify(string)}var str=function(key,holder,singleIndent,outerIndent,canonical){var i;var k;var v;var length;var innerIndent=outerIndent;var partial;var value=holder[key];switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":return String(value);case"object":if(!value){return"null"}innerIndent=outerIndent+singleIndent;partial=[];if(_.isArray(value)||_.isArguments(value)){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value,singleIndent,innerIndent,canonical)||"null"}if(partial.length===0){v="[]"}else if(innerIndent){v="[\n"+innerIndent+partial.join(",\n"+innerIndent)+"\n"+outerIndent+"]"}else{v="["+partial.join(",")+"]"}return v}var keys=_.keys(value);if(canonical)keys=keys.sort();_.each(keys,function(k){v=str(k,value,singleIndent,innerIndent,canonical);if(v){partial.push(quote(k)+(innerIndent?": ":":")+v)}});if(partial.length===0){v="{}"}else if(innerIndent){v="{\n"+innerIndent+partial.join(",\n"+innerIndent)+"\n"+outerIndent+"}"}else{v="{"+partial.join(",")+"}"}return v}};EJSON._canonicalStringify=function(value,options){options=_.extend({indent:"",canonical:false},options);if(options.indent===true){options.indent=" "}else if(typeof options.indent==="number"){var newIndent="";for(var i=0;i<options.indent;i++){newIndent+=" "}options.indent=newIndent}return str("",{"":value},options.indent,"",options.canonical)}}).call(this);if(typeof Package==="undefined")Package={};Package.ejson={EJSON:EJSON,EJSONTest:EJSONTest}})();(function(){var Meteor=Package.meteor.Meteor;var _=Package.underscore._;var EJSON=Package.ejson.EJSON;var check,Match;(function(){var currentArgumentChecker=new Meteor.EnvironmentVariable;check=function(value,pattern){var argChecker=currentArgumentChecker.getOrNullIfOutsideFiber();if(argChecker)argChecker.checking(value);try{checkSubtree(value,pattern)}catch(err){if(err instanceof Match.Error&&err.path)err.message+=" in field "+err.path;throw err}};Match={Optional:function(pattern){return new Optional(pattern)},OneOf:function(){return new OneOf(_.toArray(arguments))},Any:["__any__"],Where:function(condition){return new Where(condition)},ObjectIncluding:function(pattern){return new ObjectIncluding(pattern)},ObjectWithValues:function(pattern){return new ObjectWithValues(pattern)},Integer:["__integer__"],Error:Meteor.makeErrorType("Match.Error",function(msg){this.message="Match error: "+msg;this.path="";this.sanitizedError=new Meteor.Error(400,"Match failed")}),test:function(value,pattern){try{checkSubtree(value,pattern);return true}catch(e){if(e instanceof Match.Error)return false;throw e}},_failIfArgumentsAreNotAllChecked:function(f,context,args,description){var argChecker=new ArgumentChecker(args,description);var result=currentArgumentChecker.withValue(argChecker,function(){return f.apply(context,args)});argChecker.throwUnlessAllArgumentsHaveBeenChecked();return result}};var Optional=function(pattern){this.pattern=pattern};var OneOf=function(choices){if(_.isEmpty(choices))throw new Error("Must provide at least one choice to Match.OneOf");this.choices=choices};var Where=function(condition){this.condition=condition};var ObjectIncluding=function(pattern){this.pattern=pattern};var ObjectWithValues=function(pattern){this.pattern=pattern};var typeofChecks=[[String,"string"],[Number,"number"],[Boolean,"boolean"],[undefined,"undefined"]];var checkSubtree=function(value,pattern){if(pattern===Match.Any)return;for(var i=0;i<typeofChecks.length;++i){if(pattern===typeofChecks[i][0]){if(typeof value===typeofChecks[i][1])return;throw new Match.Error("Expected "+typeofChecks[i][1]+", got "+typeof value)}}if(pattern===null){if(value===null)return;throw new Match.Error("Expected null, got "+EJSON.stringify(value))}if(typeof pattern==="string"||typeof pattern==="number"){if(value===pattern)return;throw new Match.Error("Expected "+pattern+", got "+EJSON.stringify(value))}if(pattern===Match.Integer){if(typeof value==="number"&&(value|0)===value)return;throw new Match.Error("Expected Integer, got "+(value instanceof Object?EJSON.stringify(value):value))}if(pattern===Object)pattern=Match.ObjectIncluding({});if(pattern instanceof Array){if(pattern.length!==1)throw Error("Bad pattern: arrays must have one type element"+EJSON.stringify(pattern));if(!_.isArray(value)&&!_.isArguments(value)){throw new Match.Error("Expected array, got "+EJSON.stringify(value))}_.each(value,function(valueElement,index){try{checkSubtree(valueElement,pattern[0])}catch(err){if(err instanceof Match.Error){err.path=_prependPath(index,err.path)}throw err}});return}if(pattern instanceof Where){if(pattern.condition(value))return;throw new Match.Error("Failed Match.Where validation")}if(pattern instanceof Optional)pattern=Match.OneOf(undefined,pattern.pattern);if(pattern instanceof OneOf){for(var i=0;i<pattern.choices.length;++i){try{checkSubtree(value,pattern.choices[i]);return}catch(err){if(!(err instanceof Match.Error))throw err}}throw new Match.Error("Failed Match.OneOf or Match.Optional validation")}if(pattern instanceof Function){if(value instanceof pattern)return;throw new Match.Error("Expected "+(pattern.name||"particular constructor"))}var unknownKeysAllowed=false;var unknownKeyPattern;if(pattern instanceof ObjectIncluding){unknownKeysAllowed=true;pattern=pattern.pattern}if(pattern instanceof ObjectWithValues){unknownKeysAllowed=true;unknownKeyPattern=[pattern.pattern];pattern={}}if(typeof pattern!=="object")throw Error("Bad pattern: unknown pattern type");if(typeof value!=="object")throw new Match.Error("Expected object, got "+typeof value);if(value===null)throw new Match.Error("Expected object, got null");if(value.constructor!==Object)throw new Match.Error("Expected plain object");var requiredPatterns={};var optionalPatterns={};_.each(pattern,function(subPattern,key){if(subPattern instanceof Optional)optionalPatterns[key]=subPattern.pattern;else requiredPatterns[key]=subPattern});_.each(value,function(subValue,key){try{if(_.has(requiredPatterns,key)){checkSubtree(subValue,requiredPatterns[key]);delete requiredPatterns[key]}else if(_.has(optionalPatterns,key)){checkSubtree(subValue,optionalPatterns[key])}else{if(!unknownKeysAllowed)throw new Match.Error("Unknown key");if(unknownKeyPattern){checkSubtree(subValue,unknownKeyPattern[0])}}}catch(err){if(err instanceof Match.Error)err.path=_prependPath(key,err.path);throw err}});_.each(requiredPatterns,function(subPattern,key){throw new Match.Error("Missing key '"+key+"'")})};var ArgumentChecker=function(args,description){var self=this;self.args=_.clone(args);self.args.reverse();self.description=description};_.extend(ArgumentChecker.prototype,{checking:function(value){var self=this;if(self._checkingOneValue(value))return;if(_.isArray(value)||_.isArguments(value)){_.each(value,_.bind(self._checkingOneValue,self))}},_checkingOneValue:function(value){var self=this;for(var i=0;i<self.args.length;++i){if(value===self.args[i]||_.isNaN(value)&&_.isNaN(self.args[i])){self.args.splice(i,1);return true}}return false},throwUnlessAllArgumentsHaveBeenChecked:function(){var self=this;if(!_.isEmpty(self.args))throw new Error("Did not check() all arguments during "+self.description)}});var _jsKeywords=["do","if","in","for","let","new","try","var","case","else","enum","eval","false","null","this","true","void","with","break","catch","class","const","super","throw","while","yield","delete","export","import","public","return","static","switch","typeof","default","extends","finally","package","private","continue","debugger","function","arguments","interface","protected","implements","instanceof"];var _prependPath=function(key,base){if(typeof key==="number"||key.match(/^[0-9]+$/))key="["+key+"]";else if(!key.match(/^[a-z_$][0-9a-z_$]*$/i)||_.contains(_jsKeywords,key))key=JSON.stringify([key]);if(base&&base[0]!=="[")return key+"."+base;return key+base}}).call(this);if(typeof Package==="undefined")Package={};Package.check={check:check,Match:Match}})();(function(){var Meteor=Package.meteor.Meteor;var _=Package.underscore._;var Random;(function(){if(Meteor.isServer)var nodeCrypto=Npm.require("crypto");var Alea=function(){function Mash(){var n=4022871197;var mash=function(data){data=data.toString();for(var i=0;i<data.length;i++){n+=data.charCodeAt(i);var h=.02519603282416938*n;n=h>>>0;h-=n;h*=n;n=h>>>0;h-=n;n+=h*4294967296}return(n>>>0)*2.3283064365386963e-10};mash.version="Mash 0.9";return mash}return function(args){var s0=0;var s1=0;var s2=0;var c=1;if(args.length==0){args=[+new Date]}var mash=Mash();s0=mash(" ");s1=mash(" ");s2=mash(" ");for(var i=0;i<args.length;i++){s0-=mash(args[i]);if(s0<0){s0+=1}s1-=mash(args[i]);if(s1<0){s1+=1}s2-=mash(args[i]);if(s2<0){s2+=1}}mash=null;var random=function(){var t=2091639*s0+c*2.3283064365386963e-10;s0=s1;s1=s2;return s2=t-(c=t|0)};random.uint32=function(){return random()*4294967296};random.fract53=function(){return random()+(random()*2097152|0)*1.1102230246251565e-16};random.version="Alea 0.9";random.args=args;return random}(Array.prototype.slice.call(arguments))};var UNMISTAKABLE_CHARS="23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz";var BASE64_CHARS="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+"0123456789-_";var RandomGenerator=function(seedArray){var self=this;if(seedArray!==undefined)self.alea=Alea.apply(null,seedArray)};RandomGenerator.prototype.fraction=function(){var self=this;if(self.alea){return self.alea()}else if(nodeCrypto){var numerator=parseInt(self.hexString(8),16);return numerator*2.3283064365386963e-10}else if(typeof window!=="undefined"&&window.crypto&&window.crypto.getRandomValues){var array=new Uint32Array(1);window.crypto.getRandomValues(array);return array[0]*2.3283064365386963e-10}else{throw new Error("No random generator available")}};RandomGenerator.prototype.hexString=function(digits){var self=this;if(nodeCrypto&&!self.alea){var numBytes=Math.ceil(digits/2);var bytes;try{bytes=nodeCrypto.randomBytes(numBytes)}catch(e){bytes=nodeCrypto.pseudoRandomBytes(numBytes)}var result=bytes.toString("hex");return result.substring(0,digits)}else{var hexDigits=[];for(var i=0;i<digits;++i){hexDigits.push(self.choice("0123456789abcdef"))}return hexDigits.join("")}};RandomGenerator.prototype._randomString=function(charsCount,alphabet){var self=this;var digits=[];for(var i=0;i<charsCount;i++){digits[i]=self.choice(alphabet)}return digits.join("")};RandomGenerator.prototype.id=function(charsCount){var self=this;if(charsCount===undefined)charsCount=17;return self._randomString(charsCount,UNMISTAKABLE_CHARS)};RandomGenerator.prototype.secret=function(charsCount){var self=this;if(charsCount===undefined)charsCount=43;return self._randomString(charsCount,BASE64_CHARS)};RandomGenerator.prototype.choice=function(arrayOrString){var index=Math.floor(this.fraction()*arrayOrString.length);if(typeof arrayOrString==="string")return arrayOrString.substr(index,1);else return arrayOrString[index]};var height=typeof window!=="undefined"&&window.innerHeight||typeof document!=="undefined"&&document.documentElement&&document.documentElement.clientHeight||typeof document!=="undefined"&&document.body&&document.body.clientHeight||1;var width=typeof window!=="undefined"&&window.innerWidth||typeof document!=="undefined"&&document.documentElement&&document.documentElement.clientWidth||typeof document!=="undefined"&&document.body&&document.body.clientWidth||1;var agent=typeof navigator!=="undefined"&&navigator.userAgent||"";if(nodeCrypto||typeof window!=="undefined"&&window.crypto&&window.crypto.getRandomValues)Random=new RandomGenerator;else Random=new RandomGenerator([new Date,height,width,agent,Math.random()]);Random.createWithSeeds=function(){if(arguments.length===0){throw new Error("No seeds were provided")}return new RandomGenerator(arguments)}}).call(this);(function(){Meteor.uuid=function(){var HEX_DIGITS="0123456789abcdef";var s=[];for(var i=0;i<36;i++){s[i]=Random.choice(HEX_DIGITS)}s[14]="4";s[19]=HEX_DIGITS.substr(parseInt(s[19],16)&3|8,1);s[8]=s[13]=s[18]=s[23]="-";var uuid=s.join("");return uuid}}).call(this);if(typeof Package==="undefined")Package={};Package.random={Random:Random}})();(function(){var Meteor=Package.meteor.Meteor;var Tracker,Deps;(function(){Tracker={};Tracker.active=false;Tracker.currentComputation=null;Tracker._computations={};var setCurrentComputation=function(c){Tracker.currentComputation=c;Tracker.active=!!c};var _debugFunc=function(){return typeof Meteor!=="undefined"?Meteor._debug:typeof console!=="undefined"&&console.error?function(){console.error.apply(console,arguments)}:function(){}};var _maybeSupressMoreLogs=function(messagesLength){if(typeof Meteor!=="undefined"){if(Meteor._supressed_log_expected()){Meteor._suppress_log(messagesLength-1)}}};var _throwOrLog=function(from,e){if(throwFirstError){throw e}else{var printArgs=["Exception from Tracker "+from+" function:"];if(e.stack&&e.message&&e.name){var idx=e.stack.indexOf(e.message);if(idx<0||idx>e.name.length+2){var message=e.name+": "+e.message;printArgs.push(message)}}printArgs.push(e.stack);_maybeSupressMoreLogs(printArgs.length);for(var i=0;i<printArgs.length;i++){_debugFunc()(printArgs[i])}}};var withNoYieldsAllowed=function(f){if(typeof Meteor==="undefined"||Meteor.isClient){return f}else{return function(){var args=arguments;Meteor._noYieldsAllowed(function(){f.apply(null,args)})}}};var nextId=1;var pendingComputations=[];var willFlush=false;var inFlush=false;var inCompute=false;var throwFirstError=false;var afterFlushCallbacks=[];var requireFlush=function(){if(!willFlush){if(typeof Meteor!=="undefined")Meteor._setImmediate(Tracker._runFlush);else setTimeout(Tracker._runFlush,0);willFlush=true}};var constructingComputation=false;Tracker.Computation=function(f,parent,onError){if(!constructingComputation)throw new Error("Tracker.Computation constructor is private; use Tracker.autorun");constructingComputation=false;var self=this;self.stopped=false;self.invalidated=false;self.firstRun=true;self._id=nextId++;self._onInvalidateCallbacks=[];self._parent=parent;self._func=f;self._onError=onError;self._recomputing=false;Tracker._computations[self._id]=self;var errored=true;try{self._compute();errored=false}finally{self.firstRun=false;if(errored)self.stop()}};Tracker.Computation.prototype.onInvalidate=function(f){var self=this;if(typeof f!=="function")throw new Error("onInvalidate requires a function");if(self.invalidated){Tracker.nonreactive(function(){withNoYieldsAllowed(f)(self)})}else{self._onInvalidateCallbacks.push(f)}};Tracker.Computation.prototype.invalidate=function(){var self=this;if(!self.invalidated){if(!self._recomputing&&!self.stopped){requireFlush();pendingComputations.push(this)}self.invalidated=true;for(var i=0,f;f=self._onInvalidateCallbacks[i];i++){Tracker.nonreactive(function(){withNoYieldsAllowed(f)(self)})}self._onInvalidateCallbacks=[]}};Tracker.Computation.prototype.stop=function(){if(!this.stopped){this.stopped=true;this.invalidate();delete Tracker._computations[this._id]}};Tracker.Computation.prototype._compute=function(){var self=this;self.invalidated=false;var previous=Tracker.currentComputation;setCurrentComputation(self);var previousInCompute=inCompute;inCompute=true;try{withNoYieldsAllowed(self._func)(self)}finally{setCurrentComputation(previous);inCompute=previousInCompute}};Tracker.Computation.prototype._needsRecompute=function(){var self=this;return self.invalidated&&!self.stopped};Tracker.Computation.prototype._recompute=function(){var self=this;self._recomputing=true;try{if(self._needsRecompute()){try{self._compute()}catch(e){if(self._onError){self._onError(e)}else{_throwOrLog("recompute",e)}}}}finally{self._recomputing=false}};Tracker.Dependency=function(){this._dependentsById={}};Tracker.Dependency.prototype.depend=function(computation){if(!computation){if(!Tracker.active)return false;computation=Tracker.currentComputation}var self=this;var id=computation._id;if(!(id in self._dependentsById)){self._dependentsById[id]=computation;computation.onInvalidate(function(){delete self._dependentsById[id]});return true}return false};Tracker.Dependency.prototype.changed=function(){var self=this;for(var id in self._dependentsById)self._dependentsById[id].invalidate()};Tracker.Dependency.prototype.hasDependents=function(){var self=this;for(var id in self._dependentsById)return true;return false};Tracker.flush=function(options){Tracker._runFlush({finishSynchronously:true,throwFirstError:options&&options._throwFirstError})};Tracker._runFlush=function(options){if(inFlush)throw new Error("Can't call Tracker.flush while flushing");if(inCompute)throw new Error("Can't flush inside Tracker.autorun");options=options||{};inFlush=true;willFlush=true;throwFirstError=!!options.throwFirstError;var recomputedCount=0;var finishedTry=false;try{while(pendingComputations.length||afterFlushCallbacks.length){while(pendingComputations.length){var comp=pendingComputations.shift();comp._recompute();if(comp._needsRecompute()){pendingComputations.unshift(comp)}if(!options.finishSynchronously&&++recomputedCount>1e3){finishedTry=true;return}}if(afterFlushCallbacks.length){var func=afterFlushCallbacks.shift();try{func()}catch(e){_throwOrLog("afterFlush",e)}}}finishedTry=true}finally{if(!finishedTry){inFlush=false;Tracker._runFlush({finishSynchronously:options.finishSynchronously,throwFirstError:false})}willFlush=false;inFlush=false;if(pendingComputations.length||afterFlushCallbacks.length){if(options.finishSynchronously){throw new Error("still have more to do?")}setTimeout(requireFlush,10)}}};Tracker.autorun=function(f,options){if(typeof f!=="function")throw new Error("Tracker.autorun requires a function argument");options=options||{};constructingComputation=true;var c=new Tracker.Computation(f,Tracker.currentComputation,options.onError);if(Tracker.active)Tracker.onInvalidate(function(){c.stop()});return c};Tracker.nonreactive=function(f){var previous=Tracker.currentComputation;setCurrentComputation(null);try{return f()}finally{setCurrentComputation(previous)}};Tracker.onInvalidate=function(f){if(!Tracker.active)throw new Error("Tracker.onInvalidate requires a currentComputation");Tracker.currentComputation.onInvalidate(f)};Tracker.afterFlush=function(f){afterFlushCallbacks.push(f);requireFlush()}}).call(this);(function(){Meteor.flush=Tracker.flush;Meteor.autorun=Tracker.autorun;Meteor.autosubscribe=Tracker.autorun;Tracker.depend=function(d){return d.depend()};Deps=Tracker}).call(this);if(typeof Package==="undefined")Package={};Package.tracker={Tracker:Tracker,Deps:Deps}})();(function(){var Meteor=Package.meteor.Meteor;var _=Package.underscore._;var Random=Package.random.Random;var Retry;(function(){Retry=function(options){var self=this;_.extend(self,_.defaults(_.clone(options||{}),{baseTimeout:1e3,exponent:2.2,maxTimeout:5*6e4,minTimeout:10,minCount:2,fuzz:.5}));self.retryTimer=null};_.extend(Retry.prototype,{clear:function(){var self=this;if(self.retryTimer)clearTimeout(self.retryTimer);self.retryTimer=null},_timeout:function(count){var self=this;if(count<self.minCount)return self.minTimeout;var timeout=Math.min(self.maxTimeout,self.baseTimeout*Math.pow(self.exponent,count));timeout=timeout*(Random.fraction()*self.fuzz+(1-self.fuzz/2));return timeout},retryLater:function(count,fn){var self=this;var timeout=self._timeout(count);if(self.retryTimer)clearTimeout(self.retryTimer);self.retryTimer=Meteor.setTimeout(fn,timeout);return timeout}})}).call(this);if(typeof Package==="undefined")Package={};Package.retry={Retry:Retry}})();(function(){var Meteor=Package.meteor.Meteor;var _=Package.underscore._;var JSON=Package.json.JSON;var EJSON=Package.ejson.EJSON;var IdMap;(function(){IdMap=function(idStringify,idParse){ | |
var self=this;self._map={};self._idStringify=idStringify||JSON.stringify;self._idParse=idParse||JSON.parse};_.extend(IdMap.prototype,{get:function(id){var self=this;var key=self._idStringify(id);return self._map[key]},set:function(id,value){var self=this;var key=self._idStringify(id);self._map[key]=value},remove:function(id){var self=this;var key=self._idStringify(id);delete self._map[key]},has:function(id){var self=this;var key=self._idStringify(id);return _.has(self._map,key)},empty:function(){var self=this;return _.isEmpty(self._map)},clear:function(){var self=this;self._map={}},forEach:function(iterator){var self=this;var keys=_.keys(self._map);for(var i=0;i<keys.length;i++){var breakIfFalse=iterator.call(null,self._map[keys[i]],self._idParse(keys[i]));if(breakIfFalse===false)return}},size:function(){var self=this;return _.size(self._map)},setDefault:function(id,def){var self=this;var key=self._idStringify(id);if(_.has(self._map,key))return self._map[key];self._map[key]=def;return def},clone:function(){var self=this;var clone=new IdMap(self._idStringify,self._idParse);self.forEach(function(value,id){clone.set(id,EJSON.clone(value))});return clone}})}).call(this);if(typeof Package==="undefined")Package={};Package["id-map"]={IdMap:IdMap}})();(function(){var Meteor=Package.meteor.Meteor;var _=Package.underscore._;var OrderedDict;(function(){var element=function(key,value,next,prev){return{key:key,value:value,next:next,prev:prev}};OrderedDict=function(){var self=this;self._dict={};self._first=null;self._last=null;self._size=0;var args=_.toArray(arguments);self._stringify=function(x){return x};if(typeof args[0]==="function")self._stringify=args.shift();_.each(args,function(kv){self.putBefore(kv[0],kv[1],null)})};_.extend(OrderedDict.prototype,{_k:function(key){return" "+this._stringify(key)},empty:function(){var self=this;return!self._first},size:function(){var self=this;return self._size},_linkEltIn:function(elt){var self=this;if(!elt.next){elt.prev=self._last;if(self._last)self._last.next=elt;self._last=elt}else{elt.prev=elt.next.prev;elt.next.prev=elt;if(elt.prev)elt.prev.next=elt}if(self._first===null||self._first===elt.next)self._first=elt},_linkEltOut:function(elt){var self=this;if(elt.next)elt.next.prev=elt.prev;if(elt.prev)elt.prev.next=elt.next;if(elt===self._last)self._last=elt.prev;if(elt===self._first)self._first=elt.next},putBefore:function(key,item,before){var self=this;if(self._dict[self._k(key)])throw new Error("Item "+key+" already present in OrderedDict");var elt=before?element(key,item,self._dict[self._k(before)]):element(key,item,null);if(elt.next===undefined)throw new Error("could not find item to put this one before");self._linkEltIn(elt);self._dict[self._k(key)]=elt;self._size++},append:function(key,item){var self=this;self.putBefore(key,item,null)},remove:function(key){var self=this;var elt=self._dict[self._k(key)];if(elt===undefined)throw new Error("Item "+key+" not present in OrderedDict");self._linkEltOut(elt);self._size--;delete self._dict[self._k(key)];return elt.value},get:function(key){var self=this;if(self.has(key))return self._dict[self._k(key)].value;return undefined},has:function(key){var self=this;return _.has(self._dict,self._k(key))},forEach:function(iter){var self=this;var i=0;var elt=self._first;while(elt!==null){var b=iter(elt.value,elt.key,i);if(b===OrderedDict.BREAK)return;elt=elt.next;i++}},first:function(){var self=this;if(self.empty())return undefined;return self._first.key},firstValue:function(){var self=this;if(self.empty())return undefined;return self._first.value},last:function(){var self=this;if(self.empty())return undefined;return self._last.key},lastValue:function(){var self=this;if(self.empty())return undefined;return self._last.value},prev:function(key){var self=this;if(self.has(key)){var elt=self._dict[self._k(key)];if(elt.prev)return elt.prev.key}return null},next:function(key){var self=this;if(self.has(key)){var elt=self._dict[self._k(key)];if(elt.next)return elt.next.key}return null},moveBefore:function(key,before){var self=this;var elt=self._dict[self._k(key)];var eltBefore=before?self._dict[self._k(before)]:null;if(elt===undefined)throw new Error("Item to move is not present");if(eltBefore===undefined){throw new Error("Could not find element to move this one before")}if(eltBefore===elt.next)return;self._linkEltOut(elt);elt.next=eltBefore;self._linkEltIn(elt)},indexOf:function(key){var self=this;var ret=null;self.forEach(function(v,k,i){if(self._k(k)===self._k(key)){ret=i;return OrderedDict.BREAK}return undefined});return ret},_checkRep:function(){var self=this;_.each(self._dict,function(k,v){if(v.next===v)throw new Error("Next is a loop");if(v.prev===v)throw new Error("Prev is a loop")})}});OrderedDict.BREAK={"break":true}}).call(this);if(typeof Package==="undefined")Package={};Package["ordered-dict"]={OrderedDict:OrderedDict}})();(function(){var Meteor=Package.meteor.Meteor;var GeoJSON,module;(function(){module={exports:{}}}).call(this);(function(){(function(){var gju={};if(typeof module!=="undefined"&&module.exports){module.exports=gju}gju.lineStringsIntersect=function(l1,l2){var intersects=[];for(var i=0;i<=l1.coordinates.length-2;++i){for(var j=0;j<=l2.coordinates.length-2;++j){var a1={x:l1.coordinates[i][1],y:l1.coordinates[i][0]},a2={x:l1.coordinates[i+1][1],y:l1.coordinates[i+1][0]},b1={x:l2.coordinates[j][1],y:l2.coordinates[j][0]},b2={x:l2.coordinates[j+1][1],y:l2.coordinates[j+1][0]},ua_t=(b2.x-b1.x)*(a1.y-b1.y)-(b2.y-b1.y)*(a1.x-b1.x),ub_t=(a2.x-a1.x)*(a1.y-b1.y)-(a2.y-a1.y)*(a1.x-b1.x),u_b=(b2.y-b1.y)*(a2.x-a1.x)-(b2.x-b1.x)*(a2.y-a1.y);if(u_b!=0){var ua=ua_t/u_b,ub=ub_t/u_b;if(0<=ua&&ua<=1&&0<=ub&&ub<=1){intersects.push({type:"Point",coordinates:[a1.x+ua*(a2.x-a1.x),a1.y+ua*(a2.y-a1.y)]})}}}}if(intersects.length==0)intersects=false;return intersects};function boundingBoxAroundPolyCoords(coords){var xAll=[],yAll=[];for(var i=0;i<coords[0].length;i++){xAll.push(coords[0][i][1]);yAll.push(coords[0][i][0])}xAll=xAll.sort(function(a,b){return a-b});yAll=yAll.sort(function(a,b){return a-b});return[[xAll[0],yAll[0]],[xAll[xAll.length-1],yAll[yAll.length-1]]]}gju.pointInBoundingBox=function(point,bounds){return!(point.coordinates[1]<bounds[0][0]||point.coordinates[1]>bounds[1][0]||point.coordinates[0]<bounds[0][1]||point.coordinates[0]>bounds[1][1])};function pnpoly(x,y,coords){var vert=[[0,0]];for(var i=0;i<coords.length;i++){for(var j=0;j<coords[i].length;j++){vert.push(coords[i][j])}vert.push([0,0])}var inside=false;for(var i=0,j=vert.length-1;i<vert.length;j=i++){if(vert[i][0]>y!=vert[j][0]>y&&x<(vert[j][1]-vert[i][1])*(y-vert[i][0])/(vert[j][0]-vert[i][0])+vert[i][1])inside=!inside}return inside}gju.pointInPolygon=function(p,poly){var coords=poly.type=="Polygon"?[poly.coordinates]:poly.coordinates;var insideBox=false;for(var i=0;i<coords.length;i++){if(gju.pointInBoundingBox(p,boundingBoxAroundPolyCoords(coords[i])))insideBox=true}if(!insideBox)return false;var insidePoly=false;for(var i=0;i<coords.length;i++){if(pnpoly(p.coordinates[1],p.coordinates[0],coords[i]))insidePoly=true}return insidePoly};gju.numberToRadius=function(number){return number*Math.PI/180};gju.numberToDegree=function(number){return number*180/Math.PI};gju.drawCircle=function(radiusInMeters,centerPoint,steps){var center=[centerPoint.coordinates[1],centerPoint.coordinates[0]],dist=radiusInMeters/1e3/6371,radCenter=[gju.numberToRadius(center[0]),gju.numberToRadius(center[1])],steps=steps||15,poly=[[center[0],center[1]]];for(var i=0;i<steps;i++){var brng=2*Math.PI*i/steps;var lat=Math.asin(Math.sin(radCenter[0])*Math.cos(dist)+Math.cos(radCenter[0])*Math.sin(dist)*Math.cos(brng));var lng=radCenter[1]+Math.atan2(Math.sin(brng)*Math.sin(dist)*Math.cos(radCenter[0]),Math.cos(dist)-Math.sin(radCenter[0])*Math.sin(lat));poly[i]=[];poly[i][1]=gju.numberToDegree(lat);poly[i][0]=gju.numberToDegree(lng)}return{type:"Polygon",coordinates:[poly]}};gju.rectangleCentroid=function(rectangle){var bbox=rectangle.coordinates[0];var xmin=bbox[0][0],ymin=bbox[0][1],xmax=bbox[2][0],ymax=bbox[2][1];var xwidth=xmax-xmin;var ywidth=ymax-ymin;return{type:"Point",coordinates:[xmin+xwidth/2,ymin+ywidth/2]}};gju.pointDistance=function(pt1,pt2){var lon1=pt1.coordinates[0],lat1=pt1.coordinates[1],lon2=pt2.coordinates[0],lat2=pt2.coordinates[1],dLat=gju.numberToRadius(lat2-lat1),dLon=gju.numberToRadius(lon2-lon1),a=Math.pow(Math.sin(dLat/2),2)+Math.cos(gju.numberToRadius(lat1))*Math.cos(gju.numberToRadius(lat2))*Math.pow(Math.sin(dLon/2),2),c=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));return 6371*c*1e3},gju.geometryWithinRadius=function(geometry,center,radius){if(geometry.type=="Point"){return gju.pointDistance(geometry,center)<=radius}else if(geometry.type=="LineString"||geometry.type=="Polygon"){var point={};var coordinates;if(geometry.type=="Polygon"){coordinates=geometry.coordinates[0]}else{coordinates=geometry.coordinates}for(var i in coordinates){point.coordinates=coordinates[i];if(gju.pointDistance(point,center)>radius){return false}}}return true};gju.area=function(polygon){var area=0;var points=polygon.coordinates[0];var j=points.length-1;var p1,p2;for(var i=0;i<points.length;j=i++){var p1={x:points[i][1],y:points[i][0]};var p2={x:points[j][1],y:points[j][0]};area+=p1.x*p2.y;area-=p1.y*p2.x}area/=2;return area},gju.centroid=function(polygon){var f,x=0,y=0;var points=polygon.coordinates[0];var j=points.length-1;var p1,p2;for(var i=0;i<points.length;j=i++){var p1={x:points[i][1],y:points[i][0]};var p2={x:points[j][1],y:points[j][0]};f=p1.x*p2.y-p2.x*p1.y;x+=(p1.x+p2.x)*f;y+=(p1.y+p2.y)*f}f=gju.area(polygon)*6;return{type:"Point",coordinates:[y/f,x/f]}},gju.simplify=function(source,kink){kink=kink||20;source=source.map(function(o){return{lng:o.coordinates[0],lat:o.coordinates[1]}});var n_source,n_stack,n_dest,start,end,i,sig;var dev_sqr,max_dev_sqr,band_sqr;var x12,y12,d12,x13,y13,d13,x23,y23,d23;var F=Math.PI/180*.5;var index=new Array;var sig_start=new Array;var sig_end=new Array;if(source.length<3)return source;n_source=source.length;band_sqr=kink*360/(2*Math.PI*6378137);band_sqr*=band_sqr;n_dest=0;sig_start[0]=0;sig_end[0]=n_source-1;n_stack=1;while(n_stack>0){start=sig_start[n_stack-1];end=sig_end[n_stack-1];n_stack--;if(end-start>1){x12=source[end].lng()-source[start].lng();y12=source[end].lat()-source[start].lat();if(Math.abs(x12)>180)x12=360-Math.abs(x12);x12*=Math.cos(F*(source[end].lat()+source[start].lat()));d12=x12*x12+y12*y12;for(i=start+1,sig=start,max_dev_sqr=-1;i<end;i++){x13=source[i].lng()-source[start].lng();y13=source[i].lat()-source[start].lat();if(Math.abs(x13)>180)x13=360-Math.abs(x13);x13*=Math.cos(F*(source[i].lat()+source[start].lat()));d13=x13*x13+y13*y13;x23=source[i].lng()-source[end].lng();y23=source[i].lat()-source[end].lat();if(Math.abs(x23)>180)x23=360-Math.abs(x23);x23*=Math.cos(F*(source[i].lat()+source[end].lat()));d23=x23*x23+y23*y23;if(d13>=d12+d23)dev_sqr=d23;else if(d23>=d12+d13)dev_sqr=d13;else dev_sqr=(x13*y12-y13*x12)*(x13*y12-y13*x12)/d12;if(dev_sqr>max_dev_sqr){sig=i;max_dev_sqr=dev_sqr}}if(max_dev_sqr<band_sqr){index[n_dest]=start;n_dest++}else{n_stack++;sig_start[n_stack-1]=sig;sig_end[n_stack-1]=end;n_stack++;sig_start[n_stack-1]=start;sig_end[n_stack-1]=sig}}else{index[n_dest]=start;n_dest++}}index[n_dest]=n_source-1;n_dest++;var r=new Array;for(var i=0;i<n_dest;i++)r.push(source[index[i]]);return r.map(function(o){return{type:"Point",coordinates:[o.lng,o.lat]}})};gju.destinationPoint=function(pt,brng,dist){dist=dist/6371;brng=gju.numberToRadius(brng);var lat1=gju.numberToRadius(pt.coordinates[0]);var lon1=gju.numberToRadius(pt.coordinates[1]);var lat2=Math.asin(Math.sin(lat1)*Math.cos(dist)+Math.cos(lat1)*Math.sin(dist)*Math.cos(brng));var lon2=lon1+Math.atan2(Math.sin(brng)*Math.sin(dist)*Math.cos(lat1),Math.cos(dist)-Math.sin(lat1)*Math.sin(lat2));lon2=(lon2+3*Math.PI)%(2*Math.PI)-Math.PI;return{type:"Point",coordinates:[gju.numberToDegree(lat2),gju.numberToDegree(lon2)]}}})()}).call(this);(function(){GeoJSON=module.exports}).call(this);if(typeof Package==="undefined")Package={};Package["geojson-utils"]={GeoJSON:GeoJSON}})();(function(){var Meteor=Package.meteor.Meteor;var _=Package.underscore._;var JSON=Package.json.JSON;var EJSON=Package.ejson.EJSON;var IdMap=Package["id-map"].IdMap;var OrderedDict=Package["ordered-dict"].OrderedDict;var Tracker=Package.tracker.Tracker;var Deps=Package.tracker.Deps;var Random=Package.random.Random;var GeoJSON=Package["geojson-utils"].GeoJSON;var LocalCollection,Minimongo,MinimongoTest,MinimongoError,isArray,isPlainObject,isIndexable,isOperatorObject,isNumericKey,regexpElementMatcher,equalityElementMatcher,ELEMENT_OPERATORS,makeLookupFunction,expandArraysInBranches,projectionDetails,pathsToTree;(function(){LocalCollection=function(name){var self=this;self.name=name;self._docs=new LocalCollection._IdMap;self._observeQueue=new Meteor._SynchronousQueue;self.next_qid=1;self.queries={};self._savedOriginals=null;self.paused=false};Minimongo={};MinimongoTest={};LocalCollection._applyChanges=function(doc,changeFields){_.each(changeFields,function(value,key){if(value===undefined)delete doc[key];else doc[key]=value})};MinimongoError=function(message){var e=new Error(message);e.name="MinimongoError";return e};LocalCollection.prototype.find=function(selector,options){if(arguments.length===0)selector={};return new LocalCollection.Cursor(this,selector,options)};LocalCollection.Cursor=function(collection,selector,options){var self=this;if(!options)options={};self.collection=collection;self.sorter=null;if(LocalCollection._selectorIsId(selector)){self._selectorId=selector;self.matcher=new Minimongo.Matcher(selector)}else{self._selectorId=undefined;self.matcher=new Minimongo.Matcher(selector);if(self.matcher.hasGeoQuery()||options.sort){self.sorter=new Minimongo.Sorter(options.sort||[],{matcher:self.matcher})}}self.skip=options.skip;self.limit=options.limit;self.fields=options.fields;self._projectionFn=LocalCollection._compileProjection(self.fields||{});self._transform=LocalCollection.wrapTransform(options.transform);if(typeof Tracker!=="undefined")self.reactive=options.reactive===undefined?true:options.reactive};LocalCollection.Cursor.prototype.rewind=function(){};LocalCollection.prototype.findOne=function(selector,options){if(arguments.length===0)selector={};options=options||{};options.limit=1;return this.find(selector,options).fetch()[0]};LocalCollection.Cursor.prototype.forEach=function(callback,thisArg){var self=this;var objects=self._getRawObjects({ordered:true});if(self.reactive){self._depend({addedBefore:true,removed:true,changed:true,movedBefore:true})}_.each(objects,function(elt,i){elt=self._projectionFn(elt);if(self._transform)elt=self._transform(elt);callback.call(thisArg,elt,i,self)})};LocalCollection.Cursor.prototype.getTransform=function(){return this._transform};LocalCollection.Cursor.prototype.map=function(callback,thisArg){var self=this;var res=[];self.forEach(function(doc,index){res.push(callback.call(thisArg,doc,index,self))});return res};LocalCollection.Cursor.prototype.fetch=function(){var self=this;var res=[];self.forEach(function(doc){res.push(doc)});return res};LocalCollection.Cursor.prototype.count=function(){var self=this;if(self.reactive)self._depend({added:true,removed:true},true);return self._getRawObjects({ordered:true}).length};LocalCollection.Cursor.prototype._publishCursor=function(sub){var self=this;if(!self.collection.name)throw new Error("Can't publish a cursor from a collection without a name.");var collection=self.collection.name;return Mongo.Collection._publishCursor(self,sub,collection)};LocalCollection.Cursor.prototype._getCollectionName=function(){var self=this;return self.collection.name};LocalCollection._observeChangesCallbacksAreOrdered=function(callbacks){if(callbacks.added&&callbacks.addedBefore)throw new Error("Please specify only one of added() and addedBefore()");return!!(callbacks.addedBefore||callbacks.movedBefore)};LocalCollection._observeCallbacksAreOrdered=function(callbacks){if(callbacks.addedAt&&callbacks.added)throw new Error("Please specify only one of added() and addedAt()");if(callbacks.changedAt&&callbacks.changed)throw new Error("Please specify only one of changed() and changedAt()");if(callbacks.removed&&callbacks.removedAt)throw new Error("Please specify only one of removed() and removedAt()");return!!(callbacks.addedAt||callbacks.movedTo||callbacks.changedAt||callbacks.removedAt)};LocalCollection.ObserveHandle=function(){};_.extend(LocalCollection.Cursor.prototype,{observe:function(options){var self=this;return LocalCollection._observeFromObserveChanges(self,options)},observeChanges:function(options){var self=this;var ordered=LocalCollection._observeChangesCallbacksAreOrdered(options);if(!options._allow_unordered&&!ordered&&(self.skip||self.limit))throw new Error("must use ordered observe (ie, 'addedBefore' instead of 'added') with skip or limit");if(self.fields&&(self.fields._id===0||self.fields._id===false))throw Error("You may not observe a cursor with {fields: {_id: 0}}");var query={matcher:self.matcher,sorter:ordered&&self.sorter,distances:self.matcher.hasGeoQuery()&&ordered&&new LocalCollection._IdMap,resultsSnapshot:null,ordered:ordered,cursor:self,projectionFn:self._projectionFn};var qid;if(self.reactive){qid=self.collection.next_qid++;self.collection.queries[qid]=query}query.results=self._getRawObjects({ordered:ordered,distances:query.distances});if(self.collection.paused)query.resultsSnapshot=ordered?[]:new LocalCollection._IdMap;var wrapCallback=function(f){if(!f)return function(){};return function(){var context=this;var args=arguments;if(self.collection.paused)return;self.collection._observeQueue.queueTask(function(){f.apply(context,args)})}};query.added=wrapCallback(options.added);query.changed=wrapCallback(options.changed);query.removed=wrapCallback(options.removed);if(ordered){query.addedBefore=wrapCallback(options.addedBefore);query.movedBefore=wrapCallback(options.movedBefore)}if(!options._suppress_initial&&!self.collection.paused){var each=ordered?_.bind(_.each,null,query.results):_.bind(query.results.forEach,query.results);each(function(doc){var fields=EJSON.clone(doc);delete fields._id;if(ordered)query.addedBefore(doc._id,self._projectionFn(fields),null);query.added(doc._id,self._projectionFn(fields))})}var handle=new LocalCollection.ObserveHandle;_.extend(handle,{collection:self.collection,stop:function(){if(self.reactive)delete self.collection.queries[qid]}});if(self.reactive&&Tracker.active){Tracker.onInvalidate(function(){handle.stop()})}self.collection._observeQueue.drain();return handle}});LocalCollection.Cursor.prototype._getRawObjects=function(options){var self=this;options=options||{};var results=options.ordered?[]:new LocalCollection._IdMap;if(self._selectorId!==undefined){if(self.skip)return results;var selectedDoc=self.collection._docs.get(self._selectorId);if(selectedDoc){if(options.ordered)results.push(selectedDoc);else results.set(self._selectorId,selectedDoc)}return results}var distances;if(self.matcher.hasGeoQuery()&&options.ordered){if(options.distances){distances=options.distances;distances.clear()}else{distances=new LocalCollection._IdMap}}self.collection._docs.forEach(function(doc,id){var matchResult=self.matcher.documentMatches(doc);if(matchResult.result){if(options.ordered){results.push(doc);if(distances&&matchResult.distance!==undefined)distances.set(id,matchResult.distance)}else{results.set(id,doc)}}if(self.limit&&!self.skip&&!self.sorter&&results.length===self.limit)return false;return true});if(!options.ordered)return results;if(self.sorter){var comparator=self.sorter.getComparator({distances:distances});results.sort(comparator)}var idx_start=self.skip||0;var idx_end=self.limit?self.limit+idx_start:results.length;return results.slice(idx_start,idx_end)};LocalCollection.Cursor.prototype._depend=function(changers,_allow_unordered){var self=this;if(Tracker.active){var v=new Tracker.Dependency;v.depend();var notifyChange=_.bind(v.changed,v);var options={_suppress_initial:true,_allow_unordered:_allow_unordered};_.each(["added","changed","removed","addedBefore","movedBefore"],function(fnName){if(changers[fnName])options[fnName]=notifyChange});self.observeChanges(options)}};LocalCollection.prototype.insert=function(doc,callback){var self=this;doc=EJSON.clone(doc);if(!_.has(doc,"_id")){doc._id=LocalCollection._useOID?new LocalCollection._ObjectID:Random.id()}var id=doc._id;if(self._docs.has(id))throw MinimongoError("Duplicate _id '"+id+"'");self._saveOriginal(id,undefined);self._docs.set(id,doc);var queriesToRecompute=[];for(var qid in self.queries){var query=self.queries[qid];var matchResult=query.matcher.documentMatches(doc);if(matchResult.result){if(query.distances&&matchResult.distance!==undefined)query.distances.set(id,matchResult.distance);if(query.cursor.skip||query.cursor.limit)queriesToRecompute.push(qid);else LocalCollection._insertInResults(query,doc)}}_.each(queriesToRecompute,function(qid){if(self.queries[qid])self._recomputeResults(self.queries[qid])});self._observeQueue.drain();if(callback)Meteor.defer(function(){callback(null,id)});return id};LocalCollection.prototype._eachPossiblyMatchingDoc=function(selector,f){var self=this;var specificIds=LocalCollection._idsMatchedBySelector(selector);if(specificIds){for(var i=0;i<specificIds.length;++i){var id=specificIds[i];var doc=self._docs.get(id);if(doc){var breakIfFalse=f(doc,id);if(breakIfFalse===false)break}}}else{self._docs.forEach(f)}};LocalCollection.prototype.remove=function(selector,callback){var self=this;if(self.paused&&!self._savedOriginals&&EJSON.equals(selector,{})){var result=self._docs.size();self._docs.clear();_.each(self.queries,function(query){if(query.ordered){query.results=[]}else{query.results.clear()}});if(callback){Meteor.defer(function(){callback(null,result)})}return result}var matcher=new Minimongo.Matcher(selector);var remove=[];self._eachPossiblyMatchingDoc(selector,function(doc,id){if(matcher.documentMatches(doc).result)remove.push(id)});var queriesToRecompute=[];var queryRemove=[];for(var i=0;i<remove.length;i++){var removeId=remove[i];var removeDoc=self._docs.get(removeId);_.each(self.queries,function(query,qid){if(query.matcher.documentMatches(removeDoc).result){if(query.cursor.skip||query.cursor.limit)queriesToRecompute.push(qid);else queryRemove.push({qid:qid,doc:removeDoc})}});self._saveOriginal(removeId,removeDoc);self._docs.remove(removeId)}_.each(queryRemove,function(remove){var query=self.queries[remove.qid];if(query){query.distances&&query.distances.remove(remove.doc._id);LocalCollection._removeFromResults(query,remove.doc)}});_.each(queriesToRecompute,function(qid){var query=self.queries[qid];if(query)self._recomputeResults(query)});self._observeQueue.drain();result=remove.length;if(callback)Meteor.defer(function(){callback(null,result)});return result};LocalCollection.prototype.update=function(selector,mod,options,callback){var self=this;if(!callback&&options instanceof Function){callback=options;options=null}if(!options)options={};var matcher=new Minimongo.Matcher(selector);var qidToOriginalResults={};_.each(self.queries,function(query,qid){if((query.cursor.skip||query.cursor.limit)&&!self.paused)qidToOriginalResults[qid]=EJSON.clone(query.results)});var recomputeQids={};var updateCount=0;self._eachPossiblyMatchingDoc(selector,function(doc,id){var queryResult=matcher.documentMatches(doc);if(queryResult.result){self._saveOriginal(id,doc);self._modifyAndNotify(doc,mod,recomputeQids,queryResult.arrayIndices);++updateCount;if(!options.multi)return false}return true});_.each(recomputeQids,function(dummy,qid){var query=self.queries[qid];if(query)self._recomputeResults(query,qidToOriginalResults[qid])});self._observeQueue.drain();var insertedId;if(updateCount===0&&options.upsert){var newDoc=LocalCollection._removeDollarOperators(selector);LocalCollection._modify(newDoc,mod,{isInsert:true});if(!newDoc._id&&options.insertedId)newDoc._id=options.insertedId;insertedId=self.insert(newDoc);updateCount=1}var result;if(options._returnObject){result={numberAffected:updateCount};if(insertedId!==undefined)result.insertedId=insertedId}else{result=updateCount}if(callback)Meteor.defer(function(){callback(null,result)});return result};LocalCollection.prototype.upsert=function(selector,mod,options,callback){var self=this;if(!callback&&typeof options==="function"){callback=options;options={}}return self.update(selector,mod,_.extend({},options,{upsert:true,_returnObject:true}),callback)};LocalCollection.prototype._modifyAndNotify=function(doc,mod,recomputeQids,arrayIndices){var self=this;var matched_before={};for(var qid in self.queries){var query=self.queries[qid];if(query.ordered){matched_before[qid]=query.matcher.documentMatches(doc).result}else{matched_before[qid]=query.results.has(doc._id)}}var old_doc=EJSON.clone(doc);LocalCollection._modify(doc,mod,{arrayIndices:arrayIndices});for(qid in self.queries){query=self.queries[qid];var before=matched_before[qid];var afterMatch=query.matcher.documentMatches(doc);var after=afterMatch.result;if(after&&query.distances&&afterMatch.distance!==undefined)query.distances.set(doc._id,afterMatch.distance);if(query.cursor.skip||query.cursor.limit){if(before||after)recomputeQids[qid]=true}else if(before&&!after){LocalCollection._removeFromResults(query,doc)}else if(!before&&after){LocalCollection._insertInResults(query,doc)}else if(before&&after){LocalCollection._updateInResults(query,doc,old_doc)}}};LocalCollection._insertInResults=function(query,doc){var fields=EJSON.clone(doc);delete fields._id;if(query.ordered){if(!query.sorter){query.addedBefore(doc._id,query.projectionFn(fields),null);query.results.push(doc)}else{var i=LocalCollection._insertInSortedList(query.sorter.getComparator({distances:query.distances}),query.results,doc);var next=query.results[i+1];if(next)next=next._id;else next=null;query.addedBefore(doc._id,query.projectionFn(fields),next)}query.added(doc._id,query.projectionFn(fields))}else{query.added(doc._id,query.projectionFn(fields));query.results.set(doc._id,doc)}};LocalCollection._removeFromResults=function(query,doc){if(query.ordered){var i=LocalCollection._findInOrderedResults(query,doc);query.removed(doc._id);query.results.splice(i,1)}else{var id=doc._id;query.removed(doc._id);query.results.remove(id)}};LocalCollection._updateInResults=function(query,doc,old_doc){if(!EJSON.equals(doc._id,old_doc._id))throw new Error("Can't change a doc's _id while updating");var projectionFn=query.projectionFn;var changedFields=LocalCollection._makeChangedFields(projectionFn(doc),projectionFn(old_doc));if(!query.ordered){if(!_.isEmpty(changedFields)){query.changed(doc._id,changedFields);query.results.set(doc._id,doc)}return}var orig_idx=LocalCollection._findInOrderedResults(query,doc);if(!_.isEmpty(changedFields))query.changed(doc._id,changedFields);if(!query.sorter)return;query.results.splice(orig_idx,1);var new_idx=LocalCollection._insertInSortedList(query.sorter.getComparator({distances:query.distances}),query.results,doc);if(orig_idx!==new_idx){var next=query.results[new_idx+1];if(next)next=next._id;else next=null;query.movedBefore&&query.movedBefore(doc._id,next)}};LocalCollection.prototype._recomputeResults=function(query,oldResults){var self=this;if(!self.paused&&!oldResults)oldResults=query.results;if(query.distances)query.distances.clear();query.results=query.cursor._getRawObjects({ordered:query.ordered,distances:query.distances});if(!self.paused){LocalCollection._diffQueryChanges(query.ordered,oldResults,query.results,query,{projectionFn:query.projectionFn})}};LocalCollection._findInOrderedResults=function(query,doc){if(!query.ordered)throw new Error("Can't call _findInOrderedResults on unordered query");for(var i=0;i<query.results.length;i++)if(query.results[i]===doc)return i;throw Error("object missing from query")};LocalCollection._binarySearch=function(cmp,array,value){var first=0,rangeLength=array.length;while(rangeLength>0){var halfRange=Math.floor(rangeLength/2);if(cmp(value,array[first+halfRange])>=0){first+=halfRange+1;rangeLength-=halfRange+1}else{rangeLength=halfRange}}return first};LocalCollection._insertInSortedList=function(cmp,array,value){if(array.length===0){array.push(value);return 0}var idx=LocalCollection._binarySearch(cmp,array,value);array.splice(idx,0,value);return idx};LocalCollection.prototype.saveOriginals=function(){var self=this;if(self._savedOriginals)throw new Error("Called saveOriginals twice without retrieveOriginals");self._savedOriginals=new LocalCollection._IdMap};LocalCollection.prototype.retrieveOriginals=function(){var self=this;if(!self._savedOriginals)throw new Error("Called retrieveOriginals without saveOriginals");var originals=self._savedOriginals;self._savedOriginals=null;return originals};LocalCollection.prototype._saveOriginal=function(id,doc){var self=this;if(!self._savedOriginals)return;if(self._savedOriginals.has(id))return;self._savedOriginals.set(id,EJSON.clone(doc))};LocalCollection.prototype.pauseObservers=function(){if(this.paused)return;this.paused=true;for(var qid in this.queries){var query=this.queries[qid];query.resultsSnapshot=EJSON.clone(query.results)}};LocalCollection.prototype.resumeObservers=function(){var self=this;if(!this.paused)return;this.paused=false;for(var qid in this.queries){var query=self.queries[qid];LocalCollection._diffQueryChanges(query.ordered,query.resultsSnapshot,query.results,query,{projectionFn:query.projectionFn});query.resultsSnapshot=null}self._observeQueue.drain()};LocalCollection._idStringify=function(id){if(id instanceof LocalCollection._ObjectID){return id.valueOf()}else if(typeof id==="string"){if(id===""){return id}else if(id.substr(0,1)==="-"||id.substr(0,1)==="~"||LocalCollection._looksLikeObjectID(id)||id.substr(0,1)==="{"){return"-"+id}else{return id}}else if(id===undefined){return"-"}else if(typeof id==="object"&&id!==null){throw new Error("Meteor does not currently support objects other than ObjectID as ids")}else{return"~"+JSON.stringify(id)}};LocalCollection._idParse=function(id){if(id===""){return id}else if(id==="-"){return undefined}else if(id.substr(0,1)==="-"){return id.substr(1)}else if(id.substr(0,1)==="~"){return JSON.parse(id.substr(1))}else if(LocalCollection._looksLikeObjectID(id)){return new LocalCollection._ObjectID(id)}else{return id}};LocalCollection._makeChangedFields=function(newDoc,oldDoc){var fields={};LocalCollection._diffObjects(oldDoc,newDoc,{leftOnly:function(key,value){fields[key]=undefined},rightOnly:function(key,value){fields[key]=value},both:function(key,leftValue,rightValue){if(!EJSON.equals(leftValue,rightValue))fields[key]=rightValue}});return fields}}).call(this);(function(){LocalCollection.wrapTransform=function(transform){if(!transform)return null;if(transform.__wrappedTransform__)return transform;var wrapped=function(doc){if(!_.has(doc,"_id")){throw new Error("can only transform documents with _id")}var id=doc._id;var transformed=Tracker.nonreactive(function(){return transform(doc)});if(!isPlainObject(transformed)){throw new Error("transform must return object")}if(_.has(transformed,"_id")){if(!EJSON.equals(transformed._id,id)){throw new Error("transformed document can't have different _id")}}else{transformed._id=id}return transformed};wrapped.__wrappedTransform__=true;return wrapped}}).call(this);(function(){isArray=function(x){return _.isArray(x)&&!EJSON.isBinary(x)};isPlainObject=LocalCollection._isPlainObject=function(x){return x&&LocalCollection._f._type(x)===3};isIndexable=function(x){return isArray(x)||isPlainObject(x)};isOperatorObject=function(valueSelector,inconsistentOK){if(!isPlainObject(valueSelector))return false;var theseAreOperators=undefined;_.each(valueSelector,function(value,selKey){var thisIsOperator=selKey.substr(0,1)==="$";if(theseAreOperators===undefined){theseAreOperators=thisIsOperator}else if(theseAreOperators!==thisIsOperator){if(!inconsistentOK)throw new Error("Inconsistent operator: "+JSON.stringify(valueSelector)); | |
theseAreOperators=false}});return!!theseAreOperators};isNumericKey=function(s){return/^[0-9]+$/.test(s)}}).call(this);(function(){Minimongo.Matcher=function(selector){var self=this;self._paths={};self._hasGeoQuery=false;self._hasWhere=false;self._isSimple=true;self._matchingDocument=undefined;self._selector=null;self._docMatcher=self._compileSelector(selector)};_.extend(Minimongo.Matcher.prototype,{documentMatches:function(doc){if(!doc||typeof doc!=="object"){throw Error("documentMatches needs a document")}return this._docMatcher(doc)},hasGeoQuery:function(){return this._hasGeoQuery},hasWhere:function(){return this._hasWhere},isSimple:function(){return this._isSimple},_compileSelector:function(selector){var self=this;if(selector instanceof Function){self._isSimple=false;self._selector=selector;self._recordPathUsed("");return function(doc){return{result:!!selector.call(doc)}}}if(LocalCollection._selectorIsId(selector)){self._selector={_id:selector};self._recordPathUsed("_id");return function(doc){return{result:EJSON.equals(doc._id,selector)}}}if(!selector||"_id"in selector&&!selector._id){self._isSimple=false;return nothingMatcher}if(typeof selector==="boolean"||isArray(selector)||EJSON.isBinary(selector))throw new Error("Invalid selector: "+selector);self._selector=EJSON.clone(selector);return compileDocumentSelector(selector,self,{isRoot:true})},_recordPathUsed:function(path){this._paths[path]=true},_getPaths:function(){return _.keys(this._paths)}});var compileDocumentSelector=function(docSelector,matcher,options){options=options||{};var docMatchers=[];_.each(docSelector,function(subSelector,key){if(key.substr(0,1)==="$"){if(!_.has(LOGICAL_OPERATORS,key))throw new Error("Unrecognized logical operator: "+key);matcher._isSimple=false;docMatchers.push(LOGICAL_OPERATORS[key](subSelector,matcher,options.inElemMatch))}else{if(!options.inElemMatch)matcher._recordPathUsed(key);var lookUpByIndex=makeLookupFunction(key);var valueMatcher=compileValueSelector(subSelector,matcher,options.isRoot);docMatchers.push(function(doc){var branchValues=lookUpByIndex(doc);return valueMatcher(branchValues)})}});return andDocumentMatchers(docMatchers)};var compileValueSelector=function(valueSelector,matcher,isRoot){if(valueSelector instanceof RegExp){matcher._isSimple=false;return convertElementMatcherToBranchedMatcher(regexpElementMatcher(valueSelector))}else if(isOperatorObject(valueSelector)){return operatorBranchedMatcher(valueSelector,matcher,isRoot)}else{return convertElementMatcherToBranchedMatcher(equalityElementMatcher(valueSelector))}};var convertElementMatcherToBranchedMatcher=function(elementMatcher,options){options=options||{};return function(branches){var expanded=branches;if(!options.dontExpandLeafArrays){expanded=expandArraysInBranches(branches,options.dontIncludeLeafArrays)}var ret={};ret.result=_.any(expanded,function(element){var matched=elementMatcher(element.value);if(typeof matched==="number"){if(!element.arrayIndices)element.arrayIndices=[matched];matched=true}if(matched&&element.arrayIndices)ret.arrayIndices=element.arrayIndices;return matched});return ret}};regexpElementMatcher=function(regexp){return function(value){if(value instanceof RegExp){return _.isEqual(value,regexp)}if(typeof value!=="string")return false;regexp.lastIndex=0;return regexp.test(value)}};equalityElementMatcher=function(elementSelector){if(isOperatorObject(elementSelector))throw Error("Can't create equalityValueSelector for operator object");if(elementSelector==null){return function(value){return value==null}}return function(value){return LocalCollection._f._equal(elementSelector,value)}};var operatorBranchedMatcher=function(valueSelector,matcher,isRoot){var operatorMatchers=[];_.each(valueSelector,function(operand,operator){var simpleRange=_.contains(["$lt","$lte","$gt","$gte"],operator)&&_.isNumber(operand);var simpleInequality=operator==="$ne"&&!_.isObject(operand);var simpleInclusion=_.contains(["$in","$nin"],operator)&&_.isArray(operand)&&!_.any(operand,_.isObject);if(!(operator==="$eq"||simpleRange||simpleInclusion||simpleInequality)){matcher._isSimple=false}if(_.has(VALUE_OPERATORS,operator)){operatorMatchers.push(VALUE_OPERATORS[operator](operand,valueSelector,matcher,isRoot))}else if(_.has(ELEMENT_OPERATORS,operator)){var options=ELEMENT_OPERATORS[operator];operatorMatchers.push(convertElementMatcherToBranchedMatcher(options.compileElementSelector(operand,valueSelector,matcher),options))}else{throw new Error("Unrecognized operator: "+operator)}});return andBranchedMatchers(operatorMatchers)};var compileArrayOfDocumentSelectors=function(selectors,matcher,inElemMatch){if(!isArray(selectors)||_.isEmpty(selectors))throw Error("$and/$or/$nor must be nonempty array");return _.map(selectors,function(subSelector){if(!isPlainObject(subSelector))throw Error("$or/$and/$nor entries need to be full objects");return compileDocumentSelector(subSelector,matcher,{inElemMatch:inElemMatch})})};var LOGICAL_OPERATORS={$and:function(subSelector,matcher,inElemMatch){var matchers=compileArrayOfDocumentSelectors(subSelector,matcher,inElemMatch);return andDocumentMatchers(matchers)},$or:function(subSelector,matcher,inElemMatch){var matchers=compileArrayOfDocumentSelectors(subSelector,matcher,inElemMatch);if(matchers.length===1)return matchers[0];return function(doc){var result=_.any(matchers,function(f){return f(doc).result});return{result:result}}},$nor:function(subSelector,matcher,inElemMatch){var matchers=compileArrayOfDocumentSelectors(subSelector,matcher,inElemMatch);return function(doc){var result=_.all(matchers,function(f){return!f(doc).result});return{result:result}}},$where:function(selectorValue,matcher){matcher._recordPathUsed("");matcher._hasWhere=true;if(!(selectorValue instanceof Function)){selectorValue=Function("obj","return "+selectorValue)}return function(doc){return{result:selectorValue.call(doc,doc)}}},$comment:function(){return function(){return{result:true}}}};var invertBranchedMatcher=function(branchedMatcher){return function(branchValues){var invertMe=branchedMatcher(branchValues);return{result:!invertMe.result}}};var VALUE_OPERATORS={$not:function(operand,valueSelector,matcher){return invertBranchedMatcher(compileValueSelector(operand,matcher))},$ne:function(operand){return invertBranchedMatcher(convertElementMatcherToBranchedMatcher(equalityElementMatcher(operand)))},$nin:function(operand){return invertBranchedMatcher(convertElementMatcherToBranchedMatcher(ELEMENT_OPERATORS.$in.compileElementSelector(operand)))},$exists:function(operand){var exists=convertElementMatcherToBranchedMatcher(function(value){return value!==undefined});return operand?exists:invertBranchedMatcher(exists)},$options:function(operand,valueSelector){if(!_.has(valueSelector,"$regex"))throw Error("$options needs a $regex");return everythingMatcher},$maxDistance:function(operand,valueSelector){if(!valueSelector.$near)throw Error("$maxDistance needs a $near");return everythingMatcher},$all:function(operand,valueSelector,matcher){if(!isArray(operand))throw Error("$all requires array");if(_.isEmpty(operand))return nothingMatcher;var branchedMatchers=[];_.each(operand,function(criterion){if(isOperatorObject(criterion))throw Error("no $ expressions in $all");branchedMatchers.push(compileValueSelector(criterion,matcher))});return andBranchedMatchers(branchedMatchers)},$near:function(operand,valueSelector,matcher,isRoot){if(!isRoot)throw Error("$near can't be inside another $ operator");matcher._hasGeoQuery=true;var maxDistance,point,distance;if(isPlainObject(operand)&&_.has(operand,"$geometry")){maxDistance=operand.$maxDistance;point=operand.$geometry;distance=function(value){if(!value||!value.type)return null;if(value.type==="Point"){return GeoJSON.pointDistance(point,value)}else{return GeoJSON.geometryWithinRadius(value,point,maxDistance)?0:maxDistance+1}}}else{maxDistance=valueSelector.$maxDistance;if(!isArray(operand)&&!isPlainObject(operand))throw Error("$near argument must be coordinate pair or GeoJSON");point=pointToArray(operand);distance=function(value){if(!isArray(value)&&!isPlainObject(value))return null;return distanceCoordinatePairs(point,value)}}return function(branchedValues){branchedValues=expandArraysInBranches(branchedValues);var result={result:false};_.each(branchedValues,function(branch){var curDistance=distance(branch.value);if(curDistance===null||curDistance>maxDistance)return;if(result.distance!==undefined&&result.distance<=curDistance)return;result.result=true;result.distance=curDistance;if(!branch.arrayIndices)delete result.arrayIndices;else result.arrayIndices=branch.arrayIndices});return result}}};var distanceCoordinatePairs=function(a,b){a=pointToArray(a);b=pointToArray(b);var x=a[0]-b[0];var y=a[1]-b[1];if(_.isNaN(x)||_.isNaN(y))return null;return Math.sqrt(x*x+y*y)};var pointToArray=function(point){return _.map(point,_.identity)};var makeInequality=function(cmpValueComparator){return{compileElementSelector:function(operand){if(isArray(operand)){return function(){return false}}if(operand===undefined)operand=null;var operandType=LocalCollection._f._type(operand);return function(value){if(value===undefined)value=null;if(LocalCollection._f._type(value)!==operandType)return false;return cmpValueComparator(LocalCollection._f._cmp(value,operand))}}}};ELEMENT_OPERATORS={$lt:makeInequality(function(cmpValue){return cmpValue<0}),$gt:makeInequality(function(cmpValue){return cmpValue>0}),$lte:makeInequality(function(cmpValue){return cmpValue<=0}),$gte:makeInequality(function(cmpValue){return cmpValue>=0}),$mod:{compileElementSelector:function(operand){if(!(isArray(operand)&&operand.length===2&&typeof operand[0]==="number"&&typeof operand[1]==="number")){throw Error("argument to $mod must be an array of two numbers")}var divisor=operand[0];var remainder=operand[1];return function(value){return typeof value==="number"&&value%divisor===remainder}}},$in:{compileElementSelector:function(operand){if(!isArray(operand))throw Error("$in needs an array");var elementMatchers=[];_.each(operand,function(option){if(option instanceof RegExp)elementMatchers.push(regexpElementMatcher(option));else if(isOperatorObject(option))throw Error("cannot nest $ under $in");else elementMatchers.push(equalityElementMatcher(option))});return function(value){if(value===undefined)value=null;return _.any(elementMatchers,function(e){return e(value)})}}},$size:{dontExpandLeafArrays:true,compileElementSelector:function(operand){if(typeof operand==="string"){operand=0}else if(typeof operand!=="number"){throw Error("$size needs a number")}return function(value){return isArray(value)&&value.length===operand}}},$type:{dontIncludeLeafArrays:true,compileElementSelector:function(operand){if(typeof operand!=="number")throw Error("$type needs a number");return function(value){return value!==undefined&&LocalCollection._f._type(value)===operand}}},$regex:{compileElementSelector:function(operand,valueSelector){if(!(typeof operand==="string"||operand instanceof RegExp))throw Error("$regex has to be a string or RegExp");var regexp;if(valueSelector.$options!==undefined){if(/[^gim]/.test(valueSelector.$options))throw new Error("Only the i, m, and g regexp options are supported");var regexSource=operand instanceof RegExp?operand.source:operand;regexp=new RegExp(regexSource,valueSelector.$options)}else if(operand instanceof RegExp){regexp=operand}else{regexp=new RegExp(operand)}return regexpElementMatcher(regexp)}},$elemMatch:{dontExpandLeafArrays:true,compileElementSelector:function(operand,valueSelector,matcher){if(!isPlainObject(operand))throw Error("$elemMatch need an object");var subMatcher,isDocMatcher;if(isOperatorObject(operand,true)){subMatcher=compileValueSelector(operand,matcher);isDocMatcher=false}else{subMatcher=compileDocumentSelector(operand,matcher,{inElemMatch:true});isDocMatcher=true}return function(value){if(!isArray(value))return false;for(var i=0;i<value.length;++i){var arrayElement=value[i];var arg;if(isDocMatcher){if(!isPlainObject(arrayElement)&&!isArray(arrayElement))return false;arg=arrayElement}else{arg=[{value:arrayElement,dontIterate:true}]}if(subMatcher(arg).result)return i}return false}}}};makeLookupFunction=function(key,options){options=options||{};var parts=key.split(".");var firstPart=parts.length?parts[0]:"";var firstPartIsNumeric=isNumericKey(firstPart);var nextPartIsNumeric=parts.length>=2&&isNumericKey(parts[1]);var lookupRest;if(parts.length>1){lookupRest=makeLookupFunction(parts.slice(1).join("."))}var omitUnnecessaryFields=function(retVal){if(!retVal.dontIterate)delete retVal.dontIterate;if(retVal.arrayIndices&&!retVal.arrayIndices.length)delete retVal.arrayIndices;return retVal};return function(doc,arrayIndices){if(!arrayIndices)arrayIndices=[];if(isArray(doc)){if(!(firstPartIsNumeric&&firstPart<doc.length))return[];arrayIndices=arrayIndices.concat(+firstPart,"x")}var firstLevel=doc[firstPart];if(!lookupRest){return[omitUnnecessaryFields({value:firstLevel,dontIterate:isArray(doc)&&isArray(firstLevel),arrayIndices:arrayIndices})]}if(!isIndexable(firstLevel)){if(isArray(doc))return[];return[omitUnnecessaryFields({value:undefined,arrayIndices:arrayIndices})]}var result=[];var appendToResult=function(more){Array.prototype.push.apply(result,more)};appendToResult(lookupRest(firstLevel,arrayIndices));if(isArray(firstLevel)&&!(nextPartIsNumeric&&options.forSort)){_.each(firstLevel,function(branch,arrayIndex){if(isPlainObject(branch)){appendToResult(lookupRest(branch,arrayIndices.concat(arrayIndex)))}})}return result}};MinimongoTest.makeLookupFunction=makeLookupFunction;expandArraysInBranches=function(branches,skipTheArrays){var branchesOut=[];_.each(branches,function(branch){var thisIsArray=isArray(branch.value);if(!(skipTheArrays&&thisIsArray&&!branch.dontIterate)){branchesOut.push({value:branch.value,arrayIndices:branch.arrayIndices})}if(thisIsArray&&!branch.dontIterate){_.each(branch.value,function(leaf,i){branchesOut.push({value:leaf,arrayIndices:(branch.arrayIndices||[]).concat(i)})})}});return branchesOut};var nothingMatcher=function(docOrBranchedValues){return{result:false}};var everythingMatcher=function(docOrBranchedValues){return{result:true}};var andSomeMatchers=function(subMatchers){if(subMatchers.length===0)return everythingMatcher;if(subMatchers.length===1)return subMatchers[0];return function(docOrBranches){var ret={};ret.result=_.all(subMatchers,function(f){var subResult=f(docOrBranches);if(subResult.result&&subResult.distance!==undefined&&ret.distance===undefined){ret.distance=subResult.distance}if(subResult.result&&subResult.arrayIndices){ret.arrayIndices=subResult.arrayIndices}return subResult.result});if(!ret.result){delete ret.distance;delete ret.arrayIndices}return ret}};var andDocumentMatchers=andSomeMatchers;var andBranchedMatchers=andSomeMatchers;LocalCollection._f={_type:function(v){if(typeof v==="number")return 1;if(typeof v==="string")return 2;if(typeof v==="boolean")return 8;if(isArray(v))return 4;if(v===null)return 10;if(v instanceof RegExp)return 11;if(typeof v==="function")return 13;if(v instanceof Date)return 9;if(EJSON.isBinary(v))return 5;if(v instanceof LocalCollection._ObjectID)return 7;return 3},_equal:function(a,b){return EJSON.equals(a,b,{keyOrderSensitive:true})},_typeorder:function(t){return[-1,1,2,3,4,5,-1,6,7,8,0,9,-1,100,2,100,1,8,1][t]},_cmp:function(a,b){if(a===undefined)return b===undefined?0:-1;if(b===undefined)return 1;var ta=LocalCollection._f._type(a);var tb=LocalCollection._f._type(b);var oa=LocalCollection._f._typeorder(ta);var ob=LocalCollection._f._typeorder(tb);if(oa!==ob)return oa<ob?-1:1;if(ta!==tb)throw Error("Missing type coercion logic in _cmp");if(ta===7){ta=tb=2;a=a.toHexString();b=b.toHexString()}if(ta===9){ta=tb=1;a=a.getTime();b=b.getTime()}if(ta===1)return a-b;if(tb===2)return a<b?-1:a===b?0:1;if(ta===3){var to_array=function(obj){var ret=[];for(var key in obj){ret.push(key);ret.push(obj[key])}return ret};return LocalCollection._f._cmp(to_array(a),to_array(b))}if(ta===4){for(var i=0;;i++){if(i===a.length)return i===b.length?0:-1;if(i===b.length)return 1;var s=LocalCollection._f._cmp(a[i],b[i]);if(s!==0)return s}}if(ta===5){if(a.length!==b.length)return a.length-b.length;for(i=0;i<a.length;i++){if(a[i]<b[i])return-1;if(a[i]>b[i])return 1}return 0}if(ta===8){if(a)return b?0:1;return b?-1:0}if(ta===10)return 0;if(ta===11)throw Error("Sorting not supported on regular expression");if(ta===13)throw Error("Sorting not supported on Javascript code");throw Error("Unknown type to sort")}};LocalCollection._removeDollarOperators=function(selector){var selectorDoc={};for(var k in selector)if(k.substr(0,1)!=="$")selectorDoc[k]=selector[k];return selectorDoc}}).call(this);(function(){Minimongo.Sorter=function(spec,options){var self=this;options=options||{};self._sortSpecParts=[];var addSpecPart=function(path,ascending){if(!path)throw Error("sort keys must be non-empty");if(path.charAt(0)==="$")throw Error("unsupported sort key: "+path);self._sortSpecParts.push({path:path,lookup:makeLookupFunction(path,{forSort:true}),ascending:ascending})};if(spec instanceof Array){for(var i=0;i<spec.length;i++){if(typeof spec[i]==="string"){addSpecPart(spec[i],true)}else{addSpecPart(spec[i][0],spec[i][1]!=="desc")}}}else if(typeof spec==="object"){_.each(spec,function(value,key){addSpecPart(key,value>=0)})}else{throw Error("Bad sort specification: "+JSON.stringify(spec))}if(self.affectedByModifier){var selector={};_.each(self._sortSpecParts,function(spec){selector[spec.path]=1});self._selectorForAffectedByModifier=new Minimongo.Matcher(selector)}self._keyComparator=composeComparators(_.map(self._sortSpecParts,function(spec,i){return self._keyFieldComparator(i)}));self._keyFilter=null;options.matcher&&self._useWithMatcher(options.matcher)};_.extend(Minimongo.Sorter.prototype,{getComparator:function(options){var self=this;if(!options||!options.distances){return self._getBaseComparator()}var distances=options.distances;return composeComparators([self._getBaseComparator(),function(a,b){if(!distances.has(a._id))throw Error("Missing distance for "+a._id);if(!distances.has(b._id))throw Error("Missing distance for "+b._id);return distances.get(a._id)-distances.get(b._id)}])},_getPaths:function(){var self=this;return _.pluck(self._sortSpecParts,"path")},_getMinKeyFromDoc:function(doc){var self=this;var minKey=null;self._generateKeysFromDoc(doc,function(key){if(!self._keyCompatibleWithSelector(key))return;if(minKey===null){minKey=key;return}if(self._compareKeys(key,minKey)<0){minKey=key}});if(minKey===null)throw Error("sort selector found no keys in doc?");return minKey},_keyCompatibleWithSelector:function(key){var self=this;return!self._keyFilter||self._keyFilter(key)},_generateKeysFromDoc:function(doc,cb){var self=this;if(self._sortSpecParts.length===0)throw new Error("can't generate keys without a spec");var valuesByIndexAndPath=[];var pathFromIndices=function(indices){return indices.join(",")+","};var knownPaths=null;_.each(self._sortSpecParts,function(spec,whichField){var branches=expandArraysInBranches(spec.lookup(doc),true);if(!branches.length)branches=[{value:null}];var usedPaths=false;valuesByIndexAndPath[whichField]={};_.each(branches,function(branch){if(!branch.arrayIndices){if(branches.length>1)throw Error("multiple branches but no array used?");valuesByIndexAndPath[whichField][""]=branch.value;return}usedPaths=true;var path=pathFromIndices(branch.arrayIndices);if(_.has(valuesByIndexAndPath[whichField],path))throw Error("duplicate path: "+path);valuesByIndexAndPath[whichField][path]=branch.value;if(knownPaths&&!_.has(knownPaths,path)){throw Error("cannot index parallel arrays")}});if(knownPaths){if(!_.has(valuesByIndexAndPath[whichField],"")&&_.size(knownPaths)!==_.size(valuesByIndexAndPath[whichField])){throw Error("cannot index parallel arrays!")}}else if(usedPaths){knownPaths={};_.each(valuesByIndexAndPath[whichField],function(x,path){knownPaths[path]=true})}});if(!knownPaths){var soleKey=_.map(valuesByIndexAndPath,function(values){if(!_.has(values,""))throw Error("no value in sole key case?");return values[""]});cb(soleKey);return}_.each(knownPaths,function(x,path){var key=_.map(valuesByIndexAndPath,function(values){if(_.has(values,""))return values[""];if(!_.has(values,path))throw Error("missing path?");return values[path]});cb(key)})},_compareKeys:function(key1,key2){var self=this;if(key1.length!==self._sortSpecParts.length||key2.length!==self._sortSpecParts.length){throw Error("Key has wrong length")}return self._keyComparator(key1,key2)},_keyFieldComparator:function(i){var self=this;var invert=!self._sortSpecParts[i].ascending;return function(key1,key2){var compare=LocalCollection._f._cmp(key1[i],key2[i]);if(invert)compare=-compare;return compare}},_getBaseComparator:function(){var self=this;if(!self._sortSpecParts.length){return function(doc1,doc2){return 0}}return function(doc1,doc2){var key1=self._getMinKeyFromDoc(doc1);var key2=self._getMinKeyFromDoc(doc2);return self._compareKeys(key1,key2)}},_useWithMatcher:function(matcher){var self=this;if(self._keyFilter)throw Error("called _useWithMatcher twice?");if(_.isEmpty(self._sortSpecParts))return;var selector=matcher._selector;if(selector instanceof Function)return;var constraintsByPath={};_.each(self._sortSpecParts,function(spec,i){constraintsByPath[spec.path]=[]});_.each(selector,function(subSelector,key){var constraints=constraintsByPath[key];if(!constraints)return;if(subSelector instanceof RegExp){if(subSelector.ignoreCase||subSelector.multiline)return;constraints.push(regexpElementMatcher(subSelector));return}if(isOperatorObject(subSelector)){_.each(subSelector,function(operand,operator){if(_.contains(["$lt","$lte","$gt","$gte"],operator)){constraints.push(ELEMENT_OPERATORS[operator].compileElementSelector(operand))}if(operator==="$regex"&&!subSelector.$options){constraints.push(ELEMENT_OPERATORS.$regex.compileElementSelector(operand,subSelector))}});return}constraints.push(equalityElementMatcher(subSelector))});if(_.isEmpty(constraintsByPath[self._sortSpecParts[0].path]))return;self._keyFilter=function(key){return _.all(self._sortSpecParts,function(specPart,index){return _.all(constraintsByPath[specPart.path],function(f){return f(key[index])})})}}});var composeComparators=function(comparatorArray){return function(a,b){for(var i=0;i<comparatorArray.length;++i){var compare=comparatorArray[i](a,b);if(compare!==0)return compare}return 0}}}).call(this);(function(){LocalCollection._compileProjection=function(fields){LocalCollection._checkSupportedProjection(fields);var _idProjection=_.isUndefined(fields._id)?true:fields._id;var details=projectionDetails(fields);var transform=function(doc,ruleTree){if(_.isArray(doc))return _.map(doc,function(subdoc){return transform(subdoc,ruleTree)});var res=details.including?{}:EJSON.clone(doc);_.each(ruleTree,function(rule,key){if(!_.has(doc,key))return;if(_.isObject(rule)){if(_.isObject(doc[key]))res[key]=transform(doc[key],rule)}else if(details.including)res[key]=EJSON.clone(doc[key]);else delete res[key]});return res};return function(obj){var res=transform(obj,details.tree);if(_idProjection&&_.has(obj,"_id"))res._id=obj._id;if(!_idProjection&&_.has(res,"_id"))delete res._id;return res}};projectionDetails=function(fields){var fieldsKeys=_.keys(fields).sort();if(fieldsKeys.length>0&&!(fieldsKeys.length===1&&fieldsKeys[0]==="_id"))fieldsKeys=_.reject(fieldsKeys,function(key){return key==="_id"});var including=null;_.each(fieldsKeys,function(keyPath){var rule=!!fields[keyPath];if(including===null)including=rule;if(including!==rule)throw MinimongoError("You cannot currently mix including and excluding fields.")});var projectionRulesTree=pathsToTree(fieldsKeys,function(path){return including},function(node,path,fullPath){var currentPath=fullPath;var anotherPath=path;throw MinimongoError("both "+currentPath+" and "+anotherPath+" found in fields option, using both of them may trigger "+"unexpected behavior. Did you mean to use only one of them?")});return{tree:projectionRulesTree,including:including}};pathsToTree=function(paths,newLeafFn,conflictFn,tree){tree=tree||{};_.each(paths,function(keyPath){var treePos=tree;var pathArr=keyPath.split(".");var success=_.all(pathArr.slice(0,-1),function(key,idx){if(!_.has(treePos,key))treePos[key]={};else if(!_.isObject(treePos[key])){treePos[key]=conflictFn(treePos[key],pathArr.slice(0,idx+1).join("."),keyPath);if(!_.isObject(treePos[key]))return false}treePos=treePos[key];return true});if(success){var lastKey=_.last(pathArr);if(!_.has(treePos,lastKey))treePos[lastKey]=newLeafFn(keyPath);else treePos[lastKey]=conflictFn(treePos[lastKey],keyPath,keyPath)}});return tree};LocalCollection._checkSupportedProjection=function(fields){if(!_.isObject(fields)||_.isArray(fields))throw MinimongoError("fields option must be an object");_.each(fields,function(val,keyPath){if(_.contains(keyPath.split("."),"$"))throw MinimongoError("Minimongo doesn't support $ operator in projections yet.");if(_.indexOf([1,0,true,false],val)===-1)throw MinimongoError("Projection values should be one of 1, 0, true, or false")})}}).call(this);(function(){LocalCollection._modify=function(doc,mod,options){options=options||{};if(!isPlainObject(mod))throw MinimongoError("Modifier must be an object");var isModifier=isOperatorObject(mod);var newDoc;if(!isModifier){if(mod._id&&!EJSON.equals(doc._id,mod._id))throw MinimongoError("Cannot change the _id of a document");for(var k in mod){if(/\./.test(k))throw MinimongoError("When replacing document, field name may not contain '.'")}newDoc=mod}else{newDoc=EJSON.clone(doc);_.each(mod,function(operand,op){var modFunc=MODIFIERS[op];if(options.isInsert&&op==="$setOnInsert")modFunc=MODIFIERS["$set"];if(!modFunc)throw MinimongoError("Invalid modifier specified "+op);_.each(operand,function(arg,keypath){if(keypath===""){throw MinimongoError("An empty update path is not valid.")}if(keypath==="_id"){throw MinimongoError("Mod on _id not allowed")}var keyparts=keypath.split(".");if(!_.all(keyparts,_.identity)){throw MinimongoError("The update path '"+keypath+"' contains an empty field name, which is not allowed.")}var noCreate=_.has(NO_CREATE_MODIFIERS,op);var forbidArray=op==="$rename";var target=findModTarget(newDoc,keyparts,{noCreate:NO_CREATE_MODIFIERS[op],forbidArray:op==="$rename",arrayIndices:options.arrayIndices});var field=keyparts.pop();modFunc(target,field,arg,keypath,newDoc)})})}_.each(_.keys(doc),function(k){if(k!=="_id")delete doc[k]});_.each(newDoc,function(v,k){doc[k]=v})};var findModTarget=function(doc,keyparts,options){options=options||{};var usedArrayIndex=false;for(var i=0;i<keyparts.length;i++){var last=i===keyparts.length-1;var keypart=keyparts[i];var indexable=isIndexable(doc);if(!indexable){if(options.noCreate)return undefined;var e=MinimongoError("cannot use the part '"+keypart+"' to traverse "+doc);e.setPropertyError=true;throw e}if(doc instanceof Array){if(options.forbidArray)return null;if(keypart==="$"){if(usedArrayIndex)throw MinimongoError("Too many positional (i.e. '$') elements");if(!options.arrayIndices||!options.arrayIndices.length){throw MinimongoError("The positional operator did not find the "+"match needed from the query")}keypart=options.arrayIndices[0];usedArrayIndex=true}else if(isNumericKey(keypart)){keypart=parseInt(keypart)}else{if(options.noCreate)return undefined;throw MinimongoError("can't append to array using string field name ["+keypart+"]")}if(last)keyparts[i]=keypart;if(options.noCreate&&keypart>=doc.length)return undefined;while(doc.length<keypart)doc.push(null);if(!last){if(doc.length===keypart)doc.push({});else if(typeof doc[keypart]!=="object")throw MinimongoError("can't modify field '"+keyparts[i+1]+"' of list value "+JSON.stringify(doc[keypart]))}}else{if(keypart.length&&keypart.substr(0,1)==="$")throw MinimongoError("can't set field named "+keypart);if(!(keypart in doc)){if(options.noCreate)return undefined;if(!last)doc[keypart]={}}}if(last)return doc;doc=doc[keypart]}};var NO_CREATE_MODIFIERS={$unset:true,$pop:true,$rename:true,$pull:true,$pullAll:true};var MODIFIERS={$inc:function(target,field,arg){if(typeof arg!=="number")throw MinimongoError("Modifier $inc allowed for numbers only");if(field in target){if(typeof target[field]!=="number")throw MinimongoError("Cannot apply $inc modifier to non-number");target[field]+=arg}else{target[field]=arg}},$set:function(target,field,arg){if(!_.isObject(target)){var e=MinimongoError("Cannot set property on non-object field");e.setPropertyError=true;throw e}if(target===null){var e=MinimongoError("Cannot set property on null");e.setPropertyError=true;throw e}target[field]=EJSON.clone(arg)},$setOnInsert:function(target,field,arg){},$unset:function(target,field,arg){if(target!==undefined){if(target instanceof Array){if(field in target)target[field]=null}else delete target[field]}},$push:function(target,field,arg){if(target[field]===undefined)target[field]=[];if(!(target[field]instanceof Array))throw MinimongoError("Cannot apply $push modifier to non-array");if(!(arg&&arg.$each)){target[field].push(EJSON.clone(arg));return}var toPush=arg.$each;if(!(toPush instanceof Array))throw MinimongoError("$each must be an array");var slice=undefined;if("$slice"in arg){if(typeof arg.$slice!=="number")throw MinimongoError("$slice must be a numeric value");if(arg.$slice>0)throw MinimongoError("$slice in $push must be zero or negative");slice=arg.$slice}var sortFunction=undefined;if(arg.$sort){if(slice===undefined)throw MinimongoError("$sort requires $slice to be present");sortFunction=new Minimongo.Sorter(arg.$sort).getComparator();for(var i=0;i<toPush.length;i++){if(LocalCollection._f._type(toPush[i])!==3){throw MinimongoError("$push like modifiers using $sort "+"require all elements to be objects")}}}for(var j=0;j<toPush.length;j++)target[field].push(EJSON.clone(toPush[j]));if(sortFunction)target[field].sort(sortFunction);if(slice!==undefined){if(slice===0)target[field]=[];else target[field]=target[field].slice(slice)}},$pushAll:function(target,field,arg){if(!(typeof arg==="object"&&arg instanceof Array))throw MinimongoError("Modifier $pushAll/pullAll allowed for arrays only");var x=target[field];if(x===undefined)target[field]=arg;else if(!(x instanceof Array))throw MinimongoError("Cannot apply $pushAll modifier to non-array");else{for(var i=0;i<arg.length;i++)x.push(arg[i])}},$addToSet:function(target,field,arg){var isEach=false;if(typeof arg==="object"){for(var k in arg){if(k==="$each")isEach=true;break}}var values=isEach?arg["$each"]:[arg];var x=target[field];if(x===undefined)target[field]=values;else if(!(x instanceof Array))throw MinimongoError("Cannot apply $addToSet modifier to non-array");else{_.each(values,function(value){for(var i=0;i<x.length;i++)if(LocalCollection._f._equal(value,x[i]))return;x.push(EJSON.clone(value))})}},$pop:function(target,field,arg){if(target===undefined)return;var x=target[field];if(x===undefined)return;else if(!(x instanceof Array))throw MinimongoError("Cannot apply $pop modifier to non-array");else{if(typeof arg==="number"&&arg<0)x.splice(0,1);else x.pop()}},$pull:function(target,field,arg){if(target===undefined)return;var x=target[field];if(x===undefined)return;else if(!(x instanceof Array))throw MinimongoError("Cannot apply $pull/pullAll modifier to non-array");else{var out=[];if(typeof arg==="object"&&!(arg instanceof Array)){var matcher=new Minimongo.Matcher(arg);for(var i=0;i<x.length;i++)if(!matcher.documentMatches(x[i]).result)out.push(x[i])}else{for(var i=0;i<x.length;i++)if(!LocalCollection._f._equal(x[i],arg))out.push(x[i])}target[field]=out}},$pullAll:function(target,field,arg){if(!(typeof arg==="object"&&arg instanceof Array))throw MinimongoError("Modifier $pushAll/pullAll allowed for arrays only");if(target===undefined)return;var x=target[field];if(x===undefined)return;else if(!(x instanceof Array))throw MinimongoError("Cannot apply $pull/pullAll modifier to non-array");else{var out=[];for(var i=0;i<x.length;i++){var exclude=false;for(var j=0;j<arg.length;j++){ | |
if(LocalCollection._f._equal(x[i],arg[j])){exclude=true;break}}if(!exclude)out.push(x[i])}target[field]=out}},$rename:function(target,field,arg,keypath,doc){if(keypath===arg)throw MinimongoError("$rename source must differ from target");if(target===null)throw MinimongoError("$rename source field invalid");if(typeof arg!=="string")throw MinimongoError("$rename target must be a string");if(target===undefined)return;var v=target[field];delete target[field];var keyparts=arg.split(".");var target2=findModTarget(doc,keyparts,{forbidArray:true});if(target2===null)throw MinimongoError("$rename target field invalid");var field2=keyparts.pop();target2[field2]=v},$bit:function(target,field,arg){throw MinimongoError("$bit is not supported")}}}).call(this);(function(){LocalCollection._diffQueryChanges=function(ordered,oldResults,newResults,observer,options){if(ordered)LocalCollection._diffQueryOrderedChanges(oldResults,newResults,observer,options);else LocalCollection._diffQueryUnorderedChanges(oldResults,newResults,observer,options)};LocalCollection._diffQueryUnorderedChanges=function(oldResults,newResults,observer,options){options=options||{};var projectionFn=options.projectionFn||EJSON.clone;if(observer.movedBefore){throw new Error("_diffQueryUnordered called with a movedBefore observer!")}newResults.forEach(function(newDoc,id){var oldDoc=oldResults.get(id);if(oldDoc){if(observer.changed&&!EJSON.equals(oldDoc,newDoc)){var projectedNew=projectionFn(newDoc);var projectedOld=projectionFn(oldDoc);var changedFields=LocalCollection._makeChangedFields(projectedNew,projectedOld);if(!_.isEmpty(changedFields)){observer.changed(id,changedFields)}}}else if(observer.added){var fields=projectionFn(newDoc);delete fields._id;observer.added(newDoc._id,fields)}});if(observer.removed){oldResults.forEach(function(oldDoc,id){if(!newResults.has(id))observer.removed(id)})}};LocalCollection._diffQueryOrderedChanges=function(old_results,new_results,observer,options){options=options||{};var projectionFn=options.projectionFn||EJSON.clone;var new_presence_of_id={};_.each(new_results,function(doc){if(new_presence_of_id[doc._id])Meteor._debug("Duplicate _id in new_results");new_presence_of_id[doc._id]=true});var old_index_of_id={};_.each(old_results,function(doc,i){if(doc._id in old_index_of_id)Meteor._debug("Duplicate _id in old_results");old_index_of_id[doc._id]=i});var unmoved=[];var max_seq_len=0;var N=new_results.length;var seq_ends=new Array(N);var ptrs=new Array(N);var old_idx_seq=function(i_new){return old_index_of_id[new_results[i_new]._id]};for(var i=0;i<N;i++){if(old_index_of_id[new_results[i]._id]!==undefined){var j=max_seq_len;while(j>0){if(old_idx_seq(seq_ends[j-1])<old_idx_seq(i))break;j--}ptrs[i]=j===0?-1:seq_ends[j-1];seq_ends[j]=i;if(j+1>max_seq_len)max_seq_len=j+1}}var idx=max_seq_len===0?-1:seq_ends[max_seq_len-1];while(idx>=0){unmoved.push(idx);idx=ptrs[idx]}unmoved.reverse();unmoved.push(new_results.length);_.each(old_results,function(doc){if(!new_presence_of_id[doc._id])observer.removed&&observer.removed(doc._id)});var startOfGroup=0;_.each(unmoved,function(endOfGroup){var groupId=new_results[endOfGroup]?new_results[endOfGroup]._id:null;var oldDoc,newDoc,fields,projectedNew,projectedOld;for(var i=startOfGroup;i<endOfGroup;i++){newDoc=new_results[i];if(!_.has(old_index_of_id,newDoc._id)){fields=projectionFn(newDoc);delete fields._id;observer.addedBefore&&observer.addedBefore(newDoc._id,fields,groupId);observer.added&&observer.added(newDoc._id,fields)}else{oldDoc=old_results[old_index_of_id[newDoc._id]];projectedNew=projectionFn(newDoc);projectedOld=projectionFn(oldDoc);fields=LocalCollection._makeChangedFields(projectedNew,projectedOld);if(!_.isEmpty(fields)){observer.changed&&observer.changed(newDoc._id,fields)}observer.movedBefore&&observer.movedBefore(newDoc._id,groupId)}}if(groupId){newDoc=new_results[endOfGroup];oldDoc=old_results[old_index_of_id[newDoc._id]];projectedNew=projectionFn(newDoc);projectedOld=projectionFn(oldDoc);fields=LocalCollection._makeChangedFields(projectedNew,projectedOld);if(!_.isEmpty(fields)){observer.changed&&observer.changed(newDoc._id,fields)}}startOfGroup=endOfGroup+1})};LocalCollection._diffObjects=function(left,right,callbacks){_.each(left,function(leftValue,key){if(_.has(right,key))callbacks.both&&callbacks.both(key,leftValue,right[key]);else callbacks.leftOnly&&callbacks.leftOnly(key,leftValue)});if(callbacks.rightOnly){_.each(right,function(rightValue,key){if(!_.has(left,key))callbacks.rightOnly(key,rightValue)})}}}).call(this);(function(){LocalCollection._IdMap=function(){var self=this;IdMap.call(self,LocalCollection._idStringify,LocalCollection._idParse)};Meteor._inherits(LocalCollection._IdMap,IdMap)}).call(this);(function(){LocalCollection._CachingChangeObserver=function(options){var self=this;options=options||{};var orderedFromCallbacks=options.callbacks&&LocalCollection._observeChangesCallbacksAreOrdered(options.callbacks);if(_.has(options,"ordered")){self.ordered=options.ordered;if(options.callbacks&&options.ordered!==orderedFromCallbacks)throw Error("ordered option doesn't match callbacks")}else if(options.callbacks){self.ordered=orderedFromCallbacks}else{throw Error("must provide ordered or callbacks")}var callbacks=options.callbacks||{};if(self.ordered){self.docs=new OrderedDict(LocalCollection._idStringify);self.applyChange={addedBefore:function(id,fields,before){var doc=EJSON.clone(fields);doc._id=id;callbacks.addedBefore&&callbacks.addedBefore.call(self,id,fields,before);callbacks.added&&callbacks.added.call(self,id,fields);self.docs.putBefore(id,doc,before||null)},movedBefore:function(id,before){var doc=self.docs.get(id);callbacks.movedBefore&&callbacks.movedBefore.call(self,id,before);self.docs.moveBefore(id,before||null)}}}else{self.docs=new LocalCollection._IdMap;self.applyChange={added:function(id,fields){var doc=EJSON.clone(fields);callbacks.added&&callbacks.added.call(self,id,fields);doc._id=id;self.docs.set(id,doc)}}}self.applyChange.changed=function(id,fields){var doc=self.docs.get(id);if(!doc)throw new Error("Unknown id for changed: "+id);callbacks.changed&&callbacks.changed.call(self,id,EJSON.clone(fields));LocalCollection._applyChanges(doc,fields)};self.applyChange.removed=function(id){callbacks.removed&&callbacks.removed.call(self,id);self.docs.remove(id)}};LocalCollection._observeFromObserveChanges=function(cursor,observeCallbacks){var transform=cursor.getTransform()||function(doc){return doc};var suppressed=!!observeCallbacks._suppress_initial;var observeChangesCallbacks;if(LocalCollection._observeCallbacksAreOrdered(observeCallbacks)){var indices=!observeCallbacks._no_indices;observeChangesCallbacks={addedBefore:function(id,fields,before){var self=this;if(suppressed||!(observeCallbacks.addedAt||observeCallbacks.added))return;var doc=transform(_.extend(fields,{_id:id}));if(observeCallbacks.addedAt){var index=indices?before?self.docs.indexOf(before):self.docs.size():-1;observeCallbacks.addedAt(doc,index,before)}else{observeCallbacks.added(doc)}},changed:function(id,fields){var self=this;if(!(observeCallbacks.changedAt||observeCallbacks.changed))return;var doc=EJSON.clone(self.docs.get(id));if(!doc)throw new Error("Unknown id for changed: "+id);var oldDoc=transform(EJSON.clone(doc));LocalCollection._applyChanges(doc,fields);doc=transform(doc);if(observeCallbacks.changedAt){var index=indices?self.docs.indexOf(id):-1;observeCallbacks.changedAt(doc,oldDoc,index)}else{observeCallbacks.changed(doc,oldDoc)}},movedBefore:function(id,before){var self=this;if(!observeCallbacks.movedTo)return;var from=indices?self.docs.indexOf(id):-1;var to=indices?before?self.docs.indexOf(before):self.docs.size():-1;if(to>from)--to;observeCallbacks.movedTo(transform(EJSON.clone(self.docs.get(id))),from,to,before||null)},removed:function(id){var self=this;if(!(observeCallbacks.removedAt||observeCallbacks.removed))return;var doc=transform(self.docs.get(id));if(observeCallbacks.removedAt){var index=indices?self.docs.indexOf(id):-1;observeCallbacks.removedAt(doc,index)}else{observeCallbacks.removed(doc)}}}}else{observeChangesCallbacks={added:function(id,fields){if(!suppressed&&observeCallbacks.added){var doc=_.extend(fields,{_id:id});observeCallbacks.added(transform(doc))}},changed:function(id,fields){var self=this;if(observeCallbacks.changed){var oldDoc=self.docs.get(id);var doc=EJSON.clone(oldDoc);LocalCollection._applyChanges(doc,fields);observeCallbacks.changed(transform(doc),transform(EJSON.clone(oldDoc)))}},removed:function(id){var self=this;if(observeCallbacks.removed){observeCallbacks.removed(transform(self.docs.get(id)))}}}}var changeObserver=new LocalCollection._CachingChangeObserver({callbacks:observeChangesCallbacks});var handle=cursor.observeChanges(changeObserver.applyChange);suppressed=false;return handle}}).call(this);(function(){LocalCollection._looksLikeObjectID=function(str){return str.length===24&&str.match(/^[0-9a-f]*$/)};LocalCollection._ObjectID=function(hexString){var self=this;if(hexString){hexString=hexString.toLowerCase();if(!LocalCollection._looksLikeObjectID(hexString)){throw new Error("Invalid hexadecimal string for creating an ObjectID")}self._str=hexString}else{self._str=Random.hexString(24)}};LocalCollection._ObjectID.prototype.toString=function(){var self=this;return'ObjectID("'+self._str+'")'};LocalCollection._ObjectID.prototype.equals=function(other){var self=this;return other instanceof LocalCollection._ObjectID&&self.valueOf()===other.valueOf()};LocalCollection._ObjectID.prototype.clone=function(){var self=this;return new LocalCollection._ObjectID(self._str)};LocalCollection._ObjectID.prototype.typeName=function(){return"oid"};LocalCollection._ObjectID.prototype.getTimestamp=function(){var self=this;return parseInt(self._str.substr(0,8),16)};LocalCollection._ObjectID.prototype.valueOf=LocalCollection._ObjectID.prototype.toJSONValue=LocalCollection._ObjectID.prototype.toHexString=function(){return this._str};LocalCollection._selectorIsId=function(selector){return typeof selector==="string"||typeof selector==="number"||selector instanceof LocalCollection._ObjectID};LocalCollection._selectorIsIdPerhapsAsObject=function(selector){return LocalCollection._selectorIsId(selector)||selector&&typeof selector==="object"&&selector._id&&LocalCollection._selectorIsId(selector._id)&&_.size(selector)===1};LocalCollection._idsMatchedBySelector=function(selector){if(LocalCollection._selectorIsId(selector))return[selector];if(!selector)return null;if(_.has(selector,"_id")){if(LocalCollection._selectorIsId(selector._id))return[selector._id];if(selector._id&&selector._id.$in&&_.isArray(selector._id.$in)&&!_.isEmpty(selector._id.$in)&&_.all(selector._id.$in,LocalCollection._selectorIsId)){return selector._id.$in}return null}if(selector.$and&&_.isArray(selector.$and)){for(var i=0;i<selector.$and.length;++i){var subIds=LocalCollection._idsMatchedBySelector(selector.$and[i]);if(subIds)return subIds}}return null};EJSON.addType("oid",function(str){return new LocalCollection._ObjectID(str)})}).call(this);if(typeof Package==="undefined")Package={};Package.minimongo={LocalCollection:LocalCollection,Minimongo:Minimongo,MinimongoTest:MinimongoTest}})();(function(){var Meteor=Package.meteor.Meteor;var _=Package.underscore._;var EJSON=Package.ejson.EJSON;var Log;(function(){Log=function(){return Log.info.apply(this,arguments)};var intercept=0;var interceptedLines=[];var suppress=0;Log._intercept=function(count){intercept+=count};Log._suppress=function(count){suppress+=count};Log._intercepted=function(){var lines=interceptedLines;interceptedLines=[];intercept=0;return lines};Log.outputFormat="json";var LEVEL_COLORS={debug:"green",warn:"magenta",error:"red"};var META_COLOR="blue";var RESTRICTED_KEYS=["time","timeInexact","level","file","line","program","originApp","satellite","stderr"];var FORMATTED_KEYS=RESTRICTED_KEYS.concat(["app","message"]);var logInBrowser=function(obj){var str=Log.format(obj);var level=obj.level;if(typeof console!=="undefined"&&console[level]){console[level](str)}else{Meteor._debug(str)}};Log._getCallerDetails=function(){var getStack=function(){var err=new Error;var stack=err.stack;return stack};var stack=getStack();if(!stack)return{};var lines=stack.split("\n");var line;for(var i=1;i<lines.length;++i){line=lines[i];if(line.match(/^\s*at eval \(eval/)){return{file:"eval"}}if(!line.match(/packages\/(?:local-test:)?logging(?:\/|\.js)/))break}var details={};var match=/(?:[@(]| at )([^(]+?):([0-9:]+)(?:\)|$)/.exec(line);if(!match)return details;details.line=match[2].split(":")[0];details.file=match[1].split("/").slice(-1)[0].split("?")[0];return details};_.each(["debug","info","warn","error"],function(level){Log[level]=function(arg){if(suppress){suppress--;return}var intercepted=false;if(intercept){intercept--;intercepted=true}var obj=_.isObject(arg)&&!_.isRegExp(arg)&&!_.isDate(arg)?arg:{message:new String(arg).toString()};_.each(RESTRICTED_KEYS,function(key){if(obj[key])throw new Error("Can't set '"+key+"' in log message")});if(_.has(obj,"message")&&!_.isString(obj.message))throw new Error("The 'message' field in log objects must be a string");if(!obj.omitCallerDetails)obj=_.extend(Log._getCallerDetails(),obj);obj.time=new Date;obj.level=level;if(level==="debug")return;if(intercepted){interceptedLines.push(EJSON.stringify(obj))}else if(Meteor.isServer){if(Log.outputFormat==="colored-text"){console.log(Log.format(obj,{color:true}))}else if(Log.outputFormat==="json"){console.log(EJSON.stringify(obj))}else{throw new Error("Unknown logging output format: "+Log.outputFormat)}}else{logInBrowser(obj)}}});Log.parse=function(line){var obj=null;if(line&&line.charAt(0)==="{"){try{obj=EJSON.parse(line)}catch(e){}}if(obj&&obj.time&&obj.time instanceof Date)return obj;else return null};Log.format=function(obj,options){obj=EJSON.clone(obj);options=options||{};var time=obj.time;if(!(time instanceof Date))throw new Error("'time' must be a Date object");var timeInexact=obj.timeInexact;var level=obj.level||"info";var file=obj.file;var lineNumber=obj.line;var appName=obj.app||"";var originApp=obj.originApp;var message=obj.message||"";var program=obj.program||"";var satellite=obj.satellite;var stderr=obj.stderr||"";_.each(FORMATTED_KEYS,function(key){delete obj[key]});if(!_.isEmpty(obj)){if(message)message+=" ";message+=EJSON.stringify(obj)}var pad2=function(n){return n<10?"0"+n:n.toString()};var pad3=function(n){return n<100?"0"+pad2(n):n.toString()};var dateStamp=time.getFullYear().toString()+pad2(time.getMonth()+1)+pad2(time.getDate());var timeStamp=pad2(time.getHours())+":"+pad2(time.getMinutes())+":"+pad2(time.getSeconds())+"."+pad3(time.getMilliseconds());var utcOffsetStr="("+-((new Date).getTimezoneOffset()/60)+")";var appInfo="";if(appName)appInfo+=appName;if(originApp&&originApp!==appName)appInfo+=" via "+originApp;if(appInfo)appInfo="["+appInfo+"] ";var sourceInfoParts=[];if(program)sourceInfoParts.push(program);if(file)sourceInfoParts.push(file);if(lineNumber)sourceInfoParts.push(lineNumber);var sourceInfo=_.isEmpty(sourceInfoParts)?"":"("+sourceInfoParts.join(":")+") ";if(satellite)sourceInfo+=["[",satellite,"]"].join("");var stderrIndicator=stderr?"(STDERR) ":"";var metaPrefix=[level.charAt(0).toUpperCase(),dateStamp,"-",timeStamp,utcOffsetStr,timeInexact?"? ":" ",appInfo,sourceInfo,stderrIndicator].join("");var prettify=function(line,color){return options.color&&Meteor.isServer&&color?Npm.require("cli-color")[color](line):line};return prettify(metaPrefix,options.metaColor||META_COLOR)+prettify(message,LEVEL_COLORS[level])};Log.objFromText=function(line,override){var obj={message:line,level:"info",time:new Date,timeInexact:true};return _.extend(obj,override)}}).call(this);if(typeof Package==="undefined")Package={};Package.logging={Log:Log}})();(function(){var Meteor=Package.meteor.Meteor;var check=Package.check.check;var Match=Package.check.Match;var Random=Package.random.Random;var EJSON=Package.ejson.EJSON;var JSON=Package.json.JSON;var _=Package.underscore._;var Tracker=Package.tracker.Tracker;var Deps=Package.tracker.Deps;var Log=Package.logging.Log;var Retry=Package.retry.Retry;var LocalCollection=Package.minimongo.LocalCollection;var Minimongo=Package.minimongo.Minimongo;var DDP,LivedataTest,SockJS,toSockjsUrl,toWebsocketUrl,Heartbeat,SUPPORTED_DDP_VERSIONS,MethodInvocation,parseDDP,stringifyDDP,RandomStream,makeRpcSeed,allConnections;(function(){DDP={};LivedataTest={}}).call(this);(function(){SockJS=function(){var _document=document;var _window=window;var utils={};var REventTarget=function(){};REventTarget.prototype.addEventListener=function(eventType,listener){if(!this._listeners){this._listeners={}}if(!(eventType in this._listeners)){this._listeners[eventType]=[]}var arr=this._listeners[eventType];if(utils.arrIndexOf(arr,listener)===-1){arr.push(listener)}return};REventTarget.prototype.removeEventListener=function(eventType,listener){if(!(this._listeners&&eventType in this._listeners)){return}var arr=this._listeners[eventType];var idx=utils.arrIndexOf(arr,listener);if(idx!==-1){if(arr.length>1){this._listeners[eventType]=arr.slice(0,idx).concat(arr.slice(idx+1))}else{delete this._listeners[eventType]}return}return};REventTarget.prototype.dispatchEvent=function(event){var t=event.type;var args=Array.prototype.slice.call(arguments,0);if(this["on"+t]){this["on"+t].apply(this,args)}if(this._listeners&&t in this._listeners){for(var i=0;i<this._listeners[t].length;i++){this._listeners[t][i].apply(this,args)}}};var SimpleEvent=function(type,obj){this.type=type;if(typeof obj!=="undefined"){for(var k in obj){if(!obj.hasOwnProperty(k))continue;this[k]=obj[k]}}};SimpleEvent.prototype.toString=function(){var r=[];for(var k in this){if(!this.hasOwnProperty(k))continue;var v=this[k];if(typeof v==="function")v="[function]";r.push(k+"="+v)}return"SimpleEvent("+r.join(", ")+")"};var EventEmitter=function(events){var that=this;that._events=events||[];that._listeners={}};EventEmitter.prototype.emit=function(type){var that=this;that._verifyType(type);if(that._nuked)return;var args=Array.prototype.slice.call(arguments,1);if(that["on"+type]){that["on"+type].apply(that,args)}if(type in that._listeners){for(var i=0;i<that._listeners[type].length;i++){that._listeners[type][i].apply(that,args)}}};EventEmitter.prototype.on=function(type,callback){var that=this;that._verifyType(type);if(that._nuked)return;if(!(type in that._listeners)){that._listeners[type]=[]}that._listeners[type].push(callback)};EventEmitter.prototype._verifyType=function(type){var that=this;if(utils.arrIndexOf(that._events,type)===-1){utils.log("Event "+JSON.stringify(type)+" not listed "+JSON.stringify(that._events)+" in "+that)}};EventEmitter.prototype.nuke=function(){var that=this;that._nuked=true;for(var i=0;i<that._events.length;i++){delete that[that._events[i]]}that._listeners={}};var random_string_chars="abcdefghijklmnopqrstuvwxyz0123456789_";utils.random_string=function(length,max){max=max||random_string_chars.length;var i,ret=[];for(i=0;i<length;i++){ret.push(random_string_chars.substr(Math.floor(Math.random()*max),1))}return ret.join("")};utils.random_number=function(max){return Math.floor(Math.random()*max)};utils.random_number_string=function(max){var t=(""+(max-1)).length;var p=Array(t+1).join("0");return(p+utils.random_number(max)).slice(-t)};utils.getOrigin=function(url){url+="/";var parts=url.split("/").slice(0,3);return parts.join("/")};utils.isSameOriginUrl=function(url_a,url_b){if(!url_b)url_b=_window.location.href;return url_a.split("/").slice(0,3).join("/")===url_b.split("/").slice(0,3).join("/")};utils.isSameOriginScheme=function(url_a,url_b){if(!url_b)url_b=_window.location.href;return url_a.split(":")[0]===url_b.split(":")[0]};utils.getParentDomain=function(url){if(/^[0-9.]*$/.test(url))return url;if(/^\[/.test(url))return url;if(!/[.]/.test(url))return url;var parts=url.split(".").slice(1);return parts.join(".")};utils.objectExtend=function(dst,src){for(var k in src){if(src.hasOwnProperty(k)){dst[k]=src[k]}}return dst};var WPrefix="_jp";utils.polluteGlobalNamespace=function(){if(!(WPrefix in _window)){_window[WPrefix]={}}};utils.closeFrame=function(code,reason){return"c"+JSON.stringify([code,reason])};utils.userSetCode=function(code){return code===1e3||code>=3e3&&code<=4999};utils.countRTO=function(rtt){var rto;if(rtt>100){rto=3*rtt}else{rto=rtt+200}return rto};utils.log=function(){if(_window.console&&console.log&&console.log.apply){console.log.apply(console,arguments)}};utils.bind=function(fun,that){if(fun.bind){return fun.bind(that)}else{return function(){return fun.apply(that,arguments)}}};utils.flatUrl=function(url){return url.indexOf("?")===-1&&url.indexOf("#")===-1};utils.amendUrl=function(url,relativeTo){var baseUrl;if(relativeTo===undefined){baseUrl=_document.location}else{var protocolMatch=/^([a-z0-9.+-]+:)/i.exec(relativeTo);if(protocolMatch){var protocol=protocolMatch[0].toLowerCase();var rest=relativeTo.substring(protocol.length);var hostMatch=/[a-z0-9\.-]+(:[0-9]+)?/.exec(rest);if(hostMatch)var host=hostMatch[0]}if(!protocol||!host)throw new Error("relativeTo must be an absolute url");baseUrl={protocol:protocol,host:host}}if(!url){throw new Error("Wrong url for SockJS")}if(!utils.flatUrl(url)){throw new Error("Only basic urls are supported in SockJS")}if(url.indexOf("//")===0){url=baseUrl.protocol+url}if(url.indexOf("/")===0){url=baseUrl.protocol+"//"+baseUrl.host+url}url=url.replace(/[/]+$/,"");var parts=url.split("/");if(parts[0]==="http:"&&/:80$/.test(parts[2])||parts[0]==="https:"&&/:443$/.test(parts[2])){parts[2]=parts[2].replace(/:(80|443)$/,"")}url=parts.join("/");return url};utils.arrIndexOf=function(arr,obj){for(var i=0;i<arr.length;i++){if(arr[i]===obj){return i}}return-1};utils.arrSkip=function(arr,obj){var idx=utils.arrIndexOf(arr,obj);if(idx===-1){return arr.slice()}else{var dst=arr.slice(0,idx);return dst.concat(arr.slice(idx+1))}};utils.isArray=Array.isArray||function(value){return{}.toString.call(value).indexOf("Array")>=0};utils.delay=function(t,fun){if(typeof t==="function"){fun=t;t=0}return setTimeout(fun,t)};var json_escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,json_lookup={"\x00":"\\u0000","":"\\u0001","":"\\u0002","":"\\u0003","":"\\u0004","":"\\u0005","":"\\u0006","":"\\u0007","\b":"\\b"," ":"\\t","\n":"\\n","":"\\u000b","\f":"\\f","\r":"\\r","":"\\u000e","":"\\u000f","":"\\u0010","":"\\u0011","":"\\u0012","":"\\u0013","":"\\u0014","":"\\u0015","":"\\u0016","":"\\u0017","":"\\u0018","":"\\u0019","":"\\u001a","":"\\u001b","":"\\u001c","":"\\u001d","":"\\u001e","":"\\u001f",'"':'\\"',"\\":"\\\\","":"\\u007f","":"\\u0080","":"\\u0081","":"\\u0082","":"\\u0083","":"\\u0084"," ":"\\u0085","":"\\u0086","":"\\u0087","":"\\u0088","":"\\u0089","":"\\u008a","":"\\u008b","":"\\u008c","":"\\u008d","":"\\u008e","":"\\u008f","":"\\u0090","":"\\u0091","":"\\u0092","":"\\u0093","":"\\u0094","":"\\u0095","":"\\u0096","":"\\u0097","":"\\u0098","":"\\u0099","":"\\u009a","":"\\u009b","":"\\u009c","":"\\u009d","":"\\u009e","":"\\u009f","":"\\u00ad","":"\\u0600","":"\\u0601","":"\\u0602","":"\\u0603","":"\\u0604","":"\\u070f","឴":"\\u17b4","឵":"\\u17b5","":"\\u200c","":"\\u200d","":"\\u200e","":"\\u200f","\u2028":"\\u2028","\u2029":"\\u2029","":"\\u202a","":"\\u202b","":"\\u202c","":"\\u202d","":"\\u202e"," ":"\\u202f","":"\\u2060","":"\\u2061","":"\\u2062","":"\\u2063","":"\\u2064","":"\\u2065","":"\\u2066","":"\\u2067","":"\\u2068","":"\\u2069","":"\\u206a","":"\\u206b","":"\\u206c","":"\\u206d","":"\\u206e","":"\\u206f","\ufeff":"\\ufeff","":"\\ufff0","":"\\ufff1","":"\\ufff2","":"\\ufff3","":"\\ufff4","":"\\ufff5","":"\\ufff6","":"\\ufff7","":"\\ufff8","":"\\ufff9","":"\\ufffa","":"\\ufffb","":"\\ufffc","�":"\\ufffd","":"\\ufffe","":"\\uffff"};var extra_escapable=/[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g,extra_lookup;var JSONQuote=JSON&&JSON.stringify||function(string){json_escapable.lastIndex=0;if(json_escapable.test(string)){string=string.replace(json_escapable,function(a){return json_lookup[a]})}return'"'+string+'"'};var unroll_lookup=function(escapable){var i;var unrolled={};var c=[];for(i=0;i<65536;i++){c.push(String.fromCharCode(i))}escapable.lastIndex=0;c.join("").replace(escapable,function(a){unrolled[a]="\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4);return""});escapable.lastIndex=0;return unrolled};utils.quote=function(string){var quoted=JSONQuote(string);extra_escapable.lastIndex=0;if(!extra_escapable.test(quoted)){return quoted}if(!extra_lookup)extra_lookup=unroll_lookup(extra_escapable);return quoted.replace(extra_escapable,function(a){return extra_lookup[a]})};var _all_protocols=["websocket","xdr-streaming","xhr-streaming","iframe-eventsource","iframe-htmlfile","xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"];utils.probeProtocols=function(){var probed={};for(var i=0;i<_all_protocols.length;i++){var protocol=_all_protocols[i];probed[protocol]=SockJS[protocol]&&SockJS[protocol].enabled()}return probed};utils.detectProtocols=function(probed,protocols_whitelist,info){var pe={},protocols=[];if(!protocols_whitelist)protocols_whitelist=_all_protocols;for(var i=0;i<protocols_whitelist.length;i++){var protocol=protocols_whitelist[i];pe[protocol]=probed[protocol]}var maybe_push=function(protos){var proto=protos.shift();if(pe[proto]){protocols.push(proto)}else{if(protos.length>0){maybe_push(protos)}}};if(info.websocket!==false){maybe_push(["websocket"])}if(pe["xhr-streaming"]&&!info.null_origin){protocols.push("xhr-streaming")}else{if(pe["xdr-streaming"]&&!info.cookie_needed&&!info.null_origin){protocols.push("xdr-streaming")}else{maybe_push(["iframe-eventsource","iframe-htmlfile"])}}if(pe["xhr-polling"]&&!info.null_origin){protocols.push("xhr-polling")}else{if(pe["xdr-polling"]&&!info.cookie_needed&&!info.null_origin){protocols.push("xdr-polling")}else{maybe_push(["iframe-xhr-polling","jsonp-polling"])}}return protocols};var MPrefix="_sockjs_global";utils.createHook=function(){var window_id="a"+utils.random_string(8);if(!(MPrefix in _window)){var map={};_window[MPrefix]=function(window_id){if(!(window_id in map)){map[window_id]={id:window_id,del:function(){delete map[window_id]}}}return map[window_id]}}return _window[MPrefix](window_id)};utils.attachMessage=function(listener){utils.attachEvent("message",listener)};utils.attachEvent=function(event,listener){if(typeof _window.addEventListener!=="undefined"){_window.addEventListener(event,listener,false)}else{_document.attachEvent("on"+event,listener);_window.attachEvent("on"+event,listener)}};utils.detachMessage=function(listener){utils.detachEvent("message",listener)};utils.detachEvent=function(event,listener){if(typeof _window.addEventListener!=="undefined"){_window.removeEventListener(event,listener,false)}else{_document.detachEvent("on"+event,listener);_window.detachEvent("on"+event,listener)}};var on_unload={};var after_unload=false;var trigger_unload_callbacks=function(){for(var ref in on_unload){on_unload[ref]();delete on_unload[ref]}};var unload_triggered=function(){if(after_unload)return;after_unload=true;trigger_unload_callbacks()};utils.attachEvent("unload",unload_triggered);utils.unload_add=function(listener){var ref=utils.random_string(8);on_unload[ref]=listener;if(after_unload){utils.delay(trigger_unload_callbacks)}return ref};utils.unload_del=function(ref){if(ref in on_unload)delete on_unload[ref]};utils.createIframe=function(iframe_url,error_callback){var iframe=_document.createElement("iframe");var tref,unload_ref;var unattach=function(){clearTimeout(tref);try{iframe.onload=null}catch(x){}iframe.onerror=null};var cleanup=function(){if(iframe){unattach();setTimeout(function(){if(iframe){iframe.parentNode.removeChild(iframe)}iframe=null},0);utils.unload_del(unload_ref)}};var onerror=function(r){if(iframe){cleanup();error_callback(r)}};var post=function(msg,origin){try{if(iframe&&iframe.contentWindow){iframe.contentWindow.postMessage(msg,origin)}}catch(x){}};iframe.src=iframe_url;iframe.style.display="none";iframe.style.position="absolute";iframe.onerror=function(){onerror("onerror")};iframe.onload=function(){clearTimeout(tref);tref=setTimeout(function(){onerror("onload timeout")},2e3)};_document.body.appendChild(iframe);tref=setTimeout(function(){onerror("timeout")},15e3);unload_ref=utils.unload_add(cleanup);return{post:post,cleanup:cleanup,loaded:unattach}};utils.createHtmlfile=function(iframe_url,error_callback){var doc=new ActiveXObject("htmlfile");var tref,unload_ref;var iframe;var unattach=function(){clearTimeout(tref)};var cleanup=function(){if(doc){unattach();utils.unload_del(unload_ref);iframe.parentNode.removeChild(iframe);iframe=doc=null;CollectGarbage()}};var onerror=function(r){if(doc){cleanup();error_callback(r)}};var post=function(msg,origin){try{if(iframe&&iframe.contentWindow){iframe.contentWindow.postMessage(msg,origin)}}catch(x){}};doc.open();doc.write("<html><s"+"cript>"+'document.domain="'+document.domain+'";'+"</s"+"cript></html>");doc.close();doc.parentWindow[WPrefix]=_window[WPrefix];var c=doc.createElement("div");doc.body.appendChild(c);iframe=doc.createElement("iframe");c.appendChild(iframe);iframe.src=iframe_url;tref=setTimeout(function(){onerror("timeout")},15e3);unload_ref=utils.unload_add(cleanup);return{post:post,cleanup:cleanup,loaded:unattach}};var AbstractXHRObject=function(){};AbstractXHRObject.prototype=new EventEmitter(["chunk","finish"]);AbstractXHRObject.prototype._start=function(method,url,payload,opts){var that=this;try{that.xhr=new XMLHttpRequest}catch(x){}if(!that.xhr){try{that.xhr=new _window.ActiveXObject("Microsoft.XMLHTTP")}catch(x){}}if(_window.ActiveXObject||_window.XDomainRequest){url+=(url.indexOf("?")===-1?"?":"&")+"t="+ +new Date}that.unload_ref=utils.unload_add(function(){that._cleanup(true)});try{that.xhr.open(method,url,true)}catch(e){that.emit("finish",0,"");that._cleanup();return}if(!opts||!opts.no_credentials){that.xhr.withCredentials="true"}if(opts&&opts.headers){for(var key in opts.headers){that.xhr.setRequestHeader(key,opts.headers[key])}}that.xhr.onreadystatechange=function(){if(that.xhr){var x=that.xhr;switch(x.readyState){case 3:try{var status=x.status;var text=x.responseText}catch(x){};if(status===1223)status=204;if(text&&text.length>0){that.emit("chunk",status,text)}break;case 4:var status=x.status;if(status===1223)status=204;that.emit("finish",status,x.responseText);that._cleanup(false);break}}};that.xhr.send(payload)};AbstractXHRObject.prototype._cleanup=function(abort){var that=this;if(!that.xhr)return;utils.unload_del(that.unload_ref);that.xhr.onreadystatechange=function(){};if(abort){try{that.xhr.abort()}catch(x){}}that.unload_ref=that.xhr=null};AbstractXHRObject.prototype.close=function(){var that=this;that.nuke();that._cleanup(true)};var XHRCorsObject=utils.XHRCorsObject=function(){var that=this,args=arguments;utils.delay(function(){that._start.apply(that,args); | |
})};XHRCorsObject.prototype=new AbstractXHRObject;var XHRLocalObject=utils.XHRLocalObject=function(method,url,payload){var that=this;utils.delay(function(){that._start(method,url,payload,{no_credentials:true})})};XHRLocalObject.prototype=new AbstractXHRObject;var XDRObject=utils.XDRObject=function(method,url,payload){var that=this;utils.delay(function(){that._start(method,url,payload)})};XDRObject.prototype=new EventEmitter(["chunk","finish"]);XDRObject.prototype._start=function(method,url,payload){var that=this;var xdr=new XDomainRequest;url+=(url.indexOf("?")===-1?"?":"&")+"t="+ +new Date;var onerror=xdr.ontimeout=xdr.onerror=function(){that.emit("finish",0,"");that._cleanup(false)};xdr.onprogress=function(){that.emit("chunk",200,xdr.responseText)};xdr.onload=function(){that.emit("finish",200,xdr.responseText);that._cleanup(false)};that.xdr=xdr;that.unload_ref=utils.unload_add(function(){that._cleanup(true)});try{that.xdr.open(method,url);that.xdr.send(payload)}catch(x){onerror()}};XDRObject.prototype._cleanup=function(abort){var that=this;if(!that.xdr)return;utils.unload_del(that.unload_ref);that.xdr.ontimeout=that.xdr.onerror=that.xdr.onprogress=that.xdr.onload=null;if(abort){try{that.xdr.abort()}catch(x){}}that.unload_ref=that.xdr=null};XDRObject.prototype.close=function(){var that=this;that.nuke();that._cleanup(true)};utils.isXHRCorsCapable=function(){if(_window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest){return 1}if(_window.XDomainRequest&&_document.domain){return 2}if(IframeTransport.enabled()){return 3}return 4};var SockJS=function(url,dep_protocols_whitelist,options){if(!(this instanceof SockJS)){return new SockJS(url,dep_protocols_whitelist,options)}var that=this,protocols_whitelist;that._options={devel:false,debug:false,protocols_whitelist:[],info:undefined,rtt:undefined};if(options){utils.objectExtend(that._options,options)}that._base_url=utils.amendUrl(url);that._server=that._options.server||utils.random_number_string(1e3);if(that._options.protocols_whitelist&&that._options.protocols_whitelist.length){protocols_whitelist=that._options.protocols_whitelist}else{if(typeof dep_protocols_whitelist==="string"&&dep_protocols_whitelist.length>0){protocols_whitelist=[dep_protocols_whitelist]}else if(utils.isArray(dep_protocols_whitelist)){protocols_whitelist=dep_protocols_whitelist}else{protocols_whitelist=null}if(protocols_whitelist){that._debug('Deprecated API: Use "protocols_whitelist" option '+"instead of supplying protocol list as a second "+"parameter to SockJS constructor.")}}that._protocols=[];that.protocol=null;that.readyState=SockJS.CONNECTING;that._ir=createInfoReceiver(that._base_url);that._ir.onfinish=function(info,rtt){that._ir=null;if(info){if(that._options.info){info=utils.objectExtend(info,that._options.info)}if(that._options.rtt){rtt=that._options.rtt}that._applyInfo(info,rtt,protocols_whitelist);that._didClose()}else{that._didClose(1002,"Can't connect to server",true)}}};SockJS.prototype=new REventTarget;SockJS.version="0.3.4";SockJS.CONNECTING=0;SockJS.OPEN=1;SockJS.CLOSING=2;SockJS.CLOSED=3;SockJS.prototype._debug=function(){if(this._options.debug)utils.log.apply(utils,arguments)};SockJS.prototype._dispatchOpen=function(){var that=this;if(that.readyState===SockJS.CONNECTING){if(that._transport_tref){clearTimeout(that._transport_tref);that._transport_tref=null}that.readyState=SockJS.OPEN;that.dispatchEvent(new SimpleEvent("open"))}else{that._didClose(1006,"Server lost session")}};SockJS.prototype._dispatchMessage=function(data){var that=this;if(that.readyState!==SockJS.OPEN)return;that.dispatchEvent(new SimpleEvent("message",{data:data}))};SockJS.prototype._dispatchHeartbeat=function(data){var that=this;if(that.readyState!==SockJS.OPEN)return;that.dispatchEvent(new SimpleEvent("heartbeat",{}))};SockJS.prototype._didClose=function(code,reason,force){var that=this;if(that.readyState!==SockJS.CONNECTING&&that.readyState!==SockJS.OPEN&&that.readyState!==SockJS.CLOSING)throw new Error("INVALID_STATE_ERR");if(that._ir){that._ir.nuke();that._ir=null}if(that._transport){that._transport.doCleanup();that._transport=null}var close_event=new SimpleEvent("close",{code:code,reason:reason,wasClean:utils.userSetCode(code)});if(!utils.userSetCode(code)&&that.readyState===SockJS.CONNECTING&&!force){if(that._try_next_protocol(close_event)){return}close_event=new SimpleEvent("close",{code:2e3,reason:"All transports failed",wasClean:false,last_event:close_event})}that.readyState=SockJS.CLOSED;utils.delay(function(){that.dispatchEvent(close_event)})};SockJS.prototype._didMessage=function(data){var that=this;var type=data.slice(0,1);switch(type){case"o":that._dispatchOpen();break;case"a":var payload=JSON.parse(data.slice(1)||"[]");for(var i=0;i<payload.length;i++){that._dispatchMessage(payload[i])}break;case"m":var payload=JSON.parse(data.slice(1)||"null");that._dispatchMessage(payload);break;case"c":var payload=JSON.parse(data.slice(1)||"[]");that._didClose(payload[0],payload[1]);break;case"h":that._dispatchHeartbeat();break}};SockJS.prototype._try_next_protocol=function(close_event){var that=this;if(that.protocol){that._debug("Closed transport:",that.protocol,""+close_event);that.protocol=null}if(that._transport_tref){clearTimeout(that._transport_tref);that._transport_tref=null}while(1){var protocol=that.protocol=that._protocols.shift();if(!protocol){return false}if(SockJS[protocol]&&SockJS[protocol].need_body===true&&(!_document.body||typeof _document.readyState!=="undefined"&&_document.readyState!=="complete")){that._protocols.unshift(protocol);that.protocol="waiting-for-load";utils.attachEvent("load",function(){that._try_next_protocol()});return true}if(!SockJS[protocol]||!SockJS[protocol].enabled(that._options)){that._debug("Skipping transport:",protocol)}else{var roundTrips=SockJS[protocol].roundTrips||1;var to=(that._options.rto||0)*roundTrips||5e3;that._transport_tref=utils.delay(to,function(){if(that.readyState===SockJS.CONNECTING){that._didClose(2007,"Transport timeouted")}});var connid=utils.random_string(8);var trans_url=that._base_url+"/"+that._server+"/"+connid;that._debug("Opening transport:",protocol," url:"+trans_url," RTO:"+that._options.rto);that._transport=new SockJS[protocol](that,trans_url,that._base_url);return true}}};SockJS.prototype.close=function(code,reason){var that=this;if(code&&!utils.userSetCode(code))throw new Error("INVALID_ACCESS_ERR");if(that.readyState!==SockJS.CONNECTING&&that.readyState!==SockJS.OPEN){return false}that.readyState=SockJS.CLOSING;that._didClose(code||1e3,reason||"Normal closure");return true};SockJS.prototype.send=function(data){var that=this;if(that.readyState===SockJS.CONNECTING)throw new Error("INVALID_STATE_ERR");if(that.readyState===SockJS.OPEN){that._transport.doSend(utils.quote(""+data))}return true};SockJS.prototype._applyInfo=function(info,rtt,protocols_whitelist){var that=this;that._options.info=info;that._options.rtt=rtt;that._options.rto=utils.countRTO(rtt);that._options.info.null_origin=!_document.domain;if(info.base_url)that._base_url=utils.amendUrl(info.base_url,that._base_url);var probed=utils.probeProtocols();that._protocols=utils.detectProtocols(probed,protocols_whitelist,info);if(!utils.isSameOriginScheme(that._base_url)&&2===utils.isXHRCorsCapable()){that._protocols=["jsonp-polling"]}};var WebSocketTransport=SockJS.websocket=function(ri,trans_url){var that=this;var url=trans_url+"/websocket";if(url.slice(0,5)==="https"){url="wss"+url.slice(5)}else{url="ws"+url.slice(4)}that.ri=ri;that.url=url;var Constructor=_window.WebSocket||_window.MozWebSocket;that.ws=new Constructor(that.url);that.ws.onmessage=function(e){that.ri._didMessage(e.data)};that.unload_ref=utils.unload_add(function(){that.ws.close()});that.ws.onclose=function(){that.ri._didMessage(utils.closeFrame(1006,"WebSocket connection broken"))}};WebSocketTransport.prototype.doSend=function(data){this.ws.send("["+data+"]")};WebSocketTransport.prototype.doCleanup=function(){var that=this;var ws=that.ws;if(ws){ws.onmessage=ws.onclose=null;ws.close();utils.unload_del(that.unload_ref);that.unload_ref=that.ri=that.ws=null}};WebSocketTransport.enabled=function(){return!!(_window.WebSocket||_window.MozWebSocket)};WebSocketTransport.roundTrips=2;var BufferedSender=function(){};BufferedSender.prototype.send_constructor=function(sender){var that=this;that.send_buffer=[];that.sender=sender};BufferedSender.prototype.doSend=function(message){var that=this;that.send_buffer.push(message);if(!that.send_stop){that.send_schedule()}};BufferedSender.prototype.send_schedule_wait=function(){var that=this;var tref;that.send_stop=function(){that.send_stop=null;clearTimeout(tref)};tref=utils.delay(25,function(){that.send_stop=null;that.send_schedule()})};BufferedSender.prototype.send_schedule=function(){var that=this;if(that.send_buffer.length>0){var payload="["+that.send_buffer.join(",")+"]";that.send_stop=that.sender(that.trans_url,payload,function(success,abort_reason){that.send_stop=null;if(success===false){that.ri._didClose(1006,"Sending error "+abort_reason)}else{that.send_schedule_wait()}});that.send_buffer=[]}};BufferedSender.prototype.send_destructor=function(){var that=this;if(that._send_stop){that._send_stop()}that._send_stop=null};var jsonPGenericSender=function(url,payload,callback){var that=this;if(!("_send_form"in that)){var form=that._send_form=_document.createElement("form");var area=that._send_area=_document.createElement("textarea");area.name="d";form.style.display="none";form.style.position="absolute";form.method="POST";form.enctype="application/x-www-form-urlencoded";form.acceptCharset="UTF-8";form.appendChild(area);_document.body.appendChild(form)}var form=that._send_form;var area=that._send_area;var id="a"+utils.random_string(8);form.target=id;form.action=url+"/jsonp_send?i="+id;var iframe;try{iframe=_document.createElement('<iframe name="'+id+'">')}catch(x){iframe=_document.createElement("iframe");iframe.name=id}iframe.id=id;form.appendChild(iframe);iframe.style.display="none";try{area.value=payload}catch(e){utils.log("Your browser is seriously broken. Go home! "+e.message)}form.submit();var completed=function(e){if(!iframe.onerror)return;iframe.onreadystatechange=iframe.onerror=iframe.onload=null;utils.delay(500,function(){iframe.parentNode.removeChild(iframe);iframe=null});area.value="";callback(true)};iframe.onerror=iframe.onload=completed;iframe.onreadystatechange=function(e){if(iframe.readyState=="complete")completed()};return completed};var createAjaxSender=function(AjaxObject){return function(url,payload,callback){var xo=new AjaxObject("POST",url+"/xhr_send",payload);xo.onfinish=function(status,text){callback(status===200||status===204,"http status "+status)};return function(abort_reason){callback(false,abort_reason)}}};var jsonPGenericReceiver=function(url,callback){var tref;var script=_document.createElement("script");var script2;var close_script=function(frame){if(script2){script2.parentNode.removeChild(script2);script2=null}if(script){clearTimeout(tref);script.parentNode.removeChild(script);script.onreadystatechange=script.onerror=script.onload=script.onclick=null;script=null;callback(frame);callback=null}};var loaded_okay=false;var error_timer=null;script.id="a"+utils.random_string(8);script.src=url;script.type="text/javascript";script.charset="UTF-8";script.onerror=function(e){if(!error_timer){error_timer=setTimeout(function(){if(!loaded_okay){close_script(utils.closeFrame(1006,"JSONP script loaded abnormally (onerror)"))}},1e3)}};script.onload=function(e){close_script(utils.closeFrame(1006,"JSONP script loaded abnormally (onload)"))};script.onreadystatechange=function(e){if(/loaded|closed/.test(script.readyState)){if(script&&script.htmlFor&&script.onclick){loaded_okay=true;try{script.onclick()}catch(x){}}if(script){close_script(utils.closeFrame(1006,"JSONP script loaded abnormally (onreadystatechange)"))}}};if(typeof script.async==="undefined"&&_document.attachEvent){if(!/opera/i.test(navigator.userAgent)){try{script.htmlFor=script.id;script.event="onclick"}catch(x){}script.async=true}else{script2=_document.createElement("script");script2.text="try{var a = document.getElementById('"+script.id+"'); if(a)a.onerror();}catch(x){};";script.async=script2.async=false}}if(typeof script.async!=="undefined"){script.async=true}tref=setTimeout(function(){close_script(utils.closeFrame(1006,"JSONP script loaded abnormally (timeout)"))},35e3);var head=_document.getElementsByTagName("head")[0];head.insertBefore(script,head.firstChild);if(script2){head.insertBefore(script2,head.firstChild)}return close_script};var JsonPTransport=SockJS["jsonp-polling"]=function(ri,trans_url){utils.polluteGlobalNamespace();var that=this;that.ri=ri;that.trans_url=trans_url;that.send_constructor(jsonPGenericSender);that._schedule_recv()};JsonPTransport.prototype=new BufferedSender;JsonPTransport.prototype._schedule_recv=function(){var that=this;var callback=function(data){that._recv_stop=null;if(data){if(!that._is_closing){that.ri._didMessage(data)}}if(!that._is_closing){that._schedule_recv()}};that._recv_stop=jsonPReceiverWrapper(that.trans_url+"/jsonp",jsonPGenericReceiver,callback)};JsonPTransport.enabled=function(){return true};JsonPTransport.need_body=true;JsonPTransport.prototype.doCleanup=function(){var that=this;that._is_closing=true;if(that._recv_stop){that._recv_stop()}that.ri=that._recv_stop=null;that.send_destructor()};var jsonPReceiverWrapper=function(url,constructReceiver,user_callback){var id="a"+utils.random_string(6);var url_id=url+"?c="+escape(WPrefix+"."+id);var aborting=0;var callback=function(frame){switch(aborting){case 0:delete _window[WPrefix][id];user_callback(frame);break;case 1:user_callback(frame);aborting=2;break;case 2:delete _window[WPrefix][id];break}};var close_script=constructReceiver(url_id,callback);_window[WPrefix][id]=close_script;var stop=function(){if(_window[WPrefix][id]){aborting=1;_window[WPrefix][id](utils.closeFrame(1e3,"JSONP user aborted read"))}};return stop};var AjaxBasedTransport=function(){};AjaxBasedTransport.prototype=new BufferedSender;AjaxBasedTransport.prototype.run=function(ri,trans_url,url_suffix,Receiver,AjaxObject){var that=this;that.ri=ri;that.trans_url=trans_url;that.send_constructor(createAjaxSender(AjaxObject));that.poll=new Polling(ri,Receiver,trans_url+url_suffix,AjaxObject)};AjaxBasedTransport.prototype.doCleanup=function(){var that=this;if(that.poll){that.poll.abort();that.poll=null}};var XhrStreamingTransport=SockJS["xhr-streaming"]=function(ri,trans_url){this.run(ri,trans_url,"/xhr_streaming",XhrReceiver,utils.XHRCorsObject)};XhrStreamingTransport.prototype=new AjaxBasedTransport;XhrStreamingTransport.enabled=function(){return _window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest&&!/opera/i.test(navigator.userAgent)};XhrStreamingTransport.roundTrips=2;XhrStreamingTransport.need_body=true;var XdrStreamingTransport=SockJS["xdr-streaming"]=function(ri,trans_url){this.run(ri,trans_url,"/xhr_streaming",XhrReceiver,utils.XDRObject)};XdrStreamingTransport.prototype=new AjaxBasedTransport;XdrStreamingTransport.enabled=function(){return!!_window.XDomainRequest};XdrStreamingTransport.roundTrips=2;var XhrPollingTransport=SockJS["xhr-polling"]=function(ri,trans_url){this.run(ri,trans_url,"/xhr",XhrReceiver,utils.XHRCorsObject)};XhrPollingTransport.prototype=new AjaxBasedTransport;XhrPollingTransport.enabled=XhrStreamingTransport.enabled;XhrPollingTransport.roundTrips=2;var XdrPollingTransport=SockJS["xdr-polling"]=function(ri,trans_url){this.run(ri,trans_url,"/xhr",XhrReceiver,utils.XDRObject)};XdrPollingTransport.prototype=new AjaxBasedTransport;XdrPollingTransport.enabled=XdrStreamingTransport.enabled;XdrPollingTransport.roundTrips=2;var IframeTransport=function(){};IframeTransport.prototype.i_constructor=function(ri,trans_url,base_url){var that=this;that.ri=ri;that.origin=utils.getOrigin(base_url);that.base_url=base_url;that.trans_url=trans_url;var iframe_url=base_url+"/iframe.html";if(that.ri._options.devel){iframe_url+="?t="+ +new Date}that.window_id=utils.random_string(8);iframe_url+="#"+that.window_id;that.iframeObj=utils.createIframe(iframe_url,function(r){that.ri._didClose(1006,"Unable to load an iframe ("+r+")")});that.onmessage_cb=utils.bind(that.onmessage,that);utils.attachMessage(that.onmessage_cb)};IframeTransport.prototype.doCleanup=function(){var that=this;if(that.iframeObj){utils.detachMessage(that.onmessage_cb);try{if(that.iframeObj.iframe.contentWindow){that.postMessage("c")}}catch(x){}that.iframeObj.cleanup();that.iframeObj=null;that.onmessage_cb=that.iframeObj=null}};IframeTransport.prototype.onmessage=function(e){var that=this;if(e.origin!==that.origin)return;var window_id=e.data.slice(0,8);var type=e.data.slice(8,9);var data=e.data.slice(9);if(window_id!==that.window_id)return;switch(type){case"s":that.iframeObj.loaded();that.postMessage("s",JSON.stringify([SockJS.version,that.protocol,that.trans_url,that.base_url]));break;case"t":that.ri._didMessage(data);break}};IframeTransport.prototype.postMessage=function(type,data){var that=this;that.iframeObj.post(that.window_id+type+(data||""),that.origin)};IframeTransport.prototype.doSend=function(message){this.postMessage("m",message)};IframeTransport.enabled=function(){var konqueror=navigator&&navigator.userAgent&&navigator.userAgent.indexOf("Konqueror")!==-1;return(typeof _window.postMessage==="function"||typeof _window.postMessage==="object")&&!konqueror};var curr_window_id;var postMessage=function(type,data){if(parent!==_window){parent.postMessage(curr_window_id+type+(data||""),"*")}else{utils.log("Can't postMessage, no parent window.",type,data)}};var FacadeJS=function(){};FacadeJS.prototype._didClose=function(code,reason){postMessage("t",utils.closeFrame(code,reason))};FacadeJS.prototype._didMessage=function(frame){postMessage("t",frame)};FacadeJS.prototype._doSend=function(data){this._transport.doSend(data)};FacadeJS.prototype._doCleanup=function(){this._transport.doCleanup()};utils.parent_origin=undefined;SockJS.bootstrap_iframe=function(){var facade;curr_window_id=_document.location.hash.slice(1);var onMessage=function(e){if(e.source!==parent)return;if(typeof utils.parent_origin==="undefined")utils.parent_origin=e.origin;if(e.origin!==utils.parent_origin)return;var window_id=e.data.slice(0,8);var type=e.data.slice(8,9);var data=e.data.slice(9);if(window_id!==curr_window_id)return;switch(type){case"s":var p=JSON.parse(data);var version=p[0];var protocol=p[1];var trans_url=p[2];var base_url=p[3];if(version!==SockJS.version){utils.log("Incompatibile SockJS! Main site uses:"+' "'+version+'", the iframe:'+' "'+SockJS.version+'".')}if(!utils.flatUrl(trans_url)||!utils.flatUrl(base_url)){utils.log("Only basic urls are supported in SockJS");return}if(!utils.isSameOriginUrl(trans_url)||!utils.isSameOriginUrl(base_url)){utils.log("Can't connect to different domain from within an "+"iframe. ("+JSON.stringify([_window.location.href,trans_url,base_url])+")");return}facade=new FacadeJS;facade._transport=new FacadeJS[protocol](facade,trans_url,base_url);break;case"m":facade._doSend(data);break;case"c":if(facade)facade._doCleanup();facade=null;break}};utils.attachMessage(onMessage);postMessage("s")};var InfoReceiver=function(base_url,AjaxObject){var that=this;utils.delay(function(){that.doXhr(base_url,AjaxObject)})};InfoReceiver.prototype=new EventEmitter(["finish"]);InfoReceiver.prototype.doXhr=function(base_url,AjaxObject){var that=this;var t0=(new Date).getTime();var xo=new AjaxObject("GET",base_url+"/info?cb="+utils.random_string(10));var tref=utils.delay(8e3,function(){xo.ontimeout()});xo.onfinish=function(status,text){clearTimeout(tref);tref=null;if(status===200){var rtt=(new Date).getTime()-t0;var info=JSON.parse(text);if(typeof info!=="object")info={};that.emit("finish",info,rtt)}else{that.emit("finish")}};xo.ontimeout=function(){xo.close();that.emit("finish")}};var InfoReceiverIframe=function(base_url){var that=this;var go=function(){var ifr=new IframeTransport;ifr.protocol="w-iframe-info-receiver";var fun=function(r){if(typeof r==="string"&&r.substr(0,1)==="m"){var d=JSON.parse(r.substr(1));var info=d[0],rtt=d[1];that.emit("finish",info,rtt)}else{that.emit("finish")}ifr.doCleanup();ifr=null};var mock_ri={_options:{},_didClose:fun,_didMessage:fun};ifr.i_constructor(mock_ri,base_url,base_url)};if(!_document.body){utils.attachEvent("load",go)}else{go()}};InfoReceiverIframe.prototype=new EventEmitter(["finish"]);var InfoReceiverFake=function(){var that=this;utils.delay(function(){that.emit("finish",{},2e3)})};InfoReceiverFake.prototype=new EventEmitter(["finish"]);var createInfoReceiver=function(base_url){if(utils.isSameOriginUrl(base_url)){return new InfoReceiver(base_url,utils.XHRLocalObject)}switch(utils.isXHRCorsCapable()){case 1:return new InfoReceiver(base_url,utils.XHRLocalObject);case 2:if(utils.isSameOriginScheme(base_url))return new InfoReceiver(base_url,utils.XDRObject);else return new InfoReceiverFake;case 3:return new InfoReceiverIframe(base_url);default:return new InfoReceiverFake}};var WInfoReceiverIframe=FacadeJS["w-iframe-info-receiver"]=function(ri,_trans_url,base_url){var ir=new InfoReceiver(base_url,utils.XHRLocalObject);ir.onfinish=function(info,rtt){ri._didMessage("m"+JSON.stringify([info,rtt]));ri._didClose()}};WInfoReceiverIframe.prototype.doCleanup=function(){};var EventSourceIframeTransport=SockJS["iframe-eventsource"]=function(){var that=this;that.protocol="w-iframe-eventsource";that.i_constructor.apply(that,arguments)};EventSourceIframeTransport.prototype=new IframeTransport;EventSourceIframeTransport.enabled=function(){return"EventSource"in _window&&IframeTransport.enabled()};EventSourceIframeTransport.need_body=true;EventSourceIframeTransport.roundTrips=3;var EventSourceTransport=FacadeJS["w-iframe-eventsource"]=function(ri,trans_url){this.run(ri,trans_url,"/eventsource",EventSourceReceiver,utils.XHRLocalObject)};EventSourceTransport.prototype=new AjaxBasedTransport;var XhrPollingIframeTransport=SockJS["iframe-xhr-polling"]=function(){var that=this;that.protocol="w-iframe-xhr-polling";that.i_constructor.apply(that,arguments)};XhrPollingIframeTransport.prototype=new IframeTransport;XhrPollingIframeTransport.enabled=function(){return _window.XMLHttpRequest&&IframeTransport.enabled()};XhrPollingIframeTransport.need_body=true;XhrPollingIframeTransport.roundTrips=3;var XhrPollingITransport=FacadeJS["w-iframe-xhr-polling"]=function(ri,trans_url){this.run(ri,trans_url,"/xhr",XhrReceiver,utils.XHRLocalObject)};XhrPollingITransport.prototype=new AjaxBasedTransport;var HtmlFileIframeTransport=SockJS["iframe-htmlfile"]=function(){var that=this;that.protocol="w-iframe-htmlfile";that.i_constructor.apply(that,arguments)};HtmlFileIframeTransport.prototype=new IframeTransport;HtmlFileIframeTransport.enabled=function(){return IframeTransport.enabled()};HtmlFileIframeTransport.need_body=true;HtmlFileIframeTransport.roundTrips=3;var HtmlFileTransport=FacadeJS["w-iframe-htmlfile"]=function(ri,trans_url){this.run(ri,trans_url,"/htmlfile",HtmlfileReceiver,utils.XHRLocalObject)};HtmlFileTransport.prototype=new AjaxBasedTransport;var Polling=function(ri,Receiver,recv_url,AjaxObject){var that=this;that.ri=ri;that.Receiver=Receiver;that.recv_url=recv_url;that.AjaxObject=AjaxObject;that._scheduleRecv()};Polling.prototype._scheduleRecv=function(){var that=this;var poll=that.poll=new that.Receiver(that.recv_url,that.AjaxObject);var msg_counter=0;poll.onmessage=function(e){msg_counter+=1;that.ri._didMessage(e.data)};poll.onclose=function(e){that.poll=poll=poll.onmessage=poll.onclose=null;if(!that.poll_is_closing){if(e.reason==="permanent"){that.ri._didClose(1006,"Polling error ("+e.reason+")")}else{that._scheduleRecv()}}}};Polling.prototype.abort=function(){var that=this;that.poll_is_closing=true;if(that.poll){that.poll.abort()}};var EventSourceReceiver=function(url){var that=this;var es=new EventSource(url);es.onmessage=function(e){that.dispatchEvent(new SimpleEvent("message",{data:unescape(e.data)}))};that.es_close=es.onerror=function(e,abort_reason){var reason=abort_reason?"user":es.readyState!==2?"network":"permanent";that.es_close=es.onmessage=es.onerror=null;es.close();es=null;utils.delay(200,function(){that.dispatchEvent(new SimpleEvent("close",{reason:reason}))})}};EventSourceReceiver.prototype=new REventTarget;EventSourceReceiver.prototype.abort=function(){var that=this;if(that.es_close){that.es_close({},true)}};var _is_ie_htmlfile_capable;var isIeHtmlfileCapable=function(){if(_is_ie_htmlfile_capable===undefined){if("ActiveXObject"in _window){try{_is_ie_htmlfile_capable=!!new ActiveXObject("htmlfile")}catch(x){}}else{_is_ie_htmlfile_capable=false}}return _is_ie_htmlfile_capable};var HtmlfileReceiver=function(url){var that=this;utils.polluteGlobalNamespace();that.id="a"+utils.random_string(6,26);url+=(url.indexOf("?")===-1?"?":"&")+"c="+escape(WPrefix+"."+that.id);var constructor=isIeHtmlfileCapable()?utils.createHtmlfile:utils.createIframe;var iframeObj;_window[WPrefix][that.id]={start:function(){iframeObj.loaded()},message:function(data){that.dispatchEvent(new SimpleEvent("message",{data:data}))},stop:function(){that.iframe_close({},"network")}};that.iframe_close=function(e,abort_reason){iframeObj.cleanup();that.iframe_close=iframeObj=null;delete _window[WPrefix][that.id];that.dispatchEvent(new SimpleEvent("close",{reason:abort_reason}))};iframeObj=constructor(url,function(e){that.iframe_close({},"permanent")})};HtmlfileReceiver.prototype=new REventTarget;HtmlfileReceiver.prototype.abort=function(){var that=this;if(that.iframe_close){that.iframe_close({},"user")}};var XhrReceiver=function(url,AjaxObject){var that=this;var buf_pos=0;that.xo=new AjaxObject("POST",url,null);that.xo.onchunk=function(status,text){if(status!==200)return;while(1){var buf=text.slice(buf_pos);var p=buf.indexOf("\n");if(p===-1)break;buf_pos+=p+1;var msg=buf.slice(0,p);that.dispatchEvent(new SimpleEvent("message",{data:msg}))}};that.xo.onfinish=function(status,text){that.xo.onchunk(status,text);that.xo=null;var reason=status===200?"network":"permanent";that.dispatchEvent(new SimpleEvent("close",{reason:reason}))}};XhrReceiver.prototype=new REventTarget;XhrReceiver.prototype.abort=function(){var that=this;if(that.xo){that.xo.close();that.dispatchEvent(new SimpleEvent("close",{reason:"user"}));that.xo=null}};SockJS.getUtils=function(){return utils};SockJS.getIframeTransport=function(){return IframeTransport};return SockJS}();if("_sockjs_onload"in window)setTimeout(_sockjs_onload,1);if(typeof define==="function"&&define.amd){define("sockjs",[],function(){return SockJS})}}).call(this);(function(){LivedataTest.ClientStream=function(url,options){var self=this;self.options=_.extend({retry:true},options);self._initCommon(self.options);self.HEARTBEAT_TIMEOUT=100*1e3;self.rawUrl=url;self.socket=null;self.heartbeatTimer=null;if(typeof window!=="undefined"&&window.addEventListener)window.addEventListener("online",_.bind(self._online,self),false);self._launchConnection()};_.extend(LivedataTest.ClientStream.prototype,{send:function(data){var self=this;if(self.currentStatus.connected){self.socket.send(data)}},_changeUrl:function(url){var self=this;self.rawUrl=url},_connected:function(){var self=this;if(self.connectionTimer){clearTimeout(self.connectionTimer);self.connectionTimer=null}if(self.currentStatus.connected){return}self.currentStatus.status="connected";self.currentStatus.connected=true;self.currentStatus.retryCount=0;self.statusChanged();_.each(self.eventCallbacks.reset,function(callback){callback()})},_cleanup:function(maybeError){var self=this;self._clearConnectionAndHeartbeatTimers();if(self.socket){self.socket.onmessage=self.socket.onclose=self.socket.onerror=self.socket.onheartbeat=function(){};self.socket.close();self.socket=null}_.each(self.eventCallbacks.disconnect,function(callback){callback(maybeError)})},_clearConnectionAndHeartbeatTimers:function(){var self=this;if(self.connectionTimer){clearTimeout(self.connectionTimer);self.connectionTimer=null}if(self.heartbeatTimer){clearTimeout(self.heartbeatTimer);self.heartbeatTimer=null}},_heartbeat_timeout:function(){var self=this;Meteor._debug("Connection timeout. No sockjs heartbeat received.");self._lostConnection(new DDP.ConnectionError("Heartbeat timed out"))},_heartbeat_received:function(){var self=this;if(self._forcedToDisconnect)return;if(self.heartbeatTimer)clearTimeout(self.heartbeatTimer);self.heartbeatTimer=setTimeout(_.bind(self._heartbeat_timeout,self),self.HEARTBEAT_TIMEOUT)},_sockjsProtocolsWhitelist:function(){var protocolsWhitelist=["xdr-polling","xhr-polling","iframe-xhr-polling","jsonp-polling"];var noWebsockets=navigator&&/iPhone|iPad|iPod/.test(navigator.userAgent)&&/OS 4_|OS 5_/.test(navigator.userAgent);if(!noWebsockets)protocolsWhitelist=["websocket"].concat(protocolsWhitelist);return protocolsWhitelist},_launchConnection:function(){var self=this;self._cleanup();var options=_.extend({protocols_whitelist:self._sockjsProtocolsWhitelist()},self.options._sockjsOptions);self.socket=new SockJS(toSockjsUrl(self.rawUrl),undefined,options);self.socket.onopen=function(data){self._connected()};self.socket.onmessage=function(data){self._heartbeat_received();if(self.currentStatus.connected)_.each(self.eventCallbacks.message,function(callback){callback(data.data)})};self.socket.onclose=function(){self._lostConnection()};self.socket.onerror=function(){Meteor._debug("stream error",_.toArray(arguments),(new Date).toDateString())};self.socket.onheartbeat=function(){self._heartbeat_received()};if(self.connectionTimer)clearTimeout(self.connectionTimer);self.connectionTimer=setTimeout(function(){self._lostConnection(new DDP.ConnectionError("DDP connection timed out"))},self.CONNECT_TIMEOUT)}})}).call(this);(function(){var startsWith=function(str,starts){return str.length>=starts.length&&str.substring(0,starts.length)===starts};var endsWith=function(str,ends){return str.length>=ends.length&&str.substring(str.length-ends.length)===ends};var translateUrl=function(url,newSchemeBase,subPath){if(!newSchemeBase){newSchemeBase="http"}var ddpUrlMatch=url.match(/^ddp(i?)\+sockjs:\/\//);var httpUrlMatch=url.match(/^http(s?):\/\//);var newScheme;if(ddpUrlMatch){var urlAfterDDP=url.substr(ddpUrlMatch[0].length);newScheme=ddpUrlMatch[1]==="i"?newSchemeBase:newSchemeBase+"s";var slashPos=urlAfterDDP.indexOf("/");var host=slashPos===-1?urlAfterDDP:urlAfterDDP.substr(0,slashPos);var rest=slashPos===-1?"":urlAfterDDP.substr(slashPos);host=host.replace(/\*/g,function(){return Math.floor(Random.fraction()*10)});return newScheme+"://"+host+rest}else if(httpUrlMatch){newScheme=!httpUrlMatch[1]?newSchemeBase:newSchemeBase+"s";var urlAfterHttp=url.substr(httpUrlMatch[0].length);url=newScheme+"://"+urlAfterHttp}if(url.indexOf("://")===-1&&!startsWith(url,"/")){url=newSchemeBase+"://"+url}url=Meteor._relativeToSiteRootUrl(url);if(endsWith(url,"/"))return url+subPath;else return url+"/"+subPath};toSockjsUrl=function(url){return translateUrl(url,"http","sockjs")};toWebsocketUrl=function(url){var ret=translateUrl(url,"ws","websocket");return ret};LivedataTest.toSockjsUrl=toSockjsUrl;_.extend(LivedataTest.ClientStream.prototype,{on:function(name,callback){var self=this;if(name!=="message"&&name!=="reset"&&name!=="disconnect")throw new Error("unknown event type: "+name);if(!self.eventCallbacks[name])self.eventCallbacks[name]=[];self.eventCallbacks[name].push(callback)},_initCommon:function(options){var self=this;options=options||{};self.CONNECT_TIMEOUT=options.connectTimeoutMs||1e4;self.eventCallbacks={};self._forcedToDisconnect=false;self.currentStatus={status:"connecting",connected:false,retryCount:0};self.statusListeners=typeof Tracker!=="undefined"&&new Tracker.Dependency;self.statusChanged=function(){if(self.statusListeners)self.statusListeners.changed()};self._retry=new Retry;self.connectionTimer=null},reconnect:function(options){var self=this;options=options||{};if(options.url){self._changeUrl(options.url)}if(options._sockjsOptions){ | |
self.options._sockjsOptions=options._sockjsOptions}if(self.currentStatus.connected){if(options._force||options.url){self._lostConnection(new DDP.ForcedReconnectError)}return}if(self.currentStatus.status==="connecting"){self._lostConnection()}self._retry.clear();self.currentStatus.retryCount-=1;self._retryNow()},disconnect:function(options){var self=this;options=options||{};if(self._forcedToDisconnect)return;if(options._permanent){self._forcedToDisconnect=true}self._cleanup();self._retry.clear();self.currentStatus={status:options._permanent?"failed":"offline",connected:false,retryCount:0};if(options._permanent&&options._error)self.currentStatus.reason=options._error;self.statusChanged()},_lostConnection:function(maybeError){var self=this;self._cleanup(maybeError);self._retryLater(maybeError)},_online:function(){if(this.currentStatus.status!="offline")this.reconnect()},_retryLater:function(maybeError){var self=this;var timeout=0;if(self.options.retry||maybeError&&maybeError.errorType==="DDP.ForcedReconnectError"){timeout=self._retry.retryLater(self.currentStatus.retryCount,_.bind(self._retryNow,self));self.currentStatus.status="waiting";self.currentStatus.retryTime=(new Date).getTime()+timeout}else{self.currentStatus.status="failed";delete self.currentStatus.retryTime}self.currentStatus.connected=false;self.statusChanged()},_retryNow:function(){var self=this;if(self._forcedToDisconnect)return;self.currentStatus.retryCount+=1;self.currentStatus.status="connecting";self.currentStatus.connected=false;delete self.currentStatus.retryTime;self.statusChanged();self._launchConnection()},status:function(){var self=this;if(self.statusListeners)self.statusListeners.depend();return self.currentStatus}});DDP.ConnectionError=Meteor.makeErrorType("DDP.ConnectionError",function(message){var self=this;self.message=message});DDP.ForcedReconnectError=Meteor.makeErrorType("DDP.ForcedReconnectError",function(){})}).call(this);(function(){Heartbeat=function(options){var self=this;self.heartbeatInterval=options.heartbeatInterval;self.heartbeatTimeout=options.heartbeatTimeout;self._sendPing=options.sendPing;self._onTimeout=options.onTimeout;self._heartbeatIntervalHandle=null;self._heartbeatTimeoutHandle=null};_.extend(Heartbeat.prototype,{stop:function(){var self=this;self._clearHeartbeatIntervalTimer();self._clearHeartbeatTimeoutTimer()},start:function(){var self=this;self.stop();self._startHeartbeatIntervalTimer()},_startHeartbeatIntervalTimer:function(){var self=this;self._heartbeatIntervalHandle=Meteor.setTimeout(_.bind(self._heartbeatIntervalFired,self),self.heartbeatInterval)},_startHeartbeatTimeoutTimer:function(){var self=this;self._heartbeatTimeoutHandle=Meteor.setTimeout(_.bind(self._heartbeatTimeoutFired,self),self.heartbeatTimeout)},_clearHeartbeatIntervalTimer:function(){var self=this;if(self._heartbeatIntervalHandle){Meteor.clearTimeout(self._heartbeatIntervalHandle);self._heartbeatIntervalHandle=null}},_clearHeartbeatTimeoutTimer:function(){var self=this;if(self._heartbeatTimeoutHandle){Meteor.clearTimeout(self._heartbeatTimeoutHandle);self._heartbeatTimeoutHandle=null}},_heartbeatIntervalFired:function(){var self=this;self._heartbeatIntervalHandle=null;self._sendPing();self._startHeartbeatTimeoutTimer()},_heartbeatTimeoutFired:function(){var self=this;self._heartbeatTimeoutHandle=null;self._onTimeout()},pingReceived:function(){var self=this;if(self._heartbeatIntervalHandle){self._clearHeartbeatIntervalTimer();self._startHeartbeatIntervalTimer()}},pongReceived:function(){var self=this;if(self._heartbeatTimeoutHandle){self._clearHeartbeatTimeoutTimer();self._startHeartbeatIntervalTimer()}}})}).call(this);(function(){SUPPORTED_DDP_VERSIONS=["1","pre2","pre1"];LivedataTest.SUPPORTED_DDP_VERSIONS=SUPPORTED_DDP_VERSIONS;MethodInvocation=function(options){var self=this;this.isSimulation=options.isSimulation;this._unblock=options.unblock||function(){};this._calledUnblock=false;this.userId=options.userId;this._setUserId=options.setUserId||function(){};this.connection=options.connection;this.randomSeed=options.randomSeed;this.randomStream=null};_.extend(MethodInvocation.prototype,{unblock:function(){var self=this;self._calledUnblock=true;self._unblock()},setUserId:function(userId){var self=this;if(self._calledUnblock)throw new Error("Can't call setUserId in a method after calling unblock");self.userId=userId;self._setUserId(userId)}});parseDDP=function(stringMessage){try{var msg=JSON.parse(stringMessage)}catch(e){Meteor._debug("Discarding message with invalid JSON",stringMessage);return null}if(msg===null||typeof msg!=="object"){Meteor._debug("Discarding non-object DDP message",stringMessage);return null}if(_.has(msg,"cleared")){if(!_.has(msg,"fields"))msg.fields={};_.each(msg.cleared,function(clearKey){msg.fields[clearKey]=undefined});delete msg.cleared}_.each(["fields","params","result"],function(field){if(_.has(msg,field))msg[field]=EJSON._adjustTypesFromJSONValue(msg[field])});return msg};stringifyDDP=function(msg){var copy=EJSON.clone(msg);if(_.has(msg,"fields")){var cleared=[];_.each(msg.fields,function(value,key){if(value===undefined){cleared.push(key);delete copy.fields[key]}});if(!_.isEmpty(cleared))copy.cleared=cleared;if(_.isEmpty(copy.fields))delete copy.fields}_.each(["fields","params","result"],function(field){if(_.has(copy,field))copy[field]=EJSON._adjustTypesToJSONValue(copy[field])});if(msg.id&&typeof msg.id!=="string"){throw new Error("Message id is not a string")}return JSON.stringify(copy)};DDP._CurrentInvocation=new Meteor.EnvironmentVariable}).call(this);(function(){RandomStream=function(options){var self=this;this.seed=[].concat(options.seed||randomToken());this.sequences={}};function randomToken(){return Random.hexString(20)}RandomStream.get=function(scope,name){if(!name){name="default"}if(!scope){return Random}var randomStream=scope.randomStream;if(!randomStream){scope.randomStream=randomStream=new RandomStream({seed:scope.randomSeed})}return randomStream._sequence(name)};DDP.randomStream=function(name){var scope=DDP._CurrentInvocation.get();return RandomStream.get(scope,name)};makeRpcSeed=function(enclosing,methodName){var stream=RandomStream.get(enclosing,"/rpc/"+methodName);return stream.hexString(20)};_.extend(RandomStream.prototype,{_sequence:function(name){var self=this;var sequence=self.sequences[name]||null;if(sequence===null){var sequenceSeed=self.seed.concat(name);for(var i=0;i<sequenceSeed.length;i++){if(_.isFunction(sequenceSeed[i])){sequenceSeed[i]=sequenceSeed[i]()}}self.sequences[name]=sequence=Random.createWithSeeds.apply(null,sequenceSeed)}return sequence}})}).call(this);(function(){if(Meteor.isServer){var path=Npm.require("path");var Fiber=Npm.require("fibers");var Future=Npm.require(path.join("fibers","future"))}var Connection=function(url,options){var self=this;options=_.extend({onConnected:function(){},onDDPVersionNegotiationFailure:function(description){Meteor._debug(description)},heartbeatInterval:35e3,heartbeatTimeout:15e3,reloadWithOutstanding:false,supportedDDPVersions:SUPPORTED_DDP_VERSIONS,retry:true,respondToPings:true},options);self.onReconnect=null;if(typeof url==="object"){self._stream=url}else{self._stream=new LivedataTest.ClientStream(url,{retry:options.retry,headers:options.headers,_sockjsOptions:options._sockjsOptions,_dontPrintErrors:options._dontPrintErrors,connectTimeoutMs:options.connectTimeoutMs})}self._lastSessionId=null;self._versionSuggestion=null;self._version=null;self._stores={};self._methodHandlers={};self._nextMethodId=1;self._supportedDDPVersions=options.supportedDDPVersions;self._heartbeatInterval=options.heartbeatInterval;self._heartbeatTimeout=options.heartbeatTimeout;self._methodInvokers={};self._outstandingMethodBlocks=[];self._documentsWrittenByStub={};self._serverDocuments={};self._afterUpdateCallbacks=[];self._messagesBufferedUntilQuiescence=[];self._methodsBlockingQuiescence={};self._subsBeingRevived={};self._resetStores=false;self._updatesForUnknownStores={};self._retryMigrate=null;self._subscriptions={};self._userId=null;self._userIdDeps=new Tracker.Dependency;if(Meteor.isClient&&Package.reload&&!options.reloadWithOutstanding){Package.reload.Reload._onMigrate(function(retry){if(!self._readyToMigrate()){if(self._retryMigrate)throw new Error("Two migrations in progress?");self._retryMigrate=retry;return false}else{return[true]}})}var onMessage=function(raw_msg){try{var msg=parseDDP(raw_msg)}catch(e){Meteor._debug("Exception while parsing DDP",e);return}if(msg===null||!msg.msg){if(!(msg&&msg.server_id))Meteor._debug("discarding invalid livedata message",msg);return}if(msg.msg==="connected"){self._version=self._versionSuggestion;self._livedata_connected(msg);options.onConnected()}else if(msg.msg=="failed"){if(_.contains(self._supportedDDPVersions,msg.version)){self._versionSuggestion=msg.version;self._stream.reconnect({_force:true})}else{var description="DDP version negotiation failed; server requested version "+msg.version;self._stream.disconnect({_permanent:true,_error:description});options.onDDPVersionNegotiationFailure(description)}}else if(msg.msg==="ping"){if(options.respondToPings)self._send({msg:"pong",id:msg.id});if(self._heartbeat)self._heartbeat.pingReceived()}else if(msg.msg==="pong"){if(self._heartbeat){self._heartbeat.pongReceived()}}else if(_.include(["added","changed","removed","ready","updated"],msg.msg))self._livedata_data(msg);else if(msg.msg==="nosub")self._livedata_nosub(msg);else if(msg.msg==="result")self._livedata_result(msg);else if(msg.msg==="error")self._livedata_error(msg);else Meteor._debug("discarding unknown livedata message type",msg)};var onReset=function(){var msg={msg:"connect"};if(self._lastSessionId)msg.session=self._lastSessionId;msg.version=self._versionSuggestion||self._supportedDDPVersions[0];self._versionSuggestion=msg.version;msg.support=self._supportedDDPVersions;self._send(msg);if(!_.isEmpty(self._outstandingMethodBlocks)&&_.isEmpty(self._outstandingMethodBlocks[0].methods)){self._outstandingMethodBlocks.shift()}_.each(self._methodInvokers,function(m){m.sentMessage=false});if(self.onReconnect)self._callOnReconnectAndSendAppropriateOutstandingMethods();else self._sendOutstandingMethods();_.each(self._subscriptions,function(sub,id){self._send({msg:"sub",id:id,name:sub.name,params:sub.params})})};var onDisconnect=function(){if(self._heartbeat){self._heartbeat.stop();self._heartbeat=null}};if(Meteor.isServer){self._stream.on("message",Meteor.bindEnvironment(onMessage,Meteor._debug));self._stream.on("reset",Meteor.bindEnvironment(onReset,Meteor._debug));self._stream.on("disconnect",Meteor.bindEnvironment(onDisconnect,Meteor._debug))}else{self._stream.on("message",onMessage);self._stream.on("reset",onReset);self._stream.on("disconnect",onDisconnect)}};var MethodInvoker=function(options){var self=this;self.methodId=options.methodId;self.sentMessage=false;self._callback=options.callback;self._connection=options.connection;self._message=options.message;self._onResultReceived=options.onResultReceived||function(){};self._wait=options.wait;self._methodResult=null;self._dataVisible=false;self._connection._methodInvokers[self.methodId]=self};_.extend(MethodInvoker.prototype,{sendMessage:function(){var self=this;if(self.gotResult())throw new Error("sendingMethod is called on method with result");self._dataVisible=false;self.sentMessage=true;if(self._wait)self._connection._methodsBlockingQuiescence[self.methodId]=true;self._connection._send(self._message)},_maybeInvokeCallback:function(){var self=this;if(self._methodResult&&self._dataVisible){self._callback(self._methodResult[0],self._methodResult[1]);delete self._connection._methodInvokers[self.methodId];self._connection._outstandingMethodFinished()}},receiveResult:function(err,result){var self=this;if(self.gotResult())throw new Error("Methods should only receive results once");self._methodResult=[err,result];self._onResultReceived(err,result);self._maybeInvokeCallback()},dataVisible:function(){var self=this;self._dataVisible=true;self._maybeInvokeCallback()},gotResult:function(){var self=this;return!!self._methodResult}});_.extend(Connection.prototype,{registerStore:function(name,wrappedStore){var self=this;if(name in self._stores)return false;var store={};_.each(["update","beginUpdate","endUpdate","saveOriginals","retrieveOriginals"],function(method){store[method]=function(){return wrappedStore[method]?wrappedStore[method].apply(wrappedStore,arguments):undefined}});self._stores[name]=store;var queued=self._updatesForUnknownStores[name];if(queued){store.beginUpdate(queued.length,false);_.each(queued,function(msg){store.update(msg)});store.endUpdate();delete self._updatesForUnknownStores[name]}return true},subscribe:function(name){var self=this;var params=Array.prototype.slice.call(arguments,1);var callbacks={};if(params.length){var lastParam=params[params.length-1];if(_.isFunction(lastParam)){callbacks.onReady=params.pop()}else if(lastParam&&_.any([lastParam.onReady,lastParam.onError,lastParam.onStop],_.isFunction)){callbacks=params.pop()}}var existing=_.find(self._subscriptions,function(sub){return sub.inactive&&sub.name===name&&EJSON.equals(sub.params,params)});var id;if(existing){id=existing.id;existing.inactive=false;if(callbacks.onReady){if(!existing.ready)existing.readyCallback=callbacks.onReady}if(callbacks.onError){existing.errorCallback=callbacks.onError}if(callbacks.onStop){existing.stopCallback=callbacks.onStop}}else{id=Random.id();self._subscriptions[id]={id:id,name:name,params:EJSON.clone(params),inactive:false,ready:false,readyDeps:new Tracker.Dependency,readyCallback:callbacks.onReady,errorCallback:callbacks.onError,stopCallback:callbacks.onStop,connection:self,remove:function(){delete this.connection._subscriptions[this.id];this.ready&&this.readyDeps.changed()},stop:function(){this.connection._send({msg:"unsub",id:id});this.remove();if(callbacks.onStop){callbacks.onStop()}}};self._send({msg:"sub",id:id,name:name,params:params})}var handle={stop:function(){if(!_.has(self._subscriptions,id))return;self._subscriptions[id].stop()},ready:function(){if(!_.has(self._subscriptions,id))return false;var record=self._subscriptions[id];record.readyDeps.depend();return record.ready},subscriptionId:id};if(Tracker.active){Tracker.onInvalidate(function(c){if(_.has(self._subscriptions,id))self._subscriptions[id].inactive=true;Tracker.afterFlush(function(){if(_.has(self._subscriptions,id)&&self._subscriptions[id].inactive)handle.stop()})})}return handle},_subscribeAndWait:function(name,args,options){var self=this;var f=new Future;var ready=false;var handle;args=args||[];args.push({onReady:function(){ready=true;f["return"]()},onError:function(e){if(!ready)f["throw"](e);else options&&options.onLateError&&options.onLateError(e)}});handle=self.subscribe.apply(self,[name].concat(args));f.wait();return handle},methods:function(methods){var self=this;_.each(methods,function(func,name){if(self._methodHandlers[name])throw new Error("A method named '"+name+"' is already defined");self._methodHandlers[name]=func})},call:function(name){var args=Array.prototype.slice.call(arguments,1);if(args.length&&typeof args[args.length-1]==="function")var callback=args.pop();return this.apply(name,args,callback)},apply:function(name,args,options,callback){var self=this;if(!callback&&typeof options==="function"){callback=options;options={}}options=options||{};if(callback){callback=Meteor.bindEnvironment(callback,"delivering result of invoking '"+name+"'")}args=EJSON.clone(args);var methodId=function(){var id;return function(){if(id===undefined)id=""+self._nextMethodId++;return id}}();var enclosing=DDP._CurrentInvocation.get();var alreadyInSimulation=enclosing&&enclosing.isSimulation;var randomSeed=null;var randomSeedGenerator=function(){if(randomSeed===null){randomSeed=makeRpcSeed(enclosing,name)}return randomSeed};var stub=self._methodHandlers[name];if(stub){var setUserId=function(userId){self.setUserId(userId)};var invocation=new MethodInvocation({isSimulation:true,userId:self.userId(),setUserId:setUserId,randomSeed:function(){return randomSeedGenerator()}});if(!alreadyInSimulation)self._saveOriginals();try{var stubReturnValue=DDP._CurrentInvocation.withValue(invocation,function(){if(Meteor.isServer){return Meteor._noYieldsAllowed(function(){return stub.apply(invocation,EJSON.clone(args))})}else{return stub.apply(invocation,EJSON.clone(args))}})}catch(e){var exception=e}if(!alreadyInSimulation)self._retrieveAndStoreOriginals(methodId())}if(alreadyInSimulation){if(callback){callback(exception,stubReturnValue);return undefined}if(exception)throw exception;return stubReturnValue}if(exception&&!exception.expected){Meteor._debug("Exception while simulating the effect of invoking '"+name+"'",exception,exception.stack)}if(!callback){if(Meteor.isClient){callback=function(err){err&&Meteor._debug("Error invoking Method '"+name+"':",err.message)}}else{var future=new Future;callback=future.resolver()}}var message={msg:"method",method:name,params:args,id:methodId()};if(randomSeed!==null){message.randomSeed=randomSeed}var methodInvoker=new MethodInvoker({methodId:methodId(),callback:callback,connection:self,onResultReceived:options.onResultReceived,wait:!!options.wait,message:message});if(options.wait){self._outstandingMethodBlocks.push({wait:true,methods:[methodInvoker]})}else{if(_.isEmpty(self._outstandingMethodBlocks)||_.last(self._outstandingMethodBlocks).wait)self._outstandingMethodBlocks.push({wait:false,methods:[]});_.last(self._outstandingMethodBlocks).methods.push(methodInvoker)}if(self._outstandingMethodBlocks.length===1)methodInvoker.sendMessage();if(future){return future.wait()}return options.returnStubValue?stubReturnValue:undefined},_saveOriginals:function(){var self=this;_.each(self._stores,function(s){s.saveOriginals()})},_retrieveAndStoreOriginals:function(methodId){var self=this;if(self._documentsWrittenByStub[methodId])throw new Error("Duplicate methodId in _retrieveAndStoreOriginals");var docsWritten=[];_.each(self._stores,function(s,collection){var originals=s.retrieveOriginals();if(!originals)return;originals.forEach(function(doc,id){docsWritten.push({collection:collection,id:id});if(!_.has(self._serverDocuments,collection))self._serverDocuments[collection]=new LocalCollection._IdMap;var serverDoc=self._serverDocuments[collection].setDefault(id,{});if(serverDoc.writtenByStubs){serverDoc.writtenByStubs[methodId]=true}else{serverDoc.document=doc;serverDoc.flushCallbacks=[];serverDoc.writtenByStubs={};serverDoc.writtenByStubs[methodId]=true}})});if(!_.isEmpty(docsWritten)){self._documentsWrittenByStub[methodId]=docsWritten}},_unsubscribeAll:function(){var self=this;_.each(_.clone(self._subscriptions),function(sub,id){if(sub.name!=="meteor_autoupdate_clientVersions"){self._subscriptions[id].stop()}})},_send:function(obj){var self=this;self._stream.send(stringifyDDP(obj))},_lostConnection:function(error){var self=this;self._stream._lostConnection(error)},status:function(){var self=this;return self._stream.status.apply(self._stream,arguments)},reconnect:function(){var self=this;return self._stream.reconnect.apply(self._stream,arguments)},disconnect:function(){var self=this;return self._stream.disconnect.apply(self._stream,arguments)},close:function(){var self=this;return self._stream.disconnect({_permanent:true})},userId:function(){var self=this;if(self._userIdDeps)self._userIdDeps.depend();return self._userId},setUserId:function(userId){var self=this;if(self._userId===userId)return;self._userId=userId;if(self._userIdDeps)self._userIdDeps.changed()},_waitingForQuiescence:function(){var self=this;return!_.isEmpty(self._subsBeingRevived)||!_.isEmpty(self._methodsBlockingQuiescence)},_anyMethodsAreOutstanding:function(){var self=this;return _.any(_.pluck(self._methodInvokers,"sentMessage"))},_livedata_connected:function(msg){var self=this;if(self._version!=="pre1"&&self._heartbeatInterval!==0){self._heartbeat=new Heartbeat({heartbeatInterval:self._heartbeatInterval,heartbeatTimeout:self._heartbeatTimeout,onTimeout:function(){self._lostConnection(new DDP.ConnectionError("DDP heartbeat timed out"))},sendPing:function(){self._send({msg:"ping"})}});self._heartbeat.start()}if(self._lastSessionId)self._resetStores=true;if(typeof msg.session==="string"){var reconnectedToPreviousSession=self._lastSessionId===msg.session;self._lastSessionId=msg.session}if(reconnectedToPreviousSession){return}self._updatesForUnknownStores={};if(self._resetStores){self._documentsWrittenByStub={};self._serverDocuments={}}self._afterUpdateCallbacks=[];self._subsBeingRevived={};_.each(self._subscriptions,function(sub,id){if(sub.ready)self._subsBeingRevived[id]=true});self._methodsBlockingQuiescence={};if(self._resetStores){_.each(self._methodInvokers,function(invoker){if(invoker.gotResult()){self._afterUpdateCallbacks.push(_.bind(invoker.dataVisible,invoker))}else if(invoker.sentMessage){self._methodsBlockingQuiescence[invoker.methodId]=true}})}self._messagesBufferedUntilQuiescence=[];if(!self._waitingForQuiescence()){if(self._resetStores){_.each(self._stores,function(s){s.beginUpdate(0,true);s.endUpdate()});self._resetStores=false}self._runAfterUpdateCallbacks()}},_processOneDataMessage:function(msg,updates){var self=this;self["_process_"+msg.msg](msg,updates)},_livedata_data:function(msg){var self=this;var updates={};if(self._waitingForQuiescence()){self._messagesBufferedUntilQuiescence.push(msg);if(msg.msg==="nosub")delete self._subsBeingRevived[msg.id];_.each(msg.subs||[],function(subId){delete self._subsBeingRevived[subId]});_.each(msg.methods||[],function(methodId){delete self._methodsBlockingQuiescence[methodId]});if(self._waitingForQuiescence())return;_.each(self._messagesBufferedUntilQuiescence,function(bufferedMsg){self._processOneDataMessage(bufferedMsg,updates)});self._messagesBufferedUntilQuiescence=[]}else{self._processOneDataMessage(msg,updates)}if(self._resetStores||!_.isEmpty(updates)){_.each(self._stores,function(s,storeName){s.beginUpdate(_.has(updates,storeName)?updates[storeName].length:0,self._resetStores)});self._resetStores=false;_.each(updates,function(updateMessages,storeName){var store=self._stores[storeName];if(store){_.each(updateMessages,function(updateMessage){store.update(updateMessage)})}else{if(!_.has(self._updatesForUnknownStores,storeName))self._updatesForUnknownStores[storeName]=[];Array.prototype.push.apply(self._updatesForUnknownStores[storeName],updateMessages)}});_.each(self._stores,function(s){s.endUpdate()})}self._runAfterUpdateCallbacks()},_runAfterUpdateCallbacks:function(){var self=this;var callbacks=self._afterUpdateCallbacks;self._afterUpdateCallbacks=[];_.each(callbacks,function(c){c()})},_pushUpdate:function(updates,collection,msg){var self=this;if(!_.has(updates,collection)){updates[collection]=[]}updates[collection].push(msg)},_getServerDoc:function(collection,id){var self=this;if(!_.has(self._serverDocuments,collection))return null;var serverDocsForCollection=self._serverDocuments[collection];return serverDocsForCollection.get(id)||null},_process_added:function(msg,updates){var self=this;var id=LocalCollection._idParse(msg.id);var serverDoc=self._getServerDoc(msg.collection,id);if(serverDoc){if(serverDoc.document!==undefined)throw new Error("Server sent add for existing id: "+msg.id);serverDoc.document=msg.fields||{};serverDoc.document._id=id}else{self._pushUpdate(updates,msg.collection,msg)}},_process_changed:function(msg,updates){var self=this;var serverDoc=self._getServerDoc(msg.collection,LocalCollection._idParse(msg.id));if(serverDoc){if(serverDoc.document===undefined)throw new Error("Server sent changed for nonexisting id: "+msg.id);LocalCollection._applyChanges(serverDoc.document,msg.fields)}else{self._pushUpdate(updates,msg.collection,msg)}},_process_removed:function(msg,updates){var self=this;var serverDoc=self._getServerDoc(msg.collection,LocalCollection._idParse(msg.id));if(serverDoc){if(serverDoc.document===undefined)throw new Error("Server sent removed for nonexisting id:"+msg.id);serverDoc.document=undefined}else{self._pushUpdate(updates,msg.collection,{msg:"removed",collection:msg.collection,id:msg.id})}},_process_updated:function(msg,updates){var self=this;_.each(msg.methods,function(methodId){_.each(self._documentsWrittenByStub[methodId],function(written){var serverDoc=self._getServerDoc(written.collection,written.id);if(!serverDoc)throw new Error("Lost serverDoc for "+JSON.stringify(written));if(!serverDoc.writtenByStubs[methodId])throw new Error("Doc "+JSON.stringify(written)+" not written by method "+methodId);delete serverDoc.writtenByStubs[methodId];if(_.isEmpty(serverDoc.writtenByStubs)){self._pushUpdate(updates,written.collection,{msg:"replace",id:LocalCollection._idStringify(written.id),replace:serverDoc.document});_.each(serverDoc.flushCallbacks,function(c){c()});self._serverDocuments[written.collection].remove(written.id)}});delete self._documentsWrittenByStub[methodId];var callbackInvoker=self._methodInvokers[methodId];if(!callbackInvoker)throw new Error("No callback invoker for method "+methodId);self._runWhenAllServerDocsAreFlushed(_.bind(callbackInvoker.dataVisible,callbackInvoker))})},_process_ready:function(msg,updates){var self=this;_.each(msg.subs,function(subId){self._runWhenAllServerDocsAreFlushed(function(){var subRecord=self._subscriptions[subId];if(!subRecord)return;if(subRecord.ready)return;subRecord.readyCallback&&subRecord.readyCallback();subRecord.ready=true;subRecord.readyDeps.changed()})})},_runWhenAllServerDocsAreFlushed:function(f){var self=this;var runFAfterUpdates=function(){self._afterUpdateCallbacks.push(f)};var unflushedServerDocCount=0;var onServerDocFlush=function(){--unflushedServerDocCount;if(unflushedServerDocCount===0){runFAfterUpdates()}};_.each(self._serverDocuments,function(collectionDocs){collectionDocs.forEach(function(serverDoc){var writtenByStubForAMethodWithSentMessage=_.any(serverDoc.writtenByStubs,function(dummy,methodId){var invoker=self._methodInvokers[methodId];return invoker&&invoker.sentMessage});if(writtenByStubForAMethodWithSentMessage){++unflushedServerDocCount;serverDoc.flushCallbacks.push(onServerDocFlush)}})});if(unflushedServerDocCount===0){runFAfterUpdates()}},_livedata_nosub:function(msg){var self=this;self._livedata_data(msg);if(!_.has(self._subscriptions,msg.id))return;var errorCallback=self._subscriptions[msg.id].errorCallback;var stopCallback=self._subscriptions[msg.id].stopCallback;self._subscriptions[msg.id].remove();var meteorErrorFromMsg=function(msgArg){return msgArg&&msgArg.error&&new Meteor.Error(msgArg.error.error,msgArg.error.reason,msgArg.error.details)};if(errorCallback&&msg.error){errorCallback(meteorErrorFromMsg(msg))}if(stopCallback){stopCallback(meteorErrorFromMsg(msg))}},_process_nosub:function(){},_livedata_result:function(msg){var self=this;if(_.isEmpty(self._outstandingMethodBlocks)){Meteor._debug("Received method result but no methods outstanding");return}var currentMethodBlock=self._outstandingMethodBlocks[0].methods;var m;for(var i=0;i<currentMethodBlock.length;i++){m=currentMethodBlock[i];if(m.methodId===msg.id)break}if(!m){Meteor._debug("Can't match method response to original method call",msg);return}currentMethodBlock.splice(i,1);if(_.has(msg,"error")){m.receiveResult(new Meteor.Error(msg.error.error,msg.error.reason,msg.error.details))}else{m.receiveResult(undefined,msg.result)}},_outstandingMethodFinished:function(){var self=this;if(self._anyMethodsAreOutstanding())return;if(!_.isEmpty(self._outstandingMethodBlocks)){var firstBlock=self._outstandingMethodBlocks.shift();if(!_.isEmpty(firstBlock.methods))throw new Error("No methods outstanding but nonempty block: "+JSON.stringify(firstBlock));if(!_.isEmpty(self._outstandingMethodBlocks))self._sendOutstandingMethods()}self._maybeMigrate()},_sendOutstandingMethods:function(){var self=this;if(_.isEmpty(self._outstandingMethodBlocks))return;_.each(self._outstandingMethodBlocks[0].methods,function(m){m.sendMessage()})},_livedata_error:function(msg){Meteor._debug("Received error from server: ",msg.reason);if(msg.offendingMessage)Meteor._debug("For: ",msg.offendingMessage)},_callOnReconnectAndSendAppropriateOutstandingMethods:function(){var self=this;var oldOutstandingMethodBlocks=self._outstandingMethodBlocks;self._outstandingMethodBlocks=[];self.onReconnect();if(_.isEmpty(oldOutstandingMethodBlocks))return;if(_.isEmpty(self._outstandingMethodBlocks)){self._outstandingMethodBlocks=oldOutstandingMethodBlocks;self._sendOutstandingMethods();return}if(!_.last(self._outstandingMethodBlocks).wait&&!oldOutstandingMethodBlocks[0].wait){_.each(oldOutstandingMethodBlocks[0].methods,function(m){_.last(self._outstandingMethodBlocks).methods.push(m);if(self._outstandingMethodBlocks.length===1)m.sendMessage()});oldOutstandingMethodBlocks.shift()}_.each(oldOutstandingMethodBlocks,function(block){self._outstandingMethodBlocks.push(block)})},_readyToMigrate:function(){var self=this;return _.isEmpty(self._methodInvokers)},_maybeMigrate:function(){var self=this;if(self._retryMigrate&&self._readyToMigrate()){self._retryMigrate();self._retryMigrate=null}}});LivedataTest.Connection=Connection;DDP.connect=function(url,options){var ret=new Connection(url,options);allConnections.push(ret);return ret};allConnections=[];DDP._allSubscriptionsReady=function(){return _.all(allConnections,function(conn){return _.all(conn._subscriptions,function(sub){return sub.ready})})}}).call(this);(function(){Meteor.refresh=function(notification){};if(Meteor.isClient){var ddpUrl="/";if(typeof __meteor_runtime_config__!=="undefined"){if(__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL)ddpUrl=__meteor_runtime_config__.DDP_DEFAULT_CONNECTION_URL}var retry=new Retry;var onDDPVersionNegotiationFailure=function(description){Meteor._debug(description);if(Package.reload){var migrationData=Package.reload.Reload._migrationData("livedata")||{};var failures=migrationData.DDPVersionNegotiationFailures||0;++failures;Package.reload.Reload._onMigrate("livedata",function(){return[true,{DDPVersionNegotiationFailures:failures}]});retry.retryLater(failures,function(){Package.reload.Reload._reload()})}};Meteor.connection=DDP.connect(ddpUrl,{onDDPVersionNegotiationFailure:onDDPVersionNegotiationFailure});_.each(["subscribe","methods","call","apply","status","reconnect","disconnect"],function(name){Meteor[name]=_.bind(Meteor.connection[name],Meteor.connection)})}else{Meteor.connection=null}Meteor.default_connection=Meteor.connection;Meteor.connect=DDP.connect}).call(this);if(typeof Package==="undefined")Package={};Package.ddp={DDP:DDP,LivedataTest:LivedataTest}})();(function(){var Meteor=Package.meteor.Meteor;var Random=Package.random.Random;var EJSON=Package.ejson.EJSON;var JSON=Package.json.JSON;var _=Package.underscore._;var LocalCollection=Package.minimongo.LocalCollection;var Minimongo=Package.minimongo.Minimongo;var Log=Package.logging.Log;var DDP=Package.ddp.DDP;var Tracker=Package.tracker.Tracker;var Deps=Package.tracker.Deps;var check=Package.check.check;var Match=Package.check.Match;var Mongo,LocalCollectionDriver;(function(){LocalCollectionDriver=function(){var self=this;self.noConnCollections={}};var ensureCollection=function(name,collections){if(!(name in collections))collections[name]=new LocalCollection(name);return collections[name]};_.extend(LocalCollectionDriver.prototype,{open:function(name,conn){var self=this;if(!name)return new LocalCollection;if(!conn){return ensureCollection(name,self.noConnCollections)}if(!conn._mongo_livedata_collections)conn._mongo_livedata_collections={};return ensureCollection(name,conn._mongo_livedata_collections)}});LocalCollectionDriver=new LocalCollectionDriver}).call(this);(function(){Mongo={};Mongo.Collection=function(name,options){var self=this;if(!(self instanceof Mongo.Collection))throw new Error('use "new" to construct a Mongo.Collection');if(!name&&name!==null){Meteor._debug("Warning: creating anonymous collection. It will not be "+"saved or synchronized over the network. (Pass null for "+"the collection name to turn off this warning.)"); | |
name=null}if(name!==null&&typeof name!=="string"){throw new Error("First argument to new Mongo.Collection must be a string or null")}if(options&&options.methods){options={connection:options}}if(options&&options.manager&&!options.connection){options.connection=options.manager}options=_.extend({connection:undefined,idGeneration:"STRING",transform:null,_driver:undefined,_preventAutopublish:false},options);switch(options.idGeneration){case"MONGO":self._makeNewID=function(){var src=name?DDP.randomStream("/collection/"+name):Random;return new Mongo.ObjectID(src.hexString(24))};break;case"STRING":default:self._makeNewID=function(){var src=name?DDP.randomStream("/collection/"+name):Random;return src.id()};break}self._transform=LocalCollection.wrapTransform(options.transform);if(!name||options.connection===null)self._connection=null;else if(options.connection)self._connection=options.connection;else if(Meteor.isClient)self._connection=Meteor.connection;else self._connection=Meteor.server;if(!options._driver){if(name&&self._connection===Meteor.server&&typeof MongoInternals!=="undefined"&&MongoInternals.defaultRemoteCollectionDriver){options._driver=MongoInternals.defaultRemoteCollectionDriver()}else{options._driver=LocalCollectionDriver}}self._collection=options._driver.open(name,self._connection);self._name=name;self._driver=options._driver;if(self._connection&&self._connection.registerStore){var ok=self._connection.registerStore(name,{beginUpdate:function(batchSize,reset){if(batchSize>1||reset)self._collection.pauseObservers();if(reset)self._collection.remove({})},update:function(msg){var mongoId=LocalCollection._idParse(msg.id);var doc=self._collection.findOne(mongoId);if(msg.msg==="replace"){var replace=msg.replace;if(!replace){if(doc)self._collection.remove(mongoId)}else if(!doc){self._collection.insert(replace)}else{self._collection.update(mongoId,replace)}return}else if(msg.msg==="added"){if(doc){throw new Error("Expected not to find a document already present for an add")}self._collection.insert(_.extend({_id:mongoId},msg.fields))}else if(msg.msg==="removed"){if(!doc)throw new Error("Expected to find a document already present for removed");self._collection.remove(mongoId)}else if(msg.msg==="changed"){if(!doc)throw new Error("Expected to find a document to change");if(!_.isEmpty(msg.fields)){var modifier={};_.each(msg.fields,function(value,key){if(value===undefined){if(!modifier.$unset)modifier.$unset={};modifier.$unset[key]=1}else{if(!modifier.$set)modifier.$set={};modifier.$set[key]=value}});self._collection.update(mongoId,modifier)}}else{throw new Error("I don't know how to deal with this message")}},endUpdate:function(){self._collection.resumeObservers()},saveOriginals:function(){self._collection.saveOriginals()},retrieveOriginals:function(){return self._collection.retrieveOriginals()}});if(!ok)throw new Error("There is already a collection named '"+name+"'")}self._defineMutationMethods();if(Package.autopublish&&!options._preventAutopublish&&self._connection&&self._connection.publish){self._connection.publish(null,function(){return self.find()},{is_auto:true})}};_.extend(Mongo.Collection.prototype,{_getFindSelector:function(args){if(args.length==0)return{};else return args[0]},_getFindOptions:function(args){var self=this;if(args.length<2){return{transform:self._transform}}else{check(args[1],Match.Optional(Match.ObjectIncluding({fields:Match.Optional(Match.OneOf(Object,undefined)),sort:Match.Optional(Match.OneOf(Object,Array,undefined)),limit:Match.Optional(Match.OneOf(Number,undefined)),skip:Match.Optional(Match.OneOf(Number,undefined))})));return _.extend({transform:self._transform},args[1])}},find:function(){var self=this;var argArray=_.toArray(arguments);return self._collection.find(self._getFindSelector(argArray),self._getFindOptions(argArray))},findOne:function(){var self=this;var argArray=_.toArray(arguments);return self._collection.findOne(self._getFindSelector(argArray),self._getFindOptions(argArray))}});Mongo.Collection._publishCursor=function(cursor,sub,collection){var observeHandle=cursor.observeChanges({added:function(id,fields){sub.added(collection,id,fields)},changed:function(id,fields){sub.changed(collection,id,fields)},removed:function(id){sub.removed(collection,id)}});sub.onStop(function(){observeHandle.stop()})};Mongo.Collection._rewriteSelector=function(selector){if(LocalCollection._selectorIsId(selector))selector={_id:selector};if(!selector||"_id"in selector&&!selector._id)return{_id:Random.id()};var ret={};_.each(selector,function(value,key){if(value instanceof RegExp){ret[key]=convertRegexpToMongoSelector(value)}else if(value&&value.$regex instanceof RegExp){ret[key]=convertRegexpToMongoSelector(value.$regex);if(value.$options!==undefined)ret[key].$options=value.$options}else if(_.contains(["$or","$and","$nor"],key)){ret[key]=_.map(value,function(v){return Mongo.Collection._rewriteSelector(v)})}else{ret[key]=value}});return ret};var convertRegexpToMongoSelector=function(regexp){check(regexp,RegExp);var selector={$regex:regexp.source};var regexOptions="";if(regexp.ignoreCase)regexOptions+="i";if(regexp.multiline)regexOptions+="m";if(regexOptions)selector.$options=regexOptions;return selector};var throwIfSelectorIsNotId=function(selector,methodName){if(!LocalCollection._selectorIsIdPerhapsAsObject(selector)){throw new Meteor.Error(403,"Not permitted. Untrusted code may only "+methodName+" documents by ID.")}};_.each(["insert","update","remove"],function(name){Mongo.Collection.prototype[name]=function(){var self=this;var args=_.toArray(arguments);var callback;var insertId;var ret;if(args.length&&(args[args.length-1]===undefined||args[args.length-1]instanceof Function)){callback=args.pop()}if(name==="insert"){if(!args.length)throw new Error("insert requires an argument");args[0]=_.extend({},args[0]);if("_id"in args[0]){insertId=args[0]._id;if(!insertId||!(typeof insertId==="string"||insertId instanceof Mongo.ObjectID))throw new Error("Meteor requires document _id fields to be non-empty strings or ObjectIDs")}else{var generateId=true;if(self._connection&&self._connection!==Meteor.server){var enclosing=DDP._CurrentInvocation.get();if(!enclosing){generateId=false}}if(generateId){insertId=args[0]._id=self._makeNewID()}}}else{args[0]=Mongo.Collection._rewriteSelector(args[0]);if(name==="update"){var options=args[2]=_.clone(args[2])||{};if(options&&typeof options!=="function"&&options.upsert){if(options.insertedId){if(!(typeof options.insertedId==="string"||options.insertedId instanceof Mongo.ObjectID))throw new Error("insertedId must be string or ObjectID")}else if(!args[0]._id){options.insertedId=self._makeNewID()}}}}var chooseReturnValueFromCollectionResult=function(result){if(name==="insert"){if(!insertId&&result){insertId=result}return insertId}else{return result}};var wrappedCallback;if(callback){wrappedCallback=function(error,result){callback(error,!error&&chooseReturnValueFromCollectionResult(result))}}if(self._connection&&self._connection!==Meteor.server){var enclosing=DDP._CurrentInvocation.get();var alreadyInSimulation=enclosing&&enclosing.isSimulation;if(Meteor.isClient&&!wrappedCallback&&!alreadyInSimulation){wrappedCallback=function(err){if(err)Meteor._debug(name+" failed: "+(err.reason||err.stack))}}if(!alreadyInSimulation&&name!=="insert"){throwIfSelectorIsNotId(args[0],name)}ret=chooseReturnValueFromCollectionResult(self._connection.apply(self._prefix+name,args,{returnStubValue:true},wrappedCallback))}else{args.push(wrappedCallback);try{var queryRet=self._collection[name].apply(self._collection,args);ret=chooseReturnValueFromCollectionResult(queryRet)}catch(e){if(callback){callback(e);return null}throw e}}return ret}});Mongo.Collection.prototype.upsert=function(selector,modifier,options,callback){var self=this;if(!callback&&typeof options==="function"){callback=options;options={}}return self.update(selector,modifier,_.extend({},options,{_returnObject:true,upsert:true}),callback)};Mongo.Collection.prototype._ensureIndex=function(index,options){var self=this;if(!self._collection._ensureIndex)throw new Error("Can only call _ensureIndex on server collections");self._collection._ensureIndex(index,options)};Mongo.Collection.prototype._dropIndex=function(index){var self=this;if(!self._collection._dropIndex)throw new Error("Can only call _dropIndex on server collections");self._collection._dropIndex(index)};Mongo.Collection.prototype._dropCollection=function(){var self=this;if(!self._collection.dropCollection)throw new Error("Can only call _dropCollection on server collections");self._collection.dropCollection()};Mongo.Collection.prototype._createCappedCollection=function(byteSize,maxDocuments){var self=this;if(!self._collection._createCappedCollection)throw new Error("Can only call _createCappedCollection on server collections");self._collection._createCappedCollection(byteSize,maxDocuments)};Mongo.Collection.prototype.rawCollection=function(){var self=this;if(!self._collection.rawCollection){throw new Error("Can only call rawCollection on server collections")}return self._collection.rawCollection()};Mongo.Collection.prototype.rawDatabase=function(){var self=this;if(!(self._driver.mongo&&self._driver.mongo.db)){throw new Error("Can only call rawDatabase on server collections")}return self._driver.mongo.db};Mongo.ObjectID=LocalCollection._ObjectID;Mongo.Cursor=LocalCollection.Cursor;Mongo.Collection.Cursor=Mongo.Cursor;Mongo.Collection.ObjectID=Mongo.ObjectID;(function(){var addValidator=function(allowOrDeny,options){var VALID_KEYS=["insert","update","remove","fetch","transform"];_.each(_.keys(options),function(key){if(!_.contains(VALID_KEYS,key))throw new Error(allowOrDeny+": Invalid key: "+key)});var self=this;self._restricted=true;_.each(["insert","update","remove"],function(name){if(options[name]){if(!(options[name]instanceof Function)){throw new Error(allowOrDeny+": Value for `"+name+"` must be a function")}if(options.transform===undefined){options[name].transform=self._transform}else{options[name].transform=LocalCollection.wrapTransform(options.transform)}self._validators[name][allowOrDeny].push(options[name])}});if(options.update||options.remove||options.fetch){if(options.fetch&&!(options.fetch instanceof Array)){throw new Error(allowOrDeny+": Value for `fetch` must be an array")}self._updateFetch(options.fetch)}};Mongo.Collection.prototype.allow=function(options){addValidator.call(this,"allow",options)};Mongo.Collection.prototype.deny=function(options){addValidator.call(this,"deny",options)}})();Mongo.Collection.prototype._defineMutationMethods=function(){var self=this;self._restricted=false;self._insecure=undefined;self._validators={insert:{allow:[],deny:[]},update:{allow:[],deny:[]},remove:{allow:[],deny:[]},upsert:{allow:[],deny:[]},fetch:[],fetchAllFields:false};if(!self._name)return;self._prefix="/"+self._name+"/";if(self._connection){var m={};_.each(["insert","update","remove"],function(method){m[self._prefix+method]=function(){check(arguments,[Match.Any]);var args=_.toArray(arguments);try{var generatedId=null;if(method==="insert"&&!_.has(args[0],"_id")){generatedId=self._makeNewID()}if(this.isSimulation){if(generatedId!==null)args[0]._id=generatedId;return self._collection[method].apply(self._collection,args)}if(method!=="insert")throwIfSelectorIsNotId(args[0],method);if(self._restricted){if(self._validators[method].allow.length===0){throw new Meteor.Error(403,"Access denied. No allow validators set on restricted "+"collection for method '"+method+"'.")}var validatedMethodName="_validated"+method.charAt(0).toUpperCase()+method.slice(1);args.unshift(this.userId);method==="insert"&&args.push(generatedId);return self[validatedMethodName].apply(self,args)}else if(self._isInsecure()){if(generatedId!==null)args[0]._id=generatedId;return self._collection[method].apply(self._collection,args)}else{throw new Meteor.Error(403,"Access denied")}}catch(e){if(e.name==="MongoError"||e.name==="MinimongoError"){throw new Meteor.Error(409,e.toString())}else{throw e}}}});if(Meteor.isClient||self._connection===Meteor.server)self._connection.methods(m)}};Mongo.Collection.prototype._updateFetch=function(fields){var self=this;if(!self._validators.fetchAllFields){if(fields){self._validators.fetch=_.union(self._validators.fetch,fields)}else{self._validators.fetchAllFields=true;self._validators.fetch=null}}};Mongo.Collection.prototype._isInsecure=function(){var self=this;if(self._insecure===undefined)return!!Package.insecure;return self._insecure};var docToValidate=function(validator,doc,generatedId){var ret=doc;if(validator.transform){ret=EJSON.clone(doc);if(generatedId!==null){ret._id=generatedId}ret=validator.transform(ret)}return ret};Mongo.Collection.prototype._validatedInsert=function(userId,doc,generatedId){var self=this;if(_.any(self._validators.insert.deny,function(validator){return validator(userId,docToValidate(validator,doc,generatedId))})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.insert.allow,function(validator){return!validator(userId,docToValidate(validator,doc,generatedId))})){throw new Meteor.Error(403,"Access denied")}if(generatedId!==null)doc._id=generatedId;self._collection.insert.call(self._collection,doc)};var transformDoc=function(validator,doc){if(validator.transform)return validator.transform(doc);return doc};Mongo.Collection.prototype._validatedUpdate=function(userId,selector,mutator,options){var self=this;check(mutator,Object);options=_.clone(options)||{};if(!LocalCollection._selectorIsIdPerhapsAsObject(selector))throw new Error("validated update should be of a single ID");if(options.upsert)throw new Meteor.Error(403,"Access denied. Upserts not "+"allowed in a restricted collection.");var noReplaceError="Access denied. In a restricted collection you can only"+" update documents, not replace them. Use a Mongo update operator, such "+"as '$set'.";var fields=[];if(_.isEmpty(mutator)){throw new Meteor.Error(403,noReplaceError)}_.each(mutator,function(params,op){if(op.charAt(0)!=="$"){throw new Meteor.Error(403,noReplaceError)}else if(!_.has(ALLOWED_UPDATE_OPERATIONS,op)){throw new Meteor.Error(403,"Access denied. Operator "+op+" not allowed in a restricted collection.")}else{_.each(_.keys(params),function(field){if(field.indexOf(".")!==-1)field=field.substring(0,field.indexOf("."));if(!_.contains(fields,field))fields.push(field)})}});var findOptions={transform:null};if(!self._validators.fetchAllFields){findOptions.fields={};_.each(self._validators.fetch,function(fieldName){findOptions.fields[fieldName]=1})}var doc=self._collection.findOne(selector,findOptions);if(!doc)return 0;if(_.any(self._validators.update.deny,function(validator){var factoriedDoc=transformDoc(validator,doc);return validator(userId,factoriedDoc,fields,mutator)})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.update.allow,function(validator){var factoriedDoc=transformDoc(validator,doc);return!validator(userId,factoriedDoc,fields,mutator)})){throw new Meteor.Error(403,"Access denied")}options._forbidReplace=true;return self._collection.update.call(self._collection,selector,mutator,options)};var ALLOWED_UPDATE_OPERATIONS={$inc:1,$set:1,$unset:1,$addToSet:1,$pop:1,$pullAll:1,$pull:1,$pushAll:1,$push:1,$bit:1};Mongo.Collection.prototype._validatedRemove=function(userId,selector){var self=this;var findOptions={transform:null};if(!self._validators.fetchAllFields){findOptions.fields={};_.each(self._validators.fetch,function(fieldName){findOptions.fields[fieldName]=1})}var doc=self._collection.findOne(selector,findOptions);if(!doc)return 0;if(_.any(self._validators.remove.deny,function(validator){return validator(userId,transformDoc(validator,doc))})){throw new Meteor.Error(403,"Access denied")}if(_.all(self._validators.remove.allow,function(validator){return!validator(userId,transformDoc(validator,doc))})){throw new Meteor.Error(403,"Access denied")}return self._collection.remove.call(self._collection,selector)};Meteor.Collection=Mongo.Collection}).call(this);if(typeof Package==="undefined")Package={};Package.mongo={Mongo:Mongo}})();Meteor=Package.meteor.Meteor;Log=Package.logging.Log;Tracker=Package.tracker.Tracker;DDP=Package.ddp.DDP;Mongo=Package.mongo.Mongo;check=Package.check.check;Match=Package.check.Match;_=Package.underscore._;Random=Package.random.Random;EJSON=Package.ejson.EJSON; | |
(function () { | |
/* Imports */ | |
var Meteor = Package.meteor.Meteor; | |
/* Package-scope variables */ | |
var babelHelpers; | |
(function(){ | |
///////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
// // | |
// packages/babel-runtime/babel-runtime.js // | |
// // | |
///////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
// | |
var hasOwn = Object.prototype.hasOwnProperty; // 1 | |
// 2 | |
function canDefineNonEnumerableProperties() { // 3 | |
var testObj = {}; // 4 | |
var testPropName = "t"; // 5 | |
// 6 | |
try { // 7 | |
Object.defineProperty(testObj, testPropName, { // 8 | |
enumerable: false, // 9 | |
value: testObj // 10 | |
}); // 11 | |
// 12 | |
for (var k in testObj) { // 13 | |
if (k === testPropName) { // 14 | |
return false; // 15 | |
} // 16 | |
} // 17 | |
} catch (e) { // 18 | |
return false; // 19 | |
} // 20 | |
// 21 | |
return testObj[testPropName] === testObj; // 22 | |
} // 23 | |
// 24 | |
// The name `babelHelpers` is hard-coded in Babel. Otherwise we would make it // 25 | |
// something capitalized and more descriptive, like `BabelRuntime`. // 26 | |
babelHelpers = { // 27 | |
// Meteor-specific runtime helper for wrapping the object of for-in // 28 | |
// loops, so that inherited Array methods defined by es5-shim can be // 29 | |
// ignored in browsers where they cannot be defined as non-enumerable. // 30 | |
sanitizeForInObject: canDefineNonEnumerableProperties() // 31 | |
? function (value) { return value; } // 32 | |
: function (obj) { // 33 | |
if (Array.isArray(obj)) { // 34 | |
var newObj = {}; // 35 | |
var keys = Object.keys(obj); // 36 | |
var keyCount = keys.length; // 37 | |
for (var i = 0; i < keyCount; ++i) { // 38 | |
var key = keys[i]; // 39 | |
newObj[key] = obj[key]; // 40 | |
} // 41 | |
return newObj; // 42 | |
} // 43 | |
// 44 | |
return obj; // 45 | |
}, // 46 | |
// 47 | |
// es6.templateLiterals // 48 | |
// Constructs the object passed to the tag function in a tagged // 49 | |
// template literal. // 50 | |
taggedTemplateLiteralLoose: function (strings, raw) { // 51 | |
// Babel's own version of this calls Object.freeze on `strings` and // 52 | |
// `strings.raw`, but it doesn't seem worth the compatibility and // 53 | |
// performance concerns. If you're writing code against this helper, // 54 | |
// don't add properties to these objects. // 55 | |
strings.raw = raw; // 56 | |
return strings; // 57 | |
}, // 58 | |
// 59 | |
// es6.classes // 60 | |
// Checks that a class constructor is being called with `new`, and throws // 61 | |
// an error if it is not. // 62 | |
classCallCheck: function (instance, Constructor) { // 63 | |
if (!(instance instanceof Constructor)) { // 64 | |
throw new TypeError("Cannot call a class as a function"); // 65 | |
} // 66 | |
}, // 67 | |
// 68 | |
// es6.classes // 69 | |
inherits: function (subClass, superClass) { // 70 | |
if (typeof superClass !== "function" && superClass !== null) { // 71 | |
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); | |
} // 73 | |
// 74 | |
if (superClass) { // 75 | |
if (Object.create) { // 76 | |
// All but IE 8 // 77 | |
subClass.prototype = Object.create(superClass.prototype, { // 78 | |
constructor: { // 79 | |
value: subClass, // 80 | |
enumerable: false, // 81 | |
writable: true, // 82 | |
configurable: true // 83 | |
} // 84 | |
}); // 85 | |
} else { // 86 | |
// IE 8 path. Slightly worse for modern browsers, because `constructor` // 87 | |
// is enumerable and shows up in the inspector unnecessarily. // 88 | |
// It's not an "own" property of any instance though. // 89 | |
// // 90 | |
// For correctness when writing code, // 91 | |
// don't enumerate all the own-and-inherited properties of an instance // 92 | |
// of a class and expect not to find `constructor` (but who does that?). // 93 | |
var F = function () { // 94 | |
this.constructor = subClass; // 95 | |
}; // 96 | |
F.prototype = superClass.prototype; // 97 | |
subClass.prototype = new F(); // 98 | |
} // 99 | |
// 100 | |
// For modern browsers, this would be `subClass.__proto__ = superClass`, // 101 | |
// but IE <=10 don't support `__proto__`, and in this case the difference // 102 | |
// would be detectable; code that works in modern browsers could easily // 103 | |
// fail on IE 8 if we ever used the `__proto__` trick. // 104 | |
// // 105 | |
// There's no perfect way to make static methods inherited if they are // 106 | |
// assigned after declaration of the classes. The best we can do is // 107 | |
// to copy them. In other words, when you write `class Foo // 108 | |
// extends Bar`, we copy the static methods from Bar onto Foo, but future // 109 | |
// ones are not copied. // 110 | |
// // 111 | |
// For correctness when writing code, don't add static methods to a class // 112 | |
// after you subclass it. // 113 | |
for (var k in superClass) { // 114 | |
if (hasOwn.call(superClass, k)) { // 115 | |
subClass[k] = superClass[k]; // 116 | |
} // 117 | |
} // 118 | |
} // 119 | |
}, // 120 | |
// 121 | |
createClass: (function () { // 122 | |
var hasDefineProperty = false; // 123 | |
try { // 124 | |
// IE 8 has a broken Object.defineProperty, so feature-test by // 125 | |
// trying to call it. // 126 | |
Object.defineProperty({}, 'x', {}); // 127 | |
hasDefineProperty = true; // 128 | |
} catch (e) {} // 129 | |
// 130 | |
function defineProperties(target, props) { // 131 | |
for (var i = 0; i < props.length; i++) { // 132 | |
var descriptor = props[i]; // 133 | |
descriptor.enumerable = descriptor.enumerable || false; // 134 | |
descriptor.configurable = true; // 135 | |
if ("value" in descriptor) descriptor.writable = true; // 136 | |
Object.defineProperty(target, descriptor.key, descriptor); // 137 | |
} // 138 | |
} // 139 | |
// 140 | |
return function (Constructor, protoProps, staticProps) { // 141 | |
if (! hasDefineProperty) { // 142 | |
// e.g. `class Foo { get bar() {} }`. If you try to use getters and // 143 | |
// setters in IE 8, you will get a big nasty error, with or without // 144 | |
// Babel. I don't know of any other syntax features besides getters // 145 | |
// and setters that will trigger this error. // 146 | |
throw new Error( // 147 | |
"Your browser does not support this type of class property. " + // 148 | |
"For example, Internet Explorer 8 does not support getters and " + // 149 | |
"setters."); // 150 | |
} // 151 | |
// 152 | |
if (protoProps) defineProperties(Constructor.prototype, protoProps); // 153 | |
if (staticProps) defineProperties(Constructor, staticProps); // 154 | |
return Constructor; // 155 | |
}; // 156 | |
})(), // 157 | |
// 158 | |
// es7.objectRestSpread and react (JSX) // 159 | |
_extends: Object.assign || (function (target) { // 160 | |
for (var i = 1; i < arguments.length; i++) { // 161 | |
var source = arguments[i]; // 162 | |
for (var key in source) { // 163 | |
if (hasOwn.call(source, key)) { // 164 | |
target[key] = source[key]; // 165 | |
} // 166 | |
} // 167 | |
} // 168 | |
return target; // 169 | |
}), // 170 | |
// 171 | |
// es6.destructuring // 172 | |
objectWithoutProperties: function (obj, keys) { // 173 | |
var target = {}; // 174 | |
outer: for (var i in obj) { // 175 | |
if (! hasOwn.call(obj, i)) continue; // 176 | |
for (var j = 0; j < keys.length; j++) { // 177 | |
if (keys[j] === i) continue outer; // 178 | |
} // 179 | |
target[i] = obj[i]; // 180 | |
} // 181 | |
return target; // 182 | |
}, // 183 | |
// 184 | |
// es6.destructuring // 185 | |
objectDestructuringEmpty: function (obj) { // 186 | |
if (obj == null) throw new TypeError("Cannot destructure undefined"); // 187 | |
}, // 188 | |
// 189 | |
// es6.spread // 190 | |
bind: Function.prototype.bind || (function () { // 191 | |
var isCallable = function (value) { return typeof value === 'function'; }; // 192 | |
var $Object = Object; // 193 | |
var to_string = Object.prototype.toString; // 194 | |
var array_slice = Array.prototype.slice; // 195 | |
var array_concat = Array.prototype.concat; // 196 | |
var array_push = Array.prototype.push; // 197 | |
var max = Math.max; // 198 | |
var Empty = function Empty() {}; // 199 | |
// 200 | |
// Copied from es5-shim.js (3ac7942). See original for more comments. // 201 | |
return function bind(that) { // 202 | |
var target = this; // 203 | |
if (!isCallable(target)) { // 204 | |
throw new TypeError('Function.prototype.bind called on incompatible ' + target); // 205 | |
} // 206 | |
// 207 | |
var args = array_slice.call(arguments, 1); // 208 | |
// 209 | |
var bound; // 210 | |
var binder = function () { // 211 | |
// 212 | |
if (this instanceof bound) { // 213 | |
var result = target.apply( // 214 | |
this, // 215 | |
array_concat.call(args, array_slice.call(arguments)) // 216 | |
); // 217 | |
if ($Object(result) === result) { // 218 | |
return result; // 219 | |
} // 220 | |
return this; // 221 | |
} else { // 222 | |
return target.apply( // 223 | |
that, // 224 | |
array_concat.call(args, array_slice.call(arguments)) // 225 | |
); // 226 | |
} // 227 | |
}; // 228 | |
// 229 | |
var boundLength = max(0, target.length - args.length); // 230 | |
// 231 | |
var boundArgs = []; // 232 | |
for (var i = 0; i < boundLength; i++) { // 233 | |
array_push.call(boundArgs, '$' + i); // 234 | |
} // 235 | |
// 236 | |
// Create a Function from source code so that it has the right `.length`. // 237 | |
// Probably not important for Babel. This code violates CSPs that ban // 238 | |
// `eval`, but the browsers that need this polyfill don't have CSP! // 239 | |
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder); | |
// 241 | |
if (target.prototype) { // 242 | |
Empty.prototype = target.prototype; // 243 | |
bound.prototype = new Empty(); // 244 | |
Empty.prototype = null; // 245 | |
} // 246 | |
// 247 | |
return bound; // 248 | |
}; // 249 | |
// 250 | |
})(), // 251 | |
// 252 | |
slice: Array.prototype.slice // 253 | |
}; // 254 | |
// 255 | |
///////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
}).call(this); | |
/* Exports */ | |
if (typeof Package === 'undefined') Package = {}; | |
Package['babel-runtime'] = { | |
babelHelpers: babelHelpers | |
}; | |
})(); | |
(function () { | |
/* Imports */ | |
var Meteor = Package.meteor.Meteor; | |
var check = Package.check.check; | |
var Match = Package.check.Match; | |
/* Package-scope variables */ | |
var Babel, BabelCompiler; | |
(function(){ | |
//////////////////////////////////////////////////////////////////////////////// | |
// // | |
// packages/babel-compiler/babel.js // | |
// // | |
//////////////////////////////////////////////////////////////////////////////// | |
// 2 | |
function validateExtraFeatures(extraFeatures) { // 3 | |
if (extraFeatures) { // 4 | |
check(extraFeatures, { // 5 | |
// Modify options to enable ES2015 module syntax. // 6 | |
modules: Match.Optional(Boolean), // 7 | |
// Modify options to enable async/await syntax powered by Fibers. // 8 | |
meteorAsyncAwait: Match.Optional(Boolean), // 9 | |
// Modify options to enable React/JSX syntax. // 10 | |
react: Match.Optional(Boolean), // 11 | |
// Improve compatibility in older versions of Internet Explorer. // 12 | |
jscript: Match.Optional(Boolean) // 13 | |
}); // 14 | |
} // 15 | |
} // 16 | |
// 17 | |
/** // 18 | |
* Returns a new object containing default options appropriate for // 19 | |
*/ // 20 | |
function getDefaultOptions(extraFeatures) { // 21 | |
validateExtraFeatures(extraFeatures); // 22 | |
// 23 | |
// See https://github.com/meteor/babel/blob/master/options.js for more // 24 | |
// information about what the default options are. // 25 | |
var options = meteorBabel.getDefaultOptions(extraFeatures); // 26 | |
// 27 | |
// The sourceMap option should probably be removed from the default // 28 | |
// options returned by meteorBabel.getDefaultOptions. // 29 | |
delete options.sourceMap; // 30 | |
// 31 | |
return options; // 32 | |
} // 33 | |
// 34 | |
Babel = { // 35 | |
getDefaultOptions: getDefaultOptions, // 36 | |
// 37 | |
validateExtraFeatures: validateExtraFeatures, // 38 | |
// 39 | |
compile: function (source, options) { // 40 | |
options = options || getDefaultOptions(); // 41 | |
return meteorBabel.compile(source, options); // 42 | |
}, // 43 | |
// 44 | |
// Provided for backwards compatibility; prefer Babel.compile. // 45 | |
transformMeteor: function (source, extraOptions) { // 46 | |
var options = getDefaultOptions(); // 47 | |
// 48 | |
if (extraOptions) { // 49 | |
if (extraOptions.extraWhitelist) { // 50 | |
options.whitelist.push.apply( // 51 | |
options.whitelist, // 52 | |
extraOptions.extraWhitelist // 53 | |
); // 54 | |
} // 55 | |
// 56 | |
for (var key in extraOptions) { // 57 | |
if (key !== "extraWhitelist" && // 58 | |
hasOwnProperty.call(extraOptions, key)) { // 59 | |
options[key] = extraOptions[key]; // 60 | |
} // 61 | |
} // 62 | |
} // 63 | |
// 64 | |
return meteorBabel.compile(source, options); // 65 | |
}, // 66 | |
// 67 | |
setCacheDir: function (cacheDir) { // 68 | |
meteorBabel.setCacheDir(cacheDir); // 69 | |
} // 70 | |
}; // 71 | |
// 72 | |
//////////////////////////////////////////////////////////////////////////////// | |
}).call(this); | |
(function(){ | |
//////////////////////////////////////////////////////////////////////////////// | |
// // | |
// packages/babel-compiler/babel-compiler.js // | |
// // | |
//////////////////////////////////////////////////////////////////////////////// | |
// | |
/** // 1 | |
* A compiler that can be instantiated with features and used inside // 2 | |
* Plugin.registerCompiler // 3 | |
* @param {Object} extraFeatures The same object that getDefaultOptions takes | |
*/ // 5 | |
BabelCompiler = function BabelCompiler(extraFeatures) { // 6 | |
Babel.validateExtraFeatures(extraFeatures); // 7 | |
this.extraFeatures = extraFeatures; // 8 | |
}; // 9 | |
// 10 | |
var BCp = BabelCompiler.prototype; // 11 | |
var excludedFileExtensionPattern = /\.es5\.js$/i; // 12 | |
// 13 | |
BCp.processFilesForTarget = function (inputFiles) { // 14 | |
var self = this; // 15 | |
// 16 | |
inputFiles.forEach(function (inputFile) { // 17 | |
var source = inputFile.getContentsAsString(); // 18 | |
var inputFilePath = inputFile.getPathInPackage(); // 19 | |
var outputFilePath = inputFile.getPathInPackage(); // 20 | |
var fileOptions = inputFile.getFileOptions(); // 21 | |
var toBeAdded = { // 22 | |
sourcePath: inputFilePath, // 23 | |
path: outputFilePath, // 24 | |
data: source, // 25 | |
hash: inputFile.getSourceHash(), // 26 | |
sourceMap: null, // 27 | |
bare: !! fileOptions.bare // 28 | |
}; // 29 | |
// 30 | |
// If you need to exclude a specific file within a package from Babel // 31 | |
// compilation, pass the { transpile: false } options to api.addFiles // 32 | |
// when you add that file. // 33 | |
if (fileOptions.transpile !== false && // 34 | |
// If you need to exclude a specific file within an app from Babel // 35 | |
// compilation, give it the following file extension: .es5.js // 36 | |
! excludedFileExtensionPattern.test(inputFilePath)) { // 37 | |
// 38 | |
var targetCouldBeInternetExplorer8 = // 39 | |
inputFile.getArch() === "web.browser"; // 40 | |
// 41 | |
self.extraFeatures = self.extraFeatures || {}; // 42 | |
if (! self.extraFeatures.hasOwnProperty("jscript")) { // 43 | |
// Perform some additional transformations to improve // 44 | |
// compatibility in older browsers (e.g. wrapping named function // 45 | |
// expressions, per http://kiro.me/blog/nfe_dilemma.html). // 46 | |
self.extraFeatures.jscript = targetCouldBeInternetExplorer8; // 47 | |
} // 48 | |
// 49 | |
var babelOptions = Babel.getDefaultOptions(self.extraFeatures); // 50 | |
// 51 | |
babelOptions.sourceMap = true; // 52 | |
babelOptions.filename = inputFilePath; // 53 | |
babelOptions.sourceFileName = "/" + inputFilePath; // 54 | |
babelOptions.sourceMapName = "/" + outputFilePath + ".map"; // 55 | |
// 56 | |
try { // 57 | |
var result = Babel.compile(source, babelOptions); // 58 | |
} catch (e) { // 59 | |
if (e.loc) { // 60 | |
inputFile.error({ // 61 | |
message: e.message, // 62 | |
sourcePath: inputFilePath, // 63 | |
line: e.loc.line, // 64 | |
column: e.loc.column, // 65 | |
}); // 66 | |
// 67 | |
return; // 68 | |
} // 69 | |
// 70 | |
throw e; // 71 | |
} // 72 | |
// 73 | |
toBeAdded.data = result.code; // 74 | |
toBeAdded.hash = result.hash; // 75 | |
toBeAdded.sourceMap = result.map; // 76 | |
} // 77 | |
// 78 | |
inputFile.addJavaScript(toBeAdded); // 79 | |
}); // 80 | |
}; // 81 | |
// 82 | |
BCp.setDiskCacheDirectory = function (cacheDir) { // 83 | |
Babel.setCacheDir(cacheDir); // 84 | |
}; // 85 | |
// 86 | |
//////////////////////////////////////////////////////////////////////////////// | |
}).call(this); | |
/* Exports */ | |
if (typeof Package === 'undefined') Package = {}; | |
Package['babel-compiler'] = { | |
Babel: Babel, | |
BabelCompiler: BabelCompiler | |
}; | |
})(); | |
(function () { | |
/* Imports */ | |
var Meteor = Package.meteor.Meteor; | |
var Babel = Package['babel-compiler'].Babel; | |
var BabelCompiler = Package['babel-compiler'].BabelCompiler; | |
/* Package-scope variables */ | |
var ECMAScript; | |
(function(){ | |
/////////////////////////////////////////////////////////////////////// | |
// // | |
// packages/ecmascript/ecmascript.js // | |
// // | |
/////////////////////////////////////////////////////////////////////// | |
// | |
ECMAScript = { // 1 | |
compileForShell: function (command) { // 2 | |
var babelOptions = Babel.getDefaultOptions(); // 3 | |
babelOptions.sourceMap = false; // 4 | |
babelOptions.ast = false; // 5 | |
babelOptions.externalHelpers = true; // 6 | |
return Babel.compile(command, babelOptions).code; // 7 | |
} // | |
}; // | |
/////////////////////////////////////////////////////////////////////// | |
}).call(this); | |
/* Exports */ | |
if (typeof Package === 'undefined') Package = {}; | |
Package.ecmascript = { | |
ECMAScript: ECMAScript | |
}; | |
})(); | |
(function () { | |
/* Imports */ | |
var Meteor = Package.meteor.Meteor; | |
/* Package-scope variables */ | |
var Symbol, Map, Set; | |
(function(){ | |
/////////////////////////////////////////////////////////////////////// | |
// // | |
// packages/ecmascript-runtime/runtime.js // | |
// // | |
/////////////////////////////////////////////////////////////////////// | |
// | |
// var runtime = Npm.require("meteor-ecmascript-runtime"); // 1 | |
// 2 | |
Symbol = {}; // 3 | |
Map = {}; // 4 | |
Set = {}; // 5 | |
// 6 | |
/////////////////////////////////////////////////////////////////////// | |
}).call(this); | |
/* Exports */ | |
if (typeof Package === 'undefined') Package = {}; | |
Package['ecmascript-runtime'] = { | |
Symbol: Symbol, | |
Map: Map, | |
Set: Set | |
}; | |
})(); | |
(function () { | |
/* Imports */ | |
var Meteor = Package.meteor.Meteor; | |
/* Package-scope variables */ | |
var Promise; | |
(function(){ | |
//////////////////////////////////////////////////////////////////////////// | |
// // | |
// packages/promise/promise_server.js // | |
// // | |
//////////////////////////////////////////////////////////////////////////// | |
// | |
// var MeteorPromise = Npm.require("meteor-promise"); // 1 | |
// Define MeteorPromise.Fiber so that every Promise callback can run in a | |
// Fiber drawn from a pool of reusable Fibers. // 3 | |
// MeteorPromise.Fiber = Npm.require("fibers"); // 4 | |
Promise = {}; // 5 | |
// 6 | |
//////////////////////////////////////////////////////////////////////////// | |
}).call(this); | |
/* Exports */ | |
if (typeof Package === 'undefined') Package = {}; | |
Package.promise = { | |
Promise: Promise | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment