From c0765cd41faf25c0def691a84cf2123bfebe8566 Mon Sep 17 00:00:00 2001 From: Endel Dreyer Date: Tue, 10 Feb 2015 17:21:39 -0200 Subject: [PATCH] add Collection.prototype.clone method --- dist/hook.js | 22 +++++++++++++++++++++- dist/hook.min.js | 2 +- src/collection.js | 20 ++++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/dist/hook.js b/dist/hook.js index d29e8e4..891e3a4 100644 --- a/dist/hook.js +++ b/dist/hook.js @@ -3,7 +3,7 @@ * https://github.com/doubleleft/hook-javascript * * @copyright 2015 Doubleleft - * @build 1/26/2015 + * @build 2/10/2015 */ (function(window) { // @@ -11162,6 +11162,26 @@ Hook.Collection.prototype.buildQuery = function() { return query; }; +/** + * Return a new copy of the collection. + * @method clone + * @return {Collection} + */ +Hook.Collection.prototype.clone = function() { + var clone = this.client.collection(this.name); + + // copy attributes to the new instance + clone.options = _.clone(this.options); + clone.wheres = _.clone(this.wheres); + clone.ordering = _.clone(this.ordering); + clone._group = _.clone(this._group); + clone._limit = _.clone(this._limit); + clone._offset = _.clone(this._offset); + clone._remember = _.clone(this._remember); + + return clone; +}; + /** * module Hook * class Hook.CollectionItem diff --git a/dist/hook.min.js b/dist/hook.min.js index 12d32cb..86488c6 100644 --- a/dist/hook.min.js +++ b/dist/hook.min.js @@ -1,3 +1,3 @@ !function(a){"undefined"==typeof a.define&&(a.define=function(b,c){try{delete a.define}catch(d){a.define=void 0}"function"==typeof b?a.when=b():a[b]=c()},a.define.amd={}),function(a){function b(b){return function(e,f){if("string"==typeof f){var g=c.exec(f);if(g)return new Date(f);if(!JSON.parseMsAjaxDate)return f;if(g=d.exec(f)){var h=g[1].split(/[-+,.]/);return new Date(h[0]?+h[0]:0-+h[1])}}return b!==a?b(e,f):f}}if(this.JSON&&!this.JSON.dateParser){var c=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.{0,1}\d*))(?:Z|(\+|-)([\d|:]*))?$/,d=/^\/Date\((d|-|.*)\)[\/|\\]$/;JSON.parseMsAjaxDate=!1,JSON.useDateParser=function(a){"undefined"!=typeof a?JSON._parseSaved&&(JSON.parse=JSON._parseSaved,JSON._parseSaved=null):JSON.parseSaved||(JSON._parseSaved=JSON.parse,JSON.parse=JSON.parseWithDate)},JSON.dateParser=b(),JSON.parseWithDate=function(a,c){var d=JSON._parseSaved?JSON._parseSaved:JSON.parse;try{var e=d(a,b(c));return e}catch(f){throw new Error("JSON content could not be parsed")}},JSON.dateStringToDate=function(a,b){if(b||(b=null),!a)return b;if(a.getTime)return a;('"'===a[0]||"'"===a[0])&&(a=a.substr(1,a.length-2));var e=c.exec(a);if(e)return new Date(a);if(!JSON.parseMsAjaxDate)return b;if(e=d.exec(a)){var f=e[1].split(/[-,.]/);return new Date(+f[0])}return b}}}(),function(a){"use strict";a(function(a){function b(a,b,c,d){return e(a).then(b,c,d)}function c(a){return new d(a,P.PromiseStatus&&P.PromiseStatus())}function d(a,b){function c(){return k?k.inspect():A()}function d(a,b,c,d,e){function f(f){f._when(a,b,c,d,e)}l?l.push(f):B(function(){f(k)})}function e(a){if(l){var c=l;l=T,k=j(h,a),B(function(){b&&o(k,b),i(c,k)})}}function f(a){e(new m(a))}function g(a){if(l){var b=l;B(function(){i(b,new n(a))})}}var h,k,l=[];h=this,this._status=b,this.inspect=c,this._when=d;try{a(e,f,g)}catch(p){f(p)}}function e(a){return a instanceof d?a:f(a)}function f(a){return c(function(b){b(a)})}function g(a){return b(a,function(a){return new m(a)})}function h(){function a(a,c,g){b.resolve=b.resolver.resolve=function(b){return e?f(b):(e=!0,a(b),d)},b.reject=b.resolver.reject=function(a){return e?f(new m(a)):(e=!0,c(a),d)},b.notify=b.resolver.notify=function(a){return g(a),a}}var b,d,e;return b={promise:T,resolve:T,reject:T,notify:T,resolver:{resolve:T,reject:T,notify:T}},b.promise=d=c(a),b}function i(a,b){for(var c=0;c>>0,i=Math.max(0,Math.min(d,o)),k=[],j=o-i+1,l=[],i)for(n=function(a){l.push(a),--j||(m=n=D,e(l))},m=function(a){k.push(a),--i||(m=n=D,c(k))},p=0;o>p;++p)p in a&&b(a[p],h,g,f);else c(k)}return c(h).then(e,f,g)})}function r(a,b,c,d){function e(a){return b?b(a[0]):a[0]}return q(a,1,e,c,d)}function s(a,b,c,d){return w(a,D).then(b,c,d)}function t(){return w(arguments,D)}function u(a){return w(a,y,z)}function v(a,b){return w(a,b)}function w(a,c,e){return b(a,function(a){function f(d,f,g){function h(a,h){b(a,c,e).then(function(a){i[h]=a,--k||d(i)},f,g)}var i,j,k,l;if(k=j=a.length>>>0,i=[],!k)return void d(i);for(l=0;j>l;l++)l in a?h(a[l],l):--k}return new d(f)})}function x(a,c){var d=J(I,arguments,1);return b(a,function(a){var e;return e=a.length,d[0]=function(a,d,f){return b(a,function(a){return b(d,function(b){return c(a,b,f,e)})})},H.apply(a,d)})}function y(a){return{state:"fulfilled",value:a}}function z(a){return{state:"rejected",reason:a}}function A(){return{state:"pending"}}function B(a){1===L.push(a)&&K(C)}function C(){i(L),L=[]}function D(a){return a}function E(a){throw"function"==typeof P.reportUnhandled?P.reportUnhandled():B(function(){throw a}),a}b.promise=c,b.resolve=f,b.reject=g,b.defer=h,b.join=t,b.all=s,b.map=v,b.reduce=x,b.settle=u,b.any=r,b.some=q,b.isPromise=p,b.isPromiseLike=p,F=d.prototype,F.then=function(a,b,c){var e=this;return new d(function(d,f,g){e._when(d,g,a,b,c)},this._status&&this._status.observed())},F["catch"]=F.otherwise=function(a){return this.then(T,a)},F["finally"]=F.ensure=function(a){function b(){return f(a())}return"function"==typeof a?this.then(b,b)["yield"](this):this},F.done=function(a,b){this.then(a,b)["catch"](E)},F["yield"]=function(a){return this.then(function(){return a})},F.tap=function(a){return this.then(a)["yield"](this)},F.spread=function(a){return this.then(function(b){return s(b,function(b){return a.apply(T,b)})})},F.always=function(a,b){return this.then(a,a,b)},G=Object.create||function(a){function b(){}return b.prototype=a,new b},l.prototype=G(F),l.prototype.inspect=function(){return y(this.value)},l.prototype._when=function(a,b,c){try{a("function"==typeof c?c(this.value):this.value)}catch(d){a(new m(d))}},m.prototype=G(F),m.prototype.inspect=function(){return z(this.value)},m.prototype._when=function(a,b,c,d){try{a("function"==typeof d?d(this.value):this)}catch(e){a(new m(e))}},n.prototype=G(F),n.prototype._when=function(a,b,c,d,e){try{b("function"==typeof e?e(this.value):this.value)}catch(f){b(f)}};var F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T;if(R=a,L=[],P="undefined"!=typeof console?console:b,"object"==typeof process&&process.nextTick)K=process.nextTick;else if(S="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)K=function(a,b,c){var d=a.createElement("div");return new b(c).observe(d,{attributes:!0}),function(){d.setAttribute("x","x")}}(document,S,C);else try{K=R("vertx").runOnLoop||R("vertx").runOnContext}catch(U){Q=setTimeout,K=function(a){Q(a,0)}}return M=Function.prototype,N=M.call,J=M.bind?N.bind(N):function(a,b){return a.apply(b,I.call(arguments,2))},O=[],I=O.slice,H=O.reduce||function(a){var b,c,d,e,f;if(f=0,b=Object(this),e=b.length>>>0,c=arguments,c.length<=1)for(;;){if(f in b){d=b[f++];break}if(++f>=e)throw new TypeError}else d=c[1];for(;e>f;++f)f in b&&(d=a(d,b[f],f,b));return d},b})}("function"==typeof define&&define.amd?define:function(a){module.exports=a(require)}),function(a,b){"object"==typeof exports?module.exports=b():"function"==typeof define&&define.amd?define("uxhr",b):a.uxhr=b()}(this,function(){"use strict";return function(b,c,d){c=c||"",d=d||{};var e=d.complete||function(){},f=d.success||function(){},g=d.error||function(){},h=d.timeout||0,i=d.ontimeout||function(){},j=d.onprogress||function(){},k=d.headers||{},l=d.method||"GET",m=d.sync||!1,n=function(){return 0===b.indexOf("http")&&"undefined"!=typeof XDomainRequest?new XDomainRequest:new XMLHttpRequest}();if(!n)throw new Error("Browser doesn't support XHR");var o="undefined"!=typeof a.FormData;if("string"!=typeof c&&o&&!(c instanceof a.FormData)){var p=[];for(var q in c)p.push(q+"="+c[q]);c=p.join("&")}if("GET"===l&&c&&(b+=b.indexOf("?")>=0?"&"+c:"?"+c),n.open(l,b,!m),m||"ontimeout"in n&&(n.timeout=h,n.ontimeout=i),"onprogress"in n&&(n.onprogress=j),n.onload=function(){e(n.responseText,n.status),f(n.responseText)},n.onerror=function(){e(n.responseText),g(n.responseText,n.status)},"undefined"!=typeof n.setRequestHeader)for(var r in k)n.setRequestHeader(r,k[r]);return n.send("GET"!==l?c:null),n}}),function(){function b(a,b,c){for(var d=(c||0)-1,e=a?a.length:0;++d-1?0:-1:a?0:-1}function e(a){var b=this.cache,c=typeof a;if("boolean"==c||null==a)b[a]=!0;else{"number"!=c&&"string"!=c&&(c="object");var d="number"==c?a:t+a,e=b[c]||(b[c]={});"object"==c?(e[d]||(e[d]=[])).push(a):e[d]=!0}}function f(a){return a.charCodeAt(0)}function g(a,b){for(var c=a.criteria,d=b.criteria,e=-1,f=c.length;++eh||"undefined"==typeof g)return 1;if(h>g||"undefined"==typeof h)return-1}}return a.index-b.index}function h(a){var b=-1,c=a.length,d=a[0],f=a[c/2|0],g=a[c-1];if(d&&"object"==typeof d&&f&&"object"==typeof f&&g&&"object"==typeof g)return!1;var h=k();h["false"]=h["null"]=h["true"]=h.undefined=!1;var i=k();for(i.array=a,i.cache=h,i.push=e;++be?0:e);++d=u&&f===b,j=[];if(i){var k=h(c);k?(f=d,c=k):i=!1}for(;++e-1:void 0});return e.pop(),f.pop(),s&&(l(e),l(f)),g}function cb(a,b,c,d,e){(Zd(b)?Yb:he)(b,function(b,f){var g,h,i=b,j=a[f];if(b&&((h=Zd(b))||ie(b))){for(var k=d.length;k--;)if(g=d[k]==b){j=e[k];break}if(!g){var l;c&&(i=c(j,b),(l="undefined"!=typeof i)&&(j=i)),l||(j=h?Zd(j)?j:[]:ie(j)?j:{}),d.push(b),e.push(j),l||cb(j,b,c,d,e)}}else c&&(i=c(j,b),"undefined"==typeof i&&(i=b)),"undefined"!=typeof i&&(j=i);a[f]=j})}function db(a,b){return a+Ed(Vd()*(b-a+1))}function eb(a,c,e){var f=-1,g=ib(),i=a?a.length:0,k=[],n=!c&&i>=u&&g===b,o=e||n?j():k;if(n){var p=h(o);g=d,o=p}for(;++f3&&"function"==typeof b[c-2])var d=X(b[--c-1],b[c--],2);else c>2&&"function"==typeof b[c-1]&&(d=b[--c]);for(var e=n(arguments,1,c),f=-1,g=j(),h=j();++fc?Sd(0,f+c):c)||0,Zd(a)?g=e(a,b,c)>-1:"number"==typeof f?g=(Jb(a)?a.indexOf(b,c):e(a,b,c))>-1:he(a,function(a){return++d>=c?!(g=a===b):void 0}),g}function Ub(a,b,d){var e=!0;b=c.createCallback(b,d,3);var f=-1,g=a?a.length:0;if("number"==typeof g)for(;++fg&&(g=j)}else b=null==b&&Jb(a)?f:c.createCallback(b,d,3),Yb(a,function(a,c,d){var f=b(a,c,d);f>e&&(e=f,g=a)});return g}function bc(a,b,d){var e=1/0,g=e;if("function"!=typeof b&&d&&d[b]===a&&(b=null),null==b&&Zd(a))for(var h=-1,i=a.length;++hj&&(g=j)}else b=null==b&&Jb(a)?f:c.createCallback(b,d,3),Yb(a,function(a,c,d){var f=b(a,c,d);e>f&&(e=f,g=a)});return g}function cc(a,b,d,e){if(!a)return d;var f=arguments.length<3;b=c.createCallback(b,e,4);var g=-1,h=a.length;if("number"==typeof h)for(f&&(d=a[++g]);++gd?Sd(0,e+d):d||0}else if(d){var f=Ac(a,c);return a[f]===c?f:-1}return b(a,c,d)}function sc(a,b,d){var e=0,f=a?a.length:0;if("number"!=typeof b&&null!=b){var g=f;for(b=c.createCallback(b,d,3);g--&&b(a[g],g,a);)e++}else e=null==b||d?1:b||e;return n(a,0,Td(Sd(0,f-e),f))}function tc(){for(var a=[],c=-1,e=arguments.length,f=j(),g=ib(),i=g===b,k=j();++c=u&&h(c?a[c]:k)))}var o=a[0],p=-1,q=o?o.length:0,r=[];a:for(;++pc?Sd(0,d+c):Td(c,d-1))+1);d--;)if(a[d]===b)return d;return-1}function wc(a){for(var b=arguments,c=0,d=b.length,e=a?a.length:0;++cf;){var h=f+g>>>1;d(a[h])1?arguments:arguments[0],b=-1,c=a?ac(me(a,"length")):0,d=nd(0>c?0:c);++b2?gb(a,17,n(arguments,2),null,b):gb(a,1,null,null,b)}function Jc(a){for(var b=arguments.length>1?_(arguments,!0,!1,1):ub(a),c=-1,d=b.length;++c2?gb(b,19,n(arguments,2),null,a):gb(b,3,null,null,a)}function Lc(){for(var a=arguments,b=a.length;b--;)if(!Db(a[b]))throw new wd;return function(){for(var b=arguments,c=a.length;c--;)b=[a[c].apply(this,b)];return b[0]}}function Mc(a,b){return b="number"==typeof b?b:+b||a.length,gb(a,4,null,null,null,b)}function Nc(a,b,c){var d,e,f,g,h,i,j,k=0,l=!1,m=!0;if(!Db(a))throw new wd;if(b=Sd(0,b)||0,c===!0){var n=!0;m=!1}else Eb(c)&&(n=c.leading,l="maxWait"in c&&(Sd(b,c.maxWait)||0),m="trailing"in c?c.trailing:m);var o=function(){var c=b-(oe()-g);if(0>=c){e&&Dd(e);var l=j;e=i=j=p,l&&(k=oe(),f=a.apply(h,d),i||e||(d=h=null))}else i=Jd(o,c)},q=function(){i&&Dd(i),e=i=j=p,(m||l!==b)&&(k=oe(),f=a.apply(h,d),i||e||(d=h=null))};return function(){if(d=arguments,g=oe(),h=this,j=m&&(i||!n),l===!1)var c=n&&!i;else{e||n||(k=g);var p=l-(g-k),r=0>=p;r?(e&&(e=Dd(e)),k=g,f=a.apply(h,d)):e||(e=Jd(q,p))}return r&&i?i=Dd(i):i||b===l||(i=Jd(o,b)),c&&(r=!0,f=a.apply(h,d)),!r||i||e||(d=h=null),f}}function Oc(a){if(!Db(a))throw new wd;var b=n(arguments,1);return Jd(function(){a.apply(p,b)},1)}function Pc(a,b){if(!Db(a))throw new wd;var c=n(arguments,2);return Jd(function(){a.apply(p,c)},b)}function Qc(a,b){if(!Db(a))throw new wd;var c=function(){var d=c.cache,e=b?b.apply(this,arguments):t+arguments[0];return Hd.call(d,e)?d[e]:d[e]=a.apply(this,arguments)};return c.cache={},c}function Rc(a){var b,c;if(!Db(a))throw new wd;return function(){return b?c:(b=!0,c=a.apply(this,arguments),a=null,c)}}function Sc(a){return gb(a,16,n(arguments,1))}function Tc(a){return gb(a,32,null,n(arguments,1))}function Uc(a,b,c){var d=!0,e=!0;if(!Db(a))throw new wd;return c===!1?d=!1:Eb(c)&&(d="leading"in c?c.leading:d,e="trailing"in c?c.trailing:e),U.leading=d,U.maxWait=b,U.trailing=e,Nc(a,b,U)}function Vc(a,b){return gb(b,16,[a])}function Wc(a){return function(){return a}}function Xc(a,b,c){var d=typeof a;if(null==a||"function"==d)return X(a,b,c);if("object"!=d)return bd(a);var e=_d(a),f=e[0],g=a[f];return 1!=e.length||g!==g||Eb(g)?function(b){for(var c=e.length,d=!1;c--&&(d=ab(b[e[c]],a[e[c]],null,!0)););return d}:function(a){var b=a[f];return g===b&&(0!==g||1/g==1/b)}}function Yc(a){return null==a?"":vd(a).replace(de,hb)}function Zc(a){return a}function $c(a,b,d){var f=!0,g=b&&ub(b);b&&(d||g.length)||(null==d&&(d=b),h=e,b=a,a=c,g=ub(b)),d===!1?f=!1:Eb(d)&&"chain"in d&&(f=d.chain);var h=a,i=Db(h);Yb(g,function(c){var d=a[c]=b[c];i&&(h.prototype[c]=function(){var b=this.__chain__,c=this.__wrapped__,e=[c];Id.apply(e,arguments);var g=d.apply(a,e);if(f||b){if(c===g&&Eb(g))return this;g=new h(g),g.__chain__=b}return g})})}function _c(){return a._=zd,this}function ad(){}function bd(a){return function(b){return b[a]}}function cd(a,b,c){var d=null==a,e=null==b;if(null==c&&("boolean"==typeof a&&e?(c=a,a=1):e||"boolean"!=typeof b||(c=b,e=!0)),d&&e&&(b=1),a=+a||0,e?(b=a,a=0):b=+b||0,c||a%1||b%1){var f=Vd();return Td(a+f*(b-a+parseFloat("1e-"+((f+"").length-1))),b)}return db(a,b)}function dd(a,b){if(a){var c=a[b];return Db(c)?a[b]():c}}function ed(a,b,d){var e=c.templateSettings;a=vd(a||""),d=fe({},d,e);var f,g=fe({},d.imports,e.imports),h=_d(g),j=Rb(g),k=0,l=d.interpolate||F,m="__p += '",n=ud((d.escape||F).source+"|"+l.source+"|"+(l===D?A:F).source+"|"+(d.evaluate||F).source+"|$","g");a.replace(n,function(b,c,d,e,g,h){return d||(d=e),m+=a.slice(k,h).replace(H,i),c&&(m+="' +\n__e("+c+") +\n'"),g&&(f=!0,m+="';\n"+g+";\n__p += '"),d&&(m+="' +\n((__t = ("+d+")) == null ? '' : __t) +\n'"),k=h+b.length,b}),m+="';\n";var o=d.variable,q=o;q||(o="obj",m="with ("+o+") {\n"+m+"\n}\n"),m=(f?m.replace(x,""):m).replace(y,"$1").replace(z,"$1;"),m="function("+o+") {\n"+(q?"":o+" || ("+o+" = {});\n")+"var __t, __p = '', __e = _.escape"+(f?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+m+"return __p\n}";var r="\n/*\n//# sourceURL="+(d.sourceURL||"/lodash/template/source["+J++ +"]")+"\n*/";try{var s=qd(h,"return "+m+r).apply(p,j)}catch(t){throw t.source=m,t}return b?s(b):(s.source=m,s)}function fd(a,b,c){a=(a=+a)>-1?a:0;var d=-1,e=nd(a);for(b=X(b,c,1);++d/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:D,variable:"",imports:{_:c}},Nd||(v=function(){function b(){}return function(c){if(Eb(c)){b.prototype=c;var d=new b;b.prototype=null}return d||a.Object()}}());var Yd=Md?function(a,b){V.value=b,Md(a,"__bindData__",V)}:ad,Zd=Od||function(a){return a&&"object"==typeof a&&"number"==typeof a.length&&Ad.call(a)==L||!1},$d=function(a){var b,c=a,d=[];if(!c)return d;if(!W[typeof a])return d;for(b in c)Hd.call(c,b)&&d.push(b);return d},_d=Rd?function(a){return Eb(a)?Rd(a):[]}:$d,ae={"&":"&","<":"<",">":">",'"':""","'":"'"},be=wb(ae),ce=ud("("+_d(be).join("|")+")","g"),de=ud("["+_d(ae).join("")+"]","g"),ee=function(a,b,c){var d,e=a,f=e;if(!e)return f;var g=arguments,h=0,i="number"==typeof c?2:g.length;if(i>3&&"function"==typeof g[i-2])var j=X(g[--i-1],g[i--],2);else i>2&&"function"==typeof g[i-1]&&(j=g[--i]);for(;++h/g,E=RegExp("^["+w+"]*0+(?=.$)"),F=/($^)/,G=/\bthis\b/,H=/['\n\r\t\u2028\u2029\\]/g,I=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"],J=0,K="[object Arguments]",L="[object Array]",M="[object Boolean]",N="[object Date]",O="[object Function]",P="[object Number]",Q="[object Object]",R="[object RegExp]",S="[object String]",T={};T[O]=!1,T[K]=T[L]=T[M]=T[N]=T[P]=T[Q]=T[R]=T[S]=!0;var U={leading:!1,maxWait:0,trailing:!1},V={configurable:!1,enumerable:!1,value:null,writable:!1},W={"boolean":!1,"function":!0,object:!0,number:!1,string:!1,undefined:!1},X={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"},Y=W[typeof a]&&a||this,Z=W[typeof exports]&&exports&&!exports.nodeType&&exports,$=W[typeof module]&&module&&!module.nodeType&&module,_=$&&$.exports===Z&&Z,ab=W[typeof c]&&c;!ab||ab.global!==ab&&ab.window!==ab||(Y=ab);var bb=o();"function"==typeof define&&"object"==typeof define.amd&&define.amd?(Y._=bb,define(function(){return bb})):Z&&$?_?($.exports=bb)._=bb:Z._=bb:Y._=bb}.call(this),!function(a){"use strict";var b=a.HTMLCanvasElement&&a.HTMLCanvasElement.prototype,c=a.Blob&&function(){try{return Boolean(new Blob)}catch(a){return!1}}(),d=c&&a.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(a){return!1}}(),e=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder||a.MSBlobBuilder,f=(c||e)&&a.atob&&a.ArrayBuffer&&a.Uint8Array&&function(a){var b,f,g,h,i,j;for(b=a.split(",")[0].indexOf("base64")>=0?atob(a.split(",")[1]):decodeURIComponent(a.split(",")[1]),f=new ArrayBuffer(b.length),g=new Uint8Array(f),h=0;hc?z:c>A?A:c}function h(a,b,c){try{"function"==typeof b&&b.call(a,c)}catch(e){d(e)}}function i(b,d){function i(){L=s,null!==H&&(H.abort(),H=null),0!==I&&(clearTimeout(I),I=0),0!==J&&(clearTimeout(J),J=0),E.readyState=s}function j(a){var b=L===r||L===q?H.responseText||"":"",c=null,d=!1;if(L===q){var i=0,j="",k="";if(n)try{i=Number(H.status||0),j=String(H.statusText||""),k=String(H.getResponseHeader("Content-Type")||"")}catch(l){i=0}else i=200,k=H.contentType;if(200===i&&y.test(k)){if(L=r,G=!0,F=B,E.readyState=r,c=new e("open"),E.dispatchEvent(c),h(E,E.onopen,c),L===s)return}else if(0!==i){var m="";m=200!==i?"EventSource's response has a status "+i+" "+j.replace(/\s+/g," ")+" that is not 200. Aborting the connection.":"EventSource's response has a Content-Type specifying an unsupported type: "+k.replace(/\s+/g," ")+". Aborting the connection.",setTimeout(function(){throw new Error(m)}),d=!0}}if(L===r){b.length>K&&(G=!0);for(var o=K-1,z=b.length,J="\n";++o1048576||0===I&&!G)?0===I&&(G=!1,I=setTimeout(P,C)):(L=p,H.abort(),0!==I&&(clearTimeout(I),I=0),F>16*B&&(F=16*B),F>A&&(F=A),I=setTimeout(P,F),F=2*F+1,E.readyState=q,c=new e("error"),E.dispatchEvent(c),h(E,E.onerror,c))}function k(){j(!1)}function l(){j(!0)}b=String(b);var z=Boolean(m&&d&&d.withCredentials),B=g(d?d.retry:0/0,1e3),C=g(d?d.heartbeatTimeout:0/0,45e3),D=d&&d.lastEventId&&String(d.lastEventId)||"",E=this,F=B,G=!1,H=new o,I=0,J=0,K=0,L=p,M=[],N="",O="",P=null,Q=u,R="",S="";d=null,n&&(J=setTimeout(function T(){3===H.readyState&&k(),J=setTimeout(T,500)},0)),P=function(){if(I=0,L!==p)return void j(!1);if(n&&(void 0!==H.sendAsBinary||void 0===H.onloadend)&&a.document&&a.document.readyState&&"complete"!==a.document.readyState)return void(I=setTimeout(P,4));H.onload=H.onerror=l,n&&(H.onabort=l,H.onreadystatechange=k),H.onprogress=k,G=!1,I=setTimeout(P,C),K=0,L=q,M.length=0,O="",N=D,S="",R="",Q=u;var c=b.slice(0,5);c="data:"!==c&&"blob:"!==c?b+((-1===b.indexOf("?",0)?"?":"&")+"lastEventId="+encodeURIComponent(D)+"&r="+String(Math.random()+1).slice(2)):b,H.open("GET",c,!0),n&&(H.withCredentials=z,H.responseType="text",H.setRequestHeader("Accept","text/event-stream")),H.send(null)},c.call(this),this.close=i,this.url=b,this.readyState=q,this.withCredentials=z,this.onopen=null,this.onmessage=null,this.onerror=null,P()}function j(){this.CONNECTING=q,this.OPEN=r,this.CLOSED=s}b.prototype={get:function(a){return this.data[a+"~"]},set:function(a,b){this.data[a+"~"]=b},"delete":function(a){delete this.data[a+"~"]}},c.prototype={dispatchEvent:function(a){a.target=this;var b=String(a.type),c=this.listeners,e=c.get(b);if(e)for(var f=e.length,g=-1,h=null;++g=0;)if(d[e]===b)return;d.push(b)},removeEventListener:function(a,b){a=String(a);var c=this.listeners,d=c.get(a);if(d){for(var e=d.length,f=[],g=-1;++g>>0;if(0===c)return-1;var d=0;if(arguments.length>0&&(d=Number(arguments[1]),d!==d?d=0:0!==d&&1/0!==d&&d!==-1/0&&(d=(d>0||-1)*Math.floor(Math.abs(d)))),d>=c)return-1;for(var e=d>=0?d:Math.max(c-Math.abs(d),0);c>e;e++)if(e in b&&b[e]===a)return e;return-1}),Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var c,d;if(null===this)throw new TypeError(" this is null or not defined");var e=new Object(this),f=e.length>>>0;if("[object Function]"!=={}.toString.call(a))throw new TypeError(a+" is not a function");for(b&&(c=b),d=0;f>d;){var g;d in e&&(g=e[d],a.call(c,g,d,e)),d++}})}(),d._sliceUserAgent=function(a,b,c){var d=[],e=navigator.userAgent,f=e.indexOf(a),g=e.indexOf(b,f);0>g&&(g=e.length);for(var h=e.slice(f,g).split(c),i=h[1].split("."),j=0;j-1?d._sliceUserAgent("Chrome"," ","/"):a.indexOf("Safari")>-1?d._sliceUserAgent("Safari"," ","/"):a.indexOf("Firefox")>-1?d._sliceUserAgent("Firefox"," ","/"):a.indexOf("MSIE")>-1?d._sliceUserAgent("MSIE",";"," "):null},d.getServerUrl=function(b,c){if("file:"===a.location.protocol)return c?c:"ws://127.0.0.1/ws";var d="https:"===a.location.protocol?"wss://":"ws://",e=""!==a.location.port?":"+a.location.port:"",f=b?b:"ws";return d+a.location.hostname+e+"/"+f},d.browserNotSupportedMessage="Browser does not support WebSockets (RFC6455)",d.deriveKey=function(a,b){if(b&&b.salt){var c=b.salt,d=b.keylen||32,e=b.iterations||1e4,f=CryptoJS.PBKDF2(a,c,{keySize:d/4,iterations:e,hasher:CryptoJS.algo.SHA256});return f.toString(CryptoJS.enc.Base64)}return a},d._idchars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",d._idlen=16,d._subprotocol="wamp",d._newid=function(){for(var a="",b=0;b1){console.group("Log Item");for(var a=0;a=0){var e=a.substring(0,d);if(c._index[e])return c._index[e]+a.substring(d+1)}return b===!0?a:null},d.PrefixMap.prototype.shrink=function(a,b){for(var c=this,d=a.length;d>0;d-=1){var e=a.substring(0,d),f=c._rindex[e];if(f)return f+":"+a.substring(d)}return b===!0?a:null},d._MESSAGE_TYPEID_WELCOME=0,d._MESSAGE_TYPEID_PREFIX=1,d._MESSAGE_TYPEID_CALL=2,d._MESSAGE_TYPEID_CALL_RESULT=3,d._MESSAGE_TYPEID_CALL_ERROR=4,d._MESSAGE_TYPEID_SUBSCRIBE=5,d._MESSAGE_TYPEID_UNSUBSCRIBE=6,d._MESSAGE_TYPEID_PUBLISH=7,d._MESSAGE_TYPEID_EVENT=8,d.CONNECTION_CLOSED=0,d.CONNECTION_LOST=1,d.CONNECTION_RETRIES_EXCEEDED=2,d.CONNECTION_UNREACHABLE=3,d.CONNECTION_UNSUPPORTED=4,d.CONNECTION_UNREACHABLE_SCHEDULED_RECONNECT=5,d.CONNECTION_LOST_SCHEDULED_RECONNECT=6,d.Deferred=c.defer,d._construct=function(b,c){return"WebSocket"in a?c?new WebSocket(b,c):new WebSocket(b):"MozWebSocket"in a?c?new MozWebSocket(b,c):new MozWebSocket(b):null},d.Session=function(a,b,c,e){var f=this;if(f._wsuri=a,f._options=e,f._websocket_onopen=b,f._websocket_onclose=c,f._websocket=null,f._websocket_connected=!1,f._session_id=null,f._wamp_version=null,f._server=null,f._calls={},f._subscriptions={},f._prefixes=new d.PrefixMap,f._txcnt=0,f._rxcnt=0,f._websocket=f._options&&f._options.skipSubprotocolAnnounce?d._construct(f._wsuri):d._construct(f._wsuri,[d._subprotocol]),!f._websocket){if(void 0!==c)return void c(d.CONNECTION_UNSUPPORTED);throw d.browserNotSupportedMessage}f._websocket.onmessage=function(a){d._debugws&&(f._rxcnt+=1,console.group("WS Receive"),console.info(f._wsuri+" ["+f._session_id+"]"),console.log(f._rxcnt),console.log(a.data),console.groupEnd());var b=JSON.parse(a.data);if(b[1]in f._calls){if(b[0]===d._MESSAGE_TYPEID_CALL_RESULT){var c=f._calls[b[1]],e=b[2];if(d._debugrpc&&void 0!==c._ab_callobj){console.group("WAMP Call",c._ab_callobj[2]),console.timeEnd(c._ab_tid),console.group("Arguments");for(var g=3;g3){if(!(arguments[2]instanceof Array))throw"invalid argument type(s)";if(!(arguments[3]instanceof Array))throw"invalid argument type(s)";f=arguments[2],g=arguments[3],h=[d._MESSAGE_TYPEID_PUBLISH,b,c,f,g]}else if(arguments.length>2)if("boolean"==typeof arguments[2])e=arguments[2],h=[d._MESSAGE_TYPEID_PUBLISH,b,c,e];else{if(!(arguments[2]instanceof Array))throw"invalid argument type(s)";f=arguments[2],h=[d._MESSAGE_TYPEID_PUBLISH,b,c,f]}else h=[d._MESSAGE_TYPEID_PUBLISH,b,c];d._debugpubsub&&(console.group("WAMP Publish"),console.info(a._wsuri+" ["+a._session_id+"]"),console.log(b),console.log(c),null!==e?console.log(e):null!==f&&(console.log(f),null!==g&&console.log(g)),console.groupEnd()),a._send(h)},d.Session.prototype.authreq=function(a,b){return this.call("http://api.wamp.ws/procedure#authreq",a,b)},d.Session.prototype.authsign=function(a,b){return b||(b=""),CryptoJS.HmacSHA256(a,b).toString(CryptoJS.enc.Base64)},d.Session.prototype.auth=function(a){return this.call("http://api.wamp.ws/procedure#auth",a)},d._connect=function(b){var c=new d.Session(b.wsuri,function(){b.connects+=1,b.retryCount=0,b.onConnect(c)},function(c,e){var f=null;switch(c){case d.CONNECTION_CLOSED:b.onHangup(c,"Connection was closed properly ["+e+"]");break;case d.CONNECTION_UNSUPPORTED:b.onHangup(c,"Browser does not support WebSocket.");break;case d.CONNECTION_UNREACHABLE:b.retryCount+=1,0===b.connects?b.onHangup(c,"Connection could not be established."):b.retryCount<=b.options.maxRetries?(f=b.onHangup(d.CONNECTION_UNREACHABLE_SCHEDULED_RECONNECT,"Connection unreachable - scheduled reconnect to occur in "+b.options.retryDelay/1e3+" second(s) - attempt "+b.retryCount+" of "+b.options.maxRetries+".",{delay:b.options.retryDelay,retries:b.retryCount,maxretries:b.options.maxRetries}),f?(d._debugconnect&&console.log("Connection unreachable - retrying stopped by app"),b.onHangup(d.CONNECTION_RETRIES_EXCEEDED,"Number of connection retries exceeded.")):(d._debugconnect&&console.log("Connection unreachable - retrying ("+b.retryCount+") .."),a.setTimeout(function(){d._connect(b)},b.options.retryDelay))):b.onHangup(d.CONNECTION_RETRIES_EXCEEDED,"Number of connection retries exceeded.");break;case d.CONNECTION_LOST:b.retryCount+=1,b.retryCount<=b.options.maxRetries?(f=b.onHangup(d.CONNECTION_LOST_SCHEDULED_RECONNECT,"Connection lost - scheduled "+b.retryCount+"th reconnect to occur in "+b.options.retryDelay/1e3+" second(s).",{delay:b.options.retryDelay,retries:b.retryCount,maxretries:b.options.maxRetries}),f?(d._debugconnect&&console.log("Connection lost - retrying stopped by app"),b.onHangup(d.CONNECTION_RETRIES_EXCEEDED,"Connection lost.")):(d._debugconnect&&console.log("Connection lost - retrying ("+b.retryCount+") .."),a.setTimeout(function(){d._connect(b)},b.options.retryDelay))):b.onHangup(d.CONNECTION_RETRIES_EXCEEDED,"Connection lost.");break;default:throw"unhandled close code in ab._connect"}},b.options)},d.connect=function(a,b,c,e){var f={};if(f.wsuri=a,f.options=e?e:{},void 0===f.options.retryDelay&&(f.options.retryDelay=5e3),void 0===f.options.maxRetries&&(f.options.maxRetries=10),void 0===f.options.skipSubprotocolCheck&&(f.options.skipSubprotocolCheck=!1),void 0===f.options.skipSubprotocolAnnounce&&(f.options.skipSubprotocolAnnounce=!1),!b)throw"onConnect handler required!";f.onConnect=b,f.onHangup=c?c:function(a,b,c){d._debugconnect&&console.log(a,b,c)},f.connects=0,f.retryCount=0,d._connect(f)},d.launch=function(a,b,c){d.connect(a.wsuri,function(c){a.appkey&&""!==a.appkey?c.authreq(a.appkey,a.appextra).then(function(e){var f=null;if("function"==typeof a.appsecret)f=a.appsecret(e);else{var g=d.deriveKey(a.appsecret,JSON.parse(e).authextra);f=c.authsign(e,g)}c.auth(f).then(function(){b?b(c):d._debugconnect&&c.log("Session opened.")},c.log)},c.log):c.authreq().then(function(){c.auth().then(function(){b?b(c):d._debugconnect&&c.log("Session opened.")},c.log)},c.log)},function(a,b,e){c?c(a,b,e):d._debugconnect&&d.log("Session closed.",a,b,e)},a.sessionConfig)},d});var d={VERSION:"0.1.0",defaults:{perPage:50}};a.Hook=d,d.Client=function(b){b||(b={}),this.url=b.endpoint||b.url||a.location.origin,this.app_id=b.app_id||b.appId||"",this.key=b.key||"",this.url.lastIndexOf("/")!=this.url.length-1&&(this.url+="/"),this.keys=new d.KeyValues(this),this.auth=new d.Auth(this),this.system=new d.System(this),d.Plugin.Manager.setup(this)},d.Client.prototype.collection=function(a){return new d.Collection(this,a)},d.Client.prototype.channel=function(a,b){"undefined"==typeof b&&(b={});var c=this.collection(a);return c.segments=c.segments.replace("collection/","channels/"),b.transport||(b.transport="sse"),b.transport=b.transport.toUpperCase(),new d.Channel[b.transport](this,c,b)},d.Client.prototype.post=function(a,b){return"undefined"==typeof b&&(b={}),this.request(a,"POST",b)},d.Client.prototype.get=function(a,b){return this.request(a,"GET",b)},d.Client.prototype.put=function(a,b){return this.request(a,"PUT",b)},d.Client.prototype.remove=function(a,b){return this.request(a,"DELETE",b)},d.Client.prototype.request=function(a,b,c){var d,e,f=when.defer(),g=!1;if(c&&c._sync&&(delete c._sync,g=!0),d=this.getPayload(b,c),e=this.getHeaders(),d instanceof FormData||(e["Content-Type"]="application/json"),"undefined"!=typeof XDomainRequest){a+="?X-App-Id="+this.app_id+"&X-App-Key="+this.key+"&r="+Math.floor(1e3*Math.random());var h=this.auth.getToken();h&&(a+="&X-Auth-Token="+h)}var i=f.promise.xhr=uxhr(this.url+a,d,{method:b,headers:e,sync:g,success:function(a){var b,c=null,d=i.getAllResponseHeaders();try{c=JSON.parseWithDate(a)}catch(e){}c===!1||null===c||c.error?(c&&c.error&&console.error(c.error),f.resolver.reject(c)):(b=d.match(/x-total-count: ([^\n]+)/i),b&&(c.total=parseInt(b[1])),f.resolver.resolve(c))},error:function(a){var b=null;try{b=JSON.parseWithDate(a)}catch(c){}console.log("Error: ",b||"Invalid JSON response."),f.resolver.reject(b)}});return f.promise},d.Client.prototype.getHeaders=function(){var a,b={"X-App-Id":this.app_id,"X-App-Key":this.key},a=this.auth.getToken();return a&&(b["X-Auth-Token"]=a),b},d.Client.prototype.getPayload=function(a,b){var c=null;if(b){if(b instanceof FormData)c=b;else if("GET"!==a){var d,e,f,g=new FormData,h=!1;for(d in b)if(e=b[d],f=null,"undefined"!=typeof e&&null!==e&&("boolean"==typeof e||"number"==typeof e||"string"==typeof e?e=e.toString():e instanceof HTMLInputElement&&e.files&&e.files.length>0?(f=e.files[0].name,e=e.files[0],h=!0):e instanceof HTMLInputElement?e=e.value:e instanceof HTMLCanvasElement?(e=dataURLtoBlob(e.toDataURL()),h=!0,f="canvas.png"):"undefined"!=typeof Blob&&e instanceof Blob&&(h=!0,f="blob."+e.type.match(/\/(.*)/)[1]),!(e instanceof Array)))if("string"==typeof e)g.append(d,e);else try{g.append(d,e,f||"file")}catch(i){}h&&(c=g)}if(c=c||JSON.stringify(b,function(a,b){return this[a]instanceof Date?Math.round(this[a].getTime()/1e3):b}),"{}"==c)return null;"GET"===a&&"string"==typeof c&&(c=encodeURIComponent(c))}return c},d.Client.prototype.serialize=function(a,b){var c=[];for(var d in a)if(a.hasOwnProperty(d)){var e=b?b+"["+d+"]":d,f=a[d];c.push("object"==typeof f?this.serialize(f,e):encodeURIComponent(e)+"="+encodeURIComponent(f))}return c.join("&")},d.Events=function(){this._events={}},d.Events.prototype.on=function(a,b,c){this._events[a]||(this._events[a]=[]),this._events[a].push({callback:b,context:c||this})},d.Events.prototype.trigger=function(a){var b,c=Array.prototype.slice.call(arguments,1);if(this._events[a])for(var d=0,e=this._events[a].length;e>d;d++)b=this._events[a][d],b.callback.apply(b.context||this.client,c)},d.Iterable=function(){},d.Iterable.prototype={each:function(a){return this._iterate("each",a)},find:function(a){return this._iterate("find",a)},filter:function(a){return this._iterate("filter",a)},max:function(a){return this._iterate("max",a)},min:function(a){return this._iterate("min",a)},every:function(a){return this._iterate("every",a)},reject:function(a,b){return this._iterate("reject",a,b)},groupBy:function(a,b){return this._iterate("groupBy",a,b)},_iterate:function(a,b,c){var d=when.defer();return this.then(function(e){var f=_[a].call(_,e,b,c);d.resolver.resolve(f)}).otherwise(function(a){d.resolver.reject(a)}),d.promise}},"undefined"==typeof a.FormData&&(a.FormData=function(){this.append=function(){}}),a.location.origin||(a.location.origin=a.location.protocol+"//"+a.location.hostname+(a.location.port?":"+a.location.port:"")),d.Plugin={},d.Plugin.Manager={plugins:[]},d.Plugin.Manager.register=function(a,b){this.plugins.push({path:a,klass:b})},d.Plugin.Manager.setup=function(a){for(var b=0,c=this.plugins.length;c>b;b++)a[this.plugins[b].path]=new this.plugins[b].klass(a)},d.Auth=function(b){this.client=b,this.currentUser=null;var c=new Date,e=new Date(a.localStorage.getItem(this.client.app_id+"-"+d.Auth.AUTH_TOKEN_EXPIRATION)),f=a.localStorage.getItem(this.client.app_id+"-"+d.Auth.AUTH_DATA_KEY);f&&c.getTime()1?b.then.apply(b,Array.prototype.slice.call(arguments,1)):b},d.Collection.prototype.join=function(){return this.options["with"]=arguments,this},d.Collection.prototype.distinct=function(){return this.options.distinct=!0,this},d.Collection.prototype.group=function(){return this._group=arguments,this},d.Collection.prototype.count=function(a){a="undefined"==typeof a?"*":a,this.options.aggregation={method:"count",field:a};var b=this.get();return arguments.length>0&&b.then.apply(b,arguments),b},d.Collection.prototype.max=function(a){this.options.aggregation={method:"max",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.min=function(a){this.options.aggregation={method:"min",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.avg=function(a){this.options.aggregation={method:"avg",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.sum=function(a){this.options.aggregation={method:"sum",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.first=function(){this.options.first=1;var a=this.get();return a.then.apply(a,arguments),a},d.Collection.prototype.firstOrCreate=function(a){return this.options.first=1,this.options.data=a,this.client.post(this.segments,this.buildQuery())},d.Collection.prototype.then=function(){var a=this.get();return a.then.apply(a,arguments),a},d.Collection.prototype.debug=function(a){return a="undefined"==typeof a?"log":a,this.then(console[a].bind(console))},d.Collection.prototype.reset=function(){return this.options={},this.wheres=[],this.ordering=[],this._group=[],this._limit=null,this._offset=null,this._remember=null,this},d.Collection.prototype.sort=function(a,b){return b?"number"==typeof b&&(b=-1===parseInt(b,10)?"desc":"asc"):b="asc",this.ordering.push([a,b]),this},d.Collection.prototype.limit=function(a){return this._limit=a,this},d.Collection.prototype.offset=function(a){return this._offset=a,this},d.Collection.prototype.remember=function(a){return this._remember=a,this},d.Collection.prototype.channel=function(){throw new Error("Not implemented.")},d.Collection.prototype.paginate=function(a,b,c){var e=new d.Pagination(this);return b||(b=a,a=d.defaults.perPage),this.options.paginate=a,this.then(function(a){e._fetchComplete(a),b&&b(e)},c),e},d.Collection.prototype.drop=function(){return this.client.remove(this.segments)},d.Collection.prototype.remove=function(a){var b=this.segments;return"undefined"!=typeof a&&(b+="/"+a),this.client.remove(b,this.buildQuery())},d.Collection.prototype.update=function(a,b){return this.client.post(this.segments+"/"+a,b)},d.Collection.prototype.increment=function(a,b){this.options.operation={method:"increment",field:a,value:b||1};var c=this.client.put(this.segments,this.buildQuery());return arguments.length>0&&c.then.apply(c,arguments),c},d.Collection.prototype.decrement=function(a,b){this.options.operation={method:"decrement",field:a,value:b||1};var c=this.client.put(this.segments,this.buildQuery());return arguments.length>0&&c.then.apply(c,arguments),c},d.Collection.prototype.updateAll=function(a){return this.options.data=a,this.client.put(this.segments,this.buildQuery())},d.Collection.prototype.addWhere=function(a,b,c,d){return this.wheres.push([a,b.toLowerCase(),c,d]),this},d.Collection.prototype._validateName=function(a){var b=/^[a-z_\/0-9]+$/;if(!b.test(a))throw new Error("Invalid name: "+a);return a},d.Collection.prototype.buildQuery=function(){var a={};null!==this._limit&&(a.limit=this._limit),null!==this._offset&&(a.offset=this._offset),null!==this._remember&&(a.remember=this._remember),this.wheres.length>0&&(a.q=this.wheres),this.ordering.length>0&&(a.s=this.ordering),this._group.length>0&&(a.g=this._group);var b,c={paginate:"p",first:"f",aggregation:"aggr",operation:"op",data:"data","with":"with",select:"select",distinct:"distinct"};for(b in c)this.options[b]&&(a[c[b]]=this.options[b]);return this.reset(),a},d.CollectionItem=function(){},d.KeyValues=function(a){this.client=a},d.KeyValues.prototype.get=function(a,b){var c=this.client.get("key/"+a);return b&&c.then.apply(c,[b]),c},d.KeyValues.prototype.set=function(a,b){return this.client.post("key/"+a,{value:b})},d.Model=function(){},d.Pagination=function(a){this.fetching=!0,this.collection=a},d.Pagination.prototype._fetchComplete=function(a){this.fetching=!1,this.total=a.total,this.per_page=a.per_page,this.current_page=a.current_page,this.last_page=a.last_page,this.from=a.from,this.to=a.to,this.items=a.data},d.Pagination.prototype.hasNext=function(){return this.current_page0&&a.then.apply(a,arguments),a},d.Channel.SSE=function(a,b,c){this.collection=b,this.client_id=null,this.callbacks={},this.options=c||{},this.readyState=null},d.Channel.SSE.prototype.subscribe=function(a,b){"undefined"==typeof b&&(b=a,a="_default"),this.callbacks[a]=b;var c=this.connect();if(this.readyState===EventSource.CONNECTING){var d=this;c.then(function(){d.event_source.onopen=function(a){d.readyState=a.readyState,d._trigger.apply(d,["state:"+a.type,a])},d.event_source.onerror=function(a){d.readyState=a.readyState,d._trigger.apply(d,["state:"+a.type,a])},d.event_source.onmessage=function(a){var b=JSON.parse(a.data),c=b.event;delete b.event,d._trigger.apply(d,[c,b])}})}return c},d.Channel.SSE.prototype._trigger=function(a,b){console.log("Trigger: ",a,b),-1===a.indexOf("state:")&&this.callbacks._default&&this.callbacks._default.apply(this,[a,b]),this.callbacks[a]&&this.callbacks[a].apply(this,[b])},d.Channel.SSE.prototype.isConnected=function(){return null!==this.readyState&&this.readyState!==EventSource.CLOSED},d.Channel.SSE.prototype.unsubscribe=function(a){this.callbacks[a]&&(this.callbacks[a]=null)},d.Channel.SSE.prototype.publish=function(a,b){return"undefined"==typeof b&&(b={}),b.client_id=this.client_id,b.event=a,this.collection.create(b)},d.Channel.SSE.prototype.connect=function(){if(null!==this.readyState){var b=when.defer();return b.resolver.resolve(),b.promise}this.readyState=EventSource.CONNECTING,this._trigger.apply(this,["state:connecting"]);var c=this;return this.publish("connected").then(function(b){c.collection.where("updated_at",">",b.updated_at);var d="X-App-Id="+c.collection.client.appId+"&X-App-Key="+c.collection.client.key,e=c.collection.client.auth.getToken();e&&(d+="&X-Auth-Token="+e);var f=c.collection.buildQuery();f.stream={refresh:c.options.refresh_timeout||1,retry:c.options.retry_timeout||1},c.client_id=b.client_id,c.event_source=new EventSource(c.collection.client.url+c.collection.segments+"?"+d+"&"+JSON.stringify(f),{withCredentials:!0}),a.addEventListener("unload",function(){c.disconnect(!0)})},function(a){c.readyState=EventSource.CLOSED,c._trigger.apply(c,["state:error",a])})},d.Channel.SSE.prototype.disconnect=function(a){return this.isConnected()&&(this.close(),this.publish("disconnected",{_sync:"undefined"!=typeof a&&a})),this},d.Channel.SSE.prototype.close=function(){return this.event_source&&this.event_source.close(),this.readyState=EventSource.CLOSED,this},d.Channel.WEBSOCKETS=function(b,c,d){var e=this;if(this.client=b,this.collection=c,this.client_id=null,!d.url){var f="https:"===a.location.protocol?"wss://":"ws://",g=b.url.replace(/(?:https?:)?\/\//,f);g.match(/index\.php/)?g=g.replace("index.php","ws/"):g+="ws/",d.url=g}d.url+=this.collection.name+"?X-App-Id="+this.client.app_id+"&X-App-Key="+this.client.key;var h=this.client.auth.getToken();h&&(d.url+="&X-Auth-Token="+h),ab.debug(d.debug===!0,d.verbose===!0,d.debug===!0),this.queued_subscriptions={},this.on("connected",function(){for(var a in e.queued_subscriptions)e.queued_subscriptions.hasOwnProperty(a)&&e.subscribe(a,e.queued_subscriptions[a]);e.queued_subscriptions=null}),ab.connect(d.url,function(a){e.ws=a,e.client_id=a.sessionid(),e.trigger("connected")},function(a){console.error("Can't connect with WebSocket server: "+d.url,a)},{retryDelay:1e3,maxRetries:10})},d.Channel.WEBSOCKETS.prototype=new d.Events,d.Channel.WEBSOCKETS.prototype.constructor=d.Channel.WEBSOCKETS,d.Channel.WEBSOCKETS.prototype.subscribe=function(a,b){return this.ws?this.ws.subscribe(this.collection.name+"."+a,function(a,c){b(c)}):this.queued_subscriptions[a]=b,this},d.Channel.WEBSOCKETS.prototype.isConnected=function(){return this.ws&&this.ws._websocket_connected},d.Channel.WEBSOCKETS.prototype.unsubscribe=function(a){return this.ws&&this.ws._subscriptions[this.collection.name+"."+a]&&this.ws.unsubscribe(this.collection.name+"."+a),this},d.Channel.WEBSOCKETS.prototype.publish=function(a,b,c){var d=[],e=[];return"undefined"==typeof c&&(c={}),c.exclude&&c.exclude instanceof Array&&(d=c.exclude),c.eligible&&c.eligible instanceof Array&&(e=c.eligible),this.ws.publish(this.collection.name+"."+a,b,d,e),this},d.Channel.WEBSOCKETS.prototype.disconnect=function(){return this.ws.close(),this},d.Channel.WEBSOCKETS.prototype.call=function(a,b){return this.ws.call(a,b),this},d.Channel.WEBSOCKETS.prototype.connect=function(){return this.ws.connect(),this}}(this); \ No newline at end of file +},d.Collection.prototype.select=function(){return this.options.select=arguments,this},d.Collection.prototype.get=function(){return this.client.get(this.segments,this.buildQuery())},d.Collection.prototype.where=function(a,b,c,d){var e,f="undefined"==typeof c?"=":b,g="undefined"==typeof c?b:c,h="undefined"==typeof d?"and":d;if("object"==typeof a)for(e in a)a.hasOwnProperty(e)&&(f="=",a[e]instanceof Array?(f=a[e][0],g=a[e][1]):g=a[e],this.addWhere(e,f,g,h));else this.addWhere(a,f,g,h);return this},d.Collection.prototype.orWhere=function(a,b,c){return this.where(a,b,c,"or")},d.Collection.prototype.find=function(a){var b=this.client.get(this.segments+"/"+a,this.buildQuery());return arguments.length>1?b.then.apply(b,Array.prototype.slice.call(arguments,1)):b},d.Collection.prototype.join=function(){return this.options["with"]=arguments,this},d.Collection.prototype.distinct=function(){return this.options.distinct=!0,this},d.Collection.prototype.group=function(){return this._group=arguments,this},d.Collection.prototype.count=function(a){a="undefined"==typeof a?"*":a,this.options.aggregation={method:"count",field:a};var b=this.get();return arguments.length>0&&b.then.apply(b,arguments),b},d.Collection.prototype.max=function(a){this.options.aggregation={method:"max",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.min=function(a){this.options.aggregation={method:"min",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.avg=function(a){this.options.aggregation={method:"avg",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.sum=function(a){this.options.aggregation={method:"sum",field:a};var b=this.get();return arguments.length>1&&b.then.apply(b,Array.prototype.slice.call(arguments,1)),b},d.Collection.prototype.first=function(){this.options.first=1;var a=this.get();return a.then.apply(a,arguments),a},d.Collection.prototype.firstOrCreate=function(a){return this.options.first=1,this.options.data=a,this.client.post(this.segments,this.buildQuery())},d.Collection.prototype.then=function(){var a=this.get();return a.then.apply(a,arguments),a},d.Collection.prototype.debug=function(a){return a="undefined"==typeof a?"log":a,this.then(console[a].bind(console))},d.Collection.prototype.reset=function(){return this.options={},this.wheres=[],this.ordering=[],this._group=[],this._limit=null,this._offset=null,this._remember=null,this},d.Collection.prototype.sort=function(a,b){return b?"number"==typeof b&&(b=-1===parseInt(b,10)?"desc":"asc"):b="asc",this.ordering.push([a,b]),this},d.Collection.prototype.limit=function(a){return this._limit=a,this},d.Collection.prototype.offset=function(a){return this._offset=a,this},d.Collection.prototype.remember=function(a){return this._remember=a,this},d.Collection.prototype.channel=function(){throw new Error("Not implemented.")},d.Collection.prototype.paginate=function(a,b,c){var e=new d.Pagination(this);return b||(b=a,a=d.defaults.perPage),this.options.paginate=a,this.then(function(a){e._fetchComplete(a),b&&b(e)},c),e},d.Collection.prototype.drop=function(){return this.client.remove(this.segments)},d.Collection.prototype.remove=function(a){var b=this.segments;return"undefined"!=typeof a&&(b+="/"+a),this.client.remove(b,this.buildQuery())},d.Collection.prototype.update=function(a,b){return this.client.post(this.segments+"/"+a,b)},d.Collection.prototype.increment=function(a,b){this.options.operation={method:"increment",field:a,value:b||1};var c=this.client.put(this.segments,this.buildQuery());return arguments.length>0&&c.then.apply(c,arguments),c},d.Collection.prototype.decrement=function(a,b){this.options.operation={method:"decrement",field:a,value:b||1};var c=this.client.put(this.segments,this.buildQuery());return arguments.length>0&&c.then.apply(c,arguments),c},d.Collection.prototype.updateAll=function(a){return this.options.data=a,this.client.put(this.segments,this.buildQuery())},d.Collection.prototype.addWhere=function(a,b,c,d){return this.wheres.push([a,b.toLowerCase(),c,d]),this},d.Collection.prototype._validateName=function(a){var b=/^[a-z_\/0-9]+$/;if(!b.test(a))throw new Error("Invalid name: "+a);return a},d.Collection.prototype.buildQuery=function(){var a={};null!==this._limit&&(a.limit=this._limit),null!==this._offset&&(a.offset=this._offset),null!==this._remember&&(a.remember=this._remember),this.wheres.length>0&&(a.q=this.wheres),this.ordering.length>0&&(a.s=this.ordering),this._group.length>0&&(a.g=this._group);var b,c={paginate:"p",first:"f",aggregation:"aggr",operation:"op",data:"data","with":"with",select:"select",distinct:"distinct"};for(b in c)this.options[b]&&(a[c[b]]=this.options[b]);return this.reset(),a},d.Collection.prototype.clone=function(){var a=this.client.collection(this.name);return a.options=_.clone(this.options),a.wheres=_.clone(this.wheres),a.ordering=_.clone(this.ordering),a._group=_.clone(this._group),a._limit=_.clone(this._limit),a._offset=_.clone(this._offset),a._remember=_.clone(this._remember),a},d.CollectionItem=function(){},d.KeyValues=function(a){this.client=a},d.KeyValues.prototype.get=function(a,b){var c=this.client.get("key/"+a);return b&&c.then.apply(c,[b]),c},d.KeyValues.prototype.set=function(a,b){return this.client.post("key/"+a,{value:b})},d.Model=function(){},d.Pagination=function(a){this.fetching=!0,this.collection=a},d.Pagination.prototype._fetchComplete=function(a){this.fetching=!1,this.total=a.total,this.per_page=a.per_page,this.current_page=a.current_page,this.last_page=a.last_page,this.from=a.from,this.to=a.to,this.items=a.data},d.Pagination.prototype.hasNext=function(){return this.current_page0&&a.then.apply(a,arguments),a},d.Channel.SSE=function(a,b,c){this.collection=b,this.client_id=null,this.callbacks={},this.options=c||{},this.readyState=null},d.Channel.SSE.prototype.subscribe=function(a,b){"undefined"==typeof b&&(b=a,a="_default"),this.callbacks[a]=b;var c=this.connect();if(this.readyState===EventSource.CONNECTING){var d=this;c.then(function(){d.event_source.onopen=function(a){d.readyState=a.readyState,d._trigger.apply(d,["state:"+a.type,a])},d.event_source.onerror=function(a){d.readyState=a.readyState,d._trigger.apply(d,["state:"+a.type,a])},d.event_source.onmessage=function(a){var b=JSON.parse(a.data),c=b.event;delete b.event,d._trigger.apply(d,[c,b])}})}return c},d.Channel.SSE.prototype._trigger=function(a,b){console.log("Trigger: ",a,b),-1===a.indexOf("state:")&&this.callbacks._default&&this.callbacks._default.apply(this,[a,b]),this.callbacks[a]&&this.callbacks[a].apply(this,[b])},d.Channel.SSE.prototype.isConnected=function(){return null!==this.readyState&&this.readyState!==EventSource.CLOSED},d.Channel.SSE.prototype.unsubscribe=function(a){this.callbacks[a]&&(this.callbacks[a]=null)},d.Channel.SSE.prototype.publish=function(a,b){return"undefined"==typeof b&&(b={}),b.client_id=this.client_id,b.event=a,this.collection.create(b)},d.Channel.SSE.prototype.connect=function(){if(null!==this.readyState){var b=when.defer();return b.resolver.resolve(),b.promise}this.readyState=EventSource.CONNECTING,this._trigger.apply(this,["state:connecting"]);var c=this;return this.publish("connected").then(function(b){c.collection.where("updated_at",">",b.updated_at);var d="X-App-Id="+c.collection.client.appId+"&X-App-Key="+c.collection.client.key,e=c.collection.client.auth.getToken();e&&(d+="&X-Auth-Token="+e);var f=c.collection.buildQuery();f.stream={refresh:c.options.refresh_timeout||1,retry:c.options.retry_timeout||1},c.client_id=b.client_id,c.event_source=new EventSource(c.collection.client.url+c.collection.segments+"?"+d+"&"+JSON.stringify(f),{withCredentials:!0}),a.addEventListener("unload",function(){c.disconnect(!0)})},function(a){c.readyState=EventSource.CLOSED,c._trigger.apply(c,["state:error",a])})},d.Channel.SSE.prototype.disconnect=function(a){return this.isConnected()&&(this.close(),this.publish("disconnected",{_sync:"undefined"!=typeof a&&a})),this},d.Channel.SSE.prototype.close=function(){return this.event_source&&this.event_source.close(),this.readyState=EventSource.CLOSED,this},d.Channel.WEBSOCKETS=function(b,c,d){var e=this;if(this.client=b,this.collection=c,this.client_id=null,!d.url){var f="https:"===a.location.protocol?"wss://":"ws://",g=b.url.replace(/(?:https?:)?\/\//,f);g.match(/index\.php/)?g=g.replace("index.php","ws/"):g+="ws/",d.url=g}d.url+=this.collection.name+"?X-App-Id="+this.client.app_id+"&X-App-Key="+this.client.key;var h=this.client.auth.getToken();h&&(d.url+="&X-Auth-Token="+h),ab.debug(d.debug===!0,d.verbose===!0,d.debug===!0),this.queued_subscriptions={},this.on("connected",function(){for(var a in e.queued_subscriptions)e.queued_subscriptions.hasOwnProperty(a)&&e.subscribe(a,e.queued_subscriptions[a]);e.queued_subscriptions=null}),ab.connect(d.url,function(a){e.ws=a,e.client_id=a.sessionid(),e.trigger("connected")},function(a){console.error("Can't connect with WebSocket server: "+d.url,a)},{retryDelay:1e3,maxRetries:10})},d.Channel.WEBSOCKETS.prototype=new d.Events,d.Channel.WEBSOCKETS.prototype.constructor=d.Channel.WEBSOCKETS,d.Channel.WEBSOCKETS.prototype.subscribe=function(a,b){return this.ws?this.ws.subscribe(this.collection.name+"."+a,function(a,c){b(c)}):this.queued_subscriptions[a]=b,this},d.Channel.WEBSOCKETS.prototype.isConnected=function(){return this.ws&&this.ws._websocket_connected},d.Channel.WEBSOCKETS.prototype.unsubscribe=function(a){return this.ws&&this.ws._subscriptions[this.collection.name+"."+a]&&this.ws.unsubscribe(this.collection.name+"."+a),this},d.Channel.WEBSOCKETS.prototype.publish=function(a,b,c){var d=[],e=[];return"undefined"==typeof c&&(c={}),c.exclude&&c.exclude instanceof Array&&(d=c.exclude),c.eligible&&c.eligible instanceof Array&&(e=c.eligible),this.ws.publish(this.collection.name+"."+a,b,d,e),this},d.Channel.WEBSOCKETS.prototype.disconnect=function(){return this.ws.close(),this},d.Channel.WEBSOCKETS.prototype.call=function(a,b){return this.ws.call(a,b),this},d.Channel.WEBSOCKETS.prototype.connect=function(){return this.ws.connect(),this}}(this); \ No newline at end of file diff --git a/src/collection.js b/src/collection.js index 6e6fad4..f5c21a8 100644 --- a/src/collection.js +++ b/src/collection.js @@ -727,3 +727,23 @@ Hook.Collection.prototype.buildQuery = function() { return query; }; + +/** + * Return a new copy of the collection. + * @method clone + * @return {Collection} + */ +Hook.Collection.prototype.clone = function() { + var clone = this.client.collection(this.name); + + // copy attributes to the new instance + clone.options = _.clone(this.options); + clone.wheres = _.clone(this.wheres); + clone.ordering = _.clone(this.ordering); + clone._group = _.clone(this._group); + clone._limit = _.clone(this._limit); + clone._offset = _.clone(this._offset); + clone._remember = _.clone(this._remember); + + return clone; +};