diff --git a/dist/av-min.js b/dist/av-min.js new file mode 100644 index 000000000..0eaee1048 --- /dev/null +++ b/dist/av-min.js @@ -0,0 +1,6 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AV=t():e.AV=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=30)}([function(e,t,n){var r,i;(function(){function n(e){function t(t,n,r,i,s,o){for(;s>=0&&s0?0:a-1;return arguments.length<3&&(i=n[o?o[u]:u],u+=e),t(n,r,i,o,u,a)}}function s(e){return function(t,n,r){n=S(n,r);for(var i=C(t),s=e>0?0:i-1;s>=0&&s0?o=s>=0?s:Math.max(s+a,o):a=s>=0?Math.min(s+1,a):s+a+1;else if(n&&s&&a)return s=n(r,i),r[s]===i?s:-1;if(i!==i)return s=t(p.call(r,o,a),O.isNaN),s>=0?s+o:-1;for(s=e>0?o:a-1;s>=0&&s=0&&t<=j};O.each=O.forEach=function(e,t,n){t=A(t,n);var r,i;if(x(e))for(r=0,i=e.length;r=0},O.invoke=function(e,t){var n=p.call(arguments,2),r=O.isFunction(t);return O.map(e,function(e){var i=r?t:e[t];return null==i?i:i.apply(e,n)})},O.pluck=function(e,t){return O.map(e,O.property(t))},O.where=function(e,t){return O.filter(e,O.matcher(t))},O.findWhere=function(e,t){return O.find(e,O.matcher(t))},O.max=function(e,t,n){var r,i,s=-(1/0),o=-(1/0);if(null==t&&null!=e){e=x(e)?e:O.values(e);for(var a=0,u=e.length;as&&(s=r)}else t=S(t,n),O.each(e,function(e,n,r){i=t(e,n,r),(i>o||i===-(1/0)&&s===-(1/0))&&(s=e,o=i)});return s},O.min=function(e,t,n){var r,i,s=1/0,o=1/0;if(null==t&&null!=e){e=x(e)?e:O.values(e);for(var a=0,u=e.length;ar||void 0===n)return 1;if(nt?(o&&(clearTimeout(o),o=null),a=c,s=e.apply(r,i),o||(r=i=null)):o||n.trailing===!1||(o=setTimeout(u,l)),s}},O.debounce=function(e,t,n){var r,i,s,o,a,u=function(){var c=O.now()-o;c=0?r=setTimeout(u,t-c):(r=null,n||(a=e.apply(s,i),r||(s=i=null)))};return function(){s=this,i=arguments,o=O.now();var c=n&&!r;return r||(r=setTimeout(u,t)),c&&(a=e.apply(s,i),s=i=null),a}},O.wrap=function(e,t){return O.partial(t,e)},O.negate=function(e){return function(){return!e.apply(this,arguments)}},O.compose=function(){var e=arguments,t=e.length-1;return function(){for(var n=t,r=e[t].apply(this,arguments);n--;)r=e[n].call(this,r);return r}},O.after=function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},O.before=function(e,t){var n;return function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=null),n}},O.once=O.partial(O.before,2);var P=!{toString:null}.propertyIsEnumerable("toString"),R=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];O.keys=function(e){if(!O.isObject(e))return[];if(y)return y(e);var t=[];for(var n in e)O.has(e,n)&&t.push(n);return P&&a(e,t),t},O.allKeys=function(e){if(!O.isObject(e))return[];var t=[];for(var n in e)t.push(n);return P&&a(e,t),t},O.values=function(e){for(var t=O.keys(e),n=t.length,r=Array(n),i=0;i":">",'"':""","'":"'","`":"`"},q=O.invert(L),M=function(e){var t=function(t){return e[t]},n="(?:"+O.keys(e).join("|")+")",r=RegExp(n),i=RegExp(n,"g");return function(e){return e=null==e?"":""+e,r.test(e)?e.replace(i,t):e}};O.escape=M(L),O.unescape=M(q),O.result=function(e,t,n){var r=null==e?void 0:e[t];return void 0===r&&(r=n),O.isFunction(r)?r.call(e):r};var F=0;O.uniqueId=function(e){var t=++F+"";return e?e+t:t},O.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var J=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},Q=/\\|'|\r|\n|\u2028|\u2029/g,V=function(e){return"\\"+B[e]};O.template=function(e,t,n){!t&&n&&(t=n),t=O.defaults({},t,O.templateSettings);var r=RegExp([(t.escape||J).source,(t.interpolate||J).source,(t.evaluate||J).source].join("|")+"|$","g"),i=0,s="__p+='";e.replace(r,function(t,n,r,o,a){return s+=e.slice(i,a).replace(Q,V),i=a+t.length,n?s+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":r?s+="'+\n((__t=("+r+"))==null?'':__t)+\n'":o&&(s+="';\n"+o+"\n__p+='"),t}),s+="';\n",t.variable||(s="with(obj||{}){\n"+s+"}\n"),s="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+s+"return __p;\n";try{var o=new Function(t.variable||"obj","_",s)}catch(e){throw e.source=s,e}var a=function(e){return o.call(this,e,O)},u=t.variable||"obj";return a.source="function("+u+"){\n"+s+"}",a},O.chain=function(e){var t=O(e);return t._chain=!0,t};var W=function(e,t){return e._chain?O(t).chain():t};O.mixin=function(e){O.each(O.functions(e),function(t){var n=O[t]=e[t];O.prototype[t]=function(){var e=[this._wrapped];return d.apply(e,arguments),W(this,n.apply(O,e))}})},O.mixin(O),O.each(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=l[e];O.prototype[e]=function(){var n=this._wrapped;return t.apply(n,arguments),"shift"!==e&&"splice"!==e||0!==n.length||delete n[0],W(this,n)}}),O.each(["concat","join","slice"],function(e){var t=l[e];O.prototype[e]=function(){return W(this,t.apply(this._wrapped,arguments))}}),O.prototype.value=function(){return this._wrapped},O.prototype.valueOf=O.prototype.toJSON=O.prototype.value,O.prototype.toString=function(){return""+this._wrapped},r=[],i=function(){return O}.apply(t,r),!(void 0!==i&&(e.exports=i))}).call(this)},function(e,t,n){"use strict";var r=(n(0),n(41).Promise);r._continueWhile=function(e,t){return e()?t().then(function(){return r._continueWhile(e,t)}):r.resolve()},e.exports=r},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=n(7),s=n(5)("leancloud:request"),o=n(44),a=n(1),u=n(10),c=n(3),l=n(6),h=n(0),f=n(4),d=f.getSessionToken,p=void 0,_={cn:"https://api.leancloud.cn",us:"https://us-api.leancloud.cn"},v=function(e,t){var n=(new Date).getTime(),r=o(n+e);return t?r+","+n+",master":r+","+n},m=0,y=function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=arguments[4],u=m++;return s("request("+u+")",e,t,n,r),new a(function(a,c){var l=i(e,t).set(r).send(n);o&&l.on("progress",o),l.end(function(e,t){return t&&s("response("+u+")",t.status,t.body||t.text,t.header),e?(t&&(e.statusCode=t.status,e.responseText=t.text,e.response=t.body),c(e)):a(t.body)})})},g=function(e,t){t?e["X-LC-Sign"]=v(l.applicationKey):e["X-LC-Key"]=l.applicationKey},b=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],n={"X-LC-Id":l.applicationId,"Content-Type":"application/json;charset=UTF-8"},r=!1;return"boolean"==typeof e.useMasterKey?r=e.useMasterKey:"boolean"==typeof l._useMasterKey&&(r=l._useMasterKey),r?l.masterKey?t?n["X-LC-Sign"]=v(l.masterKey,!0):n["X-LC-Key"]=l.masterKey+",master":(console.warn("masterKey is not set, fall back to use appKey"),g(n,t)):g(n,t),l.hookKey&&(n["X-LC-Hook-Key"]=l.hookKey),null!==l._config.applicationProduction&&(n["X-LC-Prod"]=String(l._config.applicationProduction)),n["X-LC-UA"]=l._config.userAgent,a.resolve().then(function(){var t=d(e);if(t)n["X-LC-Session"]=t;else if(!l._config.disableCurrentUser)return l.User.currentAsync().then(function(e){return e&&e._sessionToken&&(n["X-LC-Session"]=e._sessionToken),n});return n})},w=function(e,t,n,i,s){l.serverURL&&(l._config.APIServerURL=l.serverURL,console.warn("Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface."));var o=l._config.APIServerURL||_.cn;if("/"!==o.charAt(o.length-1)&&(o+="/"),o+="1.1/"+e,t&&(o+="/"+t),n&&(o+="/"+n),"users"!==e&&"classes"!==e||!s||(o+="?",s._fetchWhenSave&&(delete s._fetchWhenSave,o+="&new=true"),s._where&&(o+="&where="+encodeURIComponent(JSON.stringify(s._where)),delete s._where)),"get"===i.toLowerCase()){o.indexOf("?")===-1&&(o+="?");for(var a in s)"object"===r(s[a])&&(s[a]=JSON.stringify(s[a])),o+="&"+a+"="+encodeURIComponent(s[a])}return o},O=function(e,t){return"number"!=typeof t&&(t=3600),u.setAsync("APIServerURL",e,1e3*t)},A=function(e){return new a(function(t,n){if(410===e.statusCode)O(e.response.api_server,e.response.ttl).then(function(){t(e.response.location)}).catch(n);else{var r={code:e.code||-1,error:e.message||e.responseText};if(e.response&&e.response.code)r=e.response;else if(e.responseText)try{r=JSON.parse(e.responseText)}catch(e){}n(new c(r.code,r.error))}})},S=function(e){l._config.APIServerURL="https://"+e;var t=h.findKey(_,function(e){return e===l._config.APIServerURL});t&&(l._config.region=t)},E=function(){var e="https://app-router.leancloud.cn/1/route?appId="+l.applicationId;return y("get",e).then(function(e){if(e.api_server)return S(e.api_server),O(e.api_server,e.ttl)},function(e){if(e.statusCode>=400&&e.statusCode<500)throw e})},T=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"cn";p=new a(function(t,n){return l._config.APIServerURL?void t():"cn"===e?u.getAsync("APIServerURL").then(function(e){return e?void S(e):E()}).then(function(){t()}).catch(function(e){n(e)}):(l._config.region=e,l._config.APIServerURL=_[e],t(),void 0)})},N=function(e,t,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},s=arguments[5];if(!l.applicationId)throw new Error("You must specify your applicationId using AV.init()");if(!l.applicationKey&&!l.masterKey)throw new Error("You must specify a AppKey using AV.init()");return p?p.then(function(){var o=w(e,t,n,r,i);return b(s,"bigquery"!==e).then(function(e){return y(r,o,i,e).then(null,function(t){return A(t).then(function(t){return y(r,t,i,e)})})})}):a.reject(new Error("Not initialized"))};e.exports={ajax:y,request:N,setServerUrlByRegion:T}},function(e,t,n){"use strict";function r(e,t){var n=new Error(t);return n.code=e,n}var i=n(0);i.extend(r,{OTHER_CAUSE:-1,INTERNAL_SERVER_ERROR:1,CONNECTION_FAILED:100,OBJECT_NOT_FOUND:101,INVALID_QUERY:102,INVALID_CLASS_NAME:103,MISSING_OBJECT_ID:104,INVALID_KEY_NAME:105,INVALID_POINTER:106,INVALID_JSON:107,COMMAND_UNAVAILABLE:108,NOT_INITIALIZED:109,INCORRECT_TYPE:111,INVALID_CHANNEL_NAME:112,PUSH_MISCONFIGURED:115,OBJECT_TOO_LARGE:116,OPERATION_FORBIDDEN:119,CACHE_MISS:120,INVALID_NESTED_KEY:121,INVALID_FILE_NAME:122,INVALID_ACL:123,TIMEOUT:124,INVALID_EMAIL_ADDRESS:125,MISSING_CONTENT_TYPE:126,MISSING_CONTENT_LENGTH:127,INVALID_CONTENT_LENGTH:128,FILE_TOO_LARGE:129,FILE_SAVE_ERROR:130,FILE_DELETE_ERROR:153,DUPLICATE_VALUE:137,INVALID_ROLE_NAME:139,EXCEEDED_QUOTA:140,SCRIPT_FAILED:141,VALIDATION_ERROR:142,INVALID_IMAGE_DATA:150,UNSAVED_FILE_ERROR:151,INVALID_PUSH_TIME_ERROR:152,USERNAME_MISSING:200,PASSWORD_MISSING:201,USERNAME_TAKEN:202,EMAIL_TAKEN:203,EMAIL_MISSING:204,EMAIL_NOT_FOUND:205,SESSION_MISSING:206,MUST_CREATE_USER_THROUGH_SIGNUP:207,ACCOUNT_ALREADY_LINKED:208,LINKED_ID_MISSING:250,INVALID_LINKED_SESSION:251,UNSUPPORTED_SERVICE:252,X_DOMAIN_REQUEST:602}),e.exports=r},function(e,t,n){"use strict";var r=n(0),i=function(e){return r.isNull(e)||r.isUndefined(e)},s=function(e){return r.isArray(e)?e:void 0===e||null===e?[]:[e]},o=function(e){return e.sessionToken?e.sessionToken:e.user&&"function"==typeof e.user.getSessionToken?e.user.getSessionToken():void 0},a=function(e){return function(t){return e(t),t}};e.exports={isNullOrUndefined:i,ensureArray:s,getSessionToken:o,tap:a}},function(e,t,n){function r(){return!("undefined"==typeof window||!window||"undefined"==typeof window.process||"renderer"!==window.process.type)||("undefined"!=typeof document&&document&&"WebkitAppearance"in document.documentElement.style||"undefined"!=typeof window&&window&&window.console&&(console.firebug||console.exception&&console.table)||"undefined"!=typeof navigator&&navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function i(e){var n=this.useColors;if(e[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+e[0]+(n?"%c ":" ")+"+"+t.humanize(this.diff),n){var r="color: "+this.color;e.splice(1,0,r,"color: inherit");var i=0,s=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(s=i))}),e.splice(s,0,r)}}function s(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function o(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}}function a(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}function u(){try{return window.localStorage}catch(e){}}t=e.exports=n(40),t.log=s,t.formatArgs=i,t.save=o,t.load=a,t.useColors=r,t.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(a())},function(e,t,n){"use strict";(function(t){var r=n(0),i=n(32),s=n(4),o=s.isNullOrUndefined,a=t.AV||{};a._config=a._config||{};var u=a._config;r.extend(u,{region:"cn",APIServerURL:u.APIServerURL||"",disableCurrentUser:!1,userAgent:i,applicationProduction:null});var c=function(){},l=function(e,t,n){var i;return i=t&&t.hasOwnProperty("constructor")?t.constructor:function(){e.apply(this,arguments)},r.extend(i,e),c.prototype=e.prototype,i.prototype=new c,t&&r.extend(i.prototype,t),n&&r.extend(i,n),i.prototype.constructor=i,i.__super__=e.prototype,i};a.setProduction=function(e){o(e)?u.applicationProduction=null:u.applicationProduction=e?1:0},a._getAVPath=function(e){if(!a.applicationId)throw new Error("You need to call AV.initialize before using AV.");if(e||(e=""),!r.isString(e))throw new Error("Tried to get a localStorage path that wasn't a String.");return"/"===e[0]&&(e=e.substring(1)),"AV/"+a.applicationId+"/"+e},a._installationId=null,a._getInstallationId=function(){if(a._installationId)return a.Promise.resolve(a._installationId);var e=a._getAVPath("installationId");return a.localStorage.getItemAsync(e).then(function(t){if(a._installationId=t,a._installationId)return t;var n=function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)};return a._installationId=n()+n()+"-"+n()+"-"+n()+"-"+n()+"-"+n()+n()+n(),a.localStorage.setItemAsync(e,a._installationId)})},a._parseDate=function(e){var t=new RegExp("^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})T([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(.([0-9]+))?Z$"),n=t.exec(e);if(!n)return null;var r=n[1]||0,i=(n[2]||1)-1,s=n[3]||0,o=n[4]||0,a=n[5]||0,u=n[6]||0,c=n[8]||0;return new Date(Date.UTC(r,i,s,o,a,u,c))},a._extend=function(e,t){var n=l(this,e,t);return n.extend=this.extend,n},a._getValue=function(e,t){return e&&e[t]?r.isFunction(e[t])?e[t]():e[t]:null},a._encode=function(e,t,n){if(e instanceof a.Object){if(n)throw new Error("AV.Objects not allowed here");if(!t||r.include(t,e)||!e._hasData)return e._toPointer();if(!e.dirty())return t=t.concat(e),a._encode(e._toFullJSON(t),t,n);throw new Error("Tried to save an object with a pointer to a new, unsaved object.")}if(e instanceof a.ACL)return e.toJSON();if(r.isDate(e))return{__type:"Date",iso:e.toJSON()};if(e instanceof a.GeoPoint)return e.toJSON();if(r.isArray(e))return r.map(e,function(e){return a._encode(e,t,n)});if(r.isRegExp(e))return e.source;if(e instanceof a.Relation)return e.toJSON();if(e instanceof a.Op)return e.toJSON();if(e instanceof a.File){if(!e.url()&&!e.id)throw new Error("Tried to save an object containing an unsaved file.");return e._toFullJSON()}return r.isObject(e)?r.mapObject(e,function(e,r){return a._encode(e,t,n)}):e},a._decode=function(e,t){if(!r.isObject(e)||r.isDate(e))return e;if(r.isArray(e))return r.map(e,function(e){return a._decode(e)});if(e instanceof a.Object)return e;if(e instanceof a.File)return e;if(e instanceof a.Op)return e;if(e instanceof a.GeoPoint)return e;if(e instanceof a.ACL)return e;if("ACL"===t)return new a.ACL(e);if(e.__op)return a.Op._decode(e);var n;if("Pointer"===e.__type){n=e.className;var i=a.Object._create(n,void 0,void 0,!0);if(Object.keys(e).length>3){var s=r.clone(e);delete s.__type,delete s.className,i._finishFetch(s,!0)}else i._finishFetch({objectId:e.objectId},!1);return i}if("Object"===e.__type){n=e.className;var o=r.clone(e);delete o.__type,delete o.className;var u=a.Object._create(n,void 0,void 0,!0);return u._finishFetch(o,!0),u}if("Date"===e.__type)return a._parseDate(e.iso);if("GeoPoint"===e.__type)return new a.GeoPoint({latitude:e.latitude,longitude:e.longitude});if("Relation"===e.__type){if(!t)throw new Error("key missing decoding a Relation");var c=new a.Relation(null,t);return c.targetClassName=e.className,c}if("File"===e.__type){var l=new a.File(e.name),h=r.clone(e);return delete h.__type,l._finishFetch(h),l}return r.mapObject(e,a._decode)},a._encodeObjectOrArray=function(e){var t=function(e){return e&&e._toFullJSON&&(e=e._toFullJSON([])),r.mapObject(e,function(e){return a._encode(e,[])})};return r.isArray(e)?e.map(function(e){return t(e)}):t(e)},a._arrayEach=r.each,a._traverse=function(e,t,n){if(e instanceof a.Object){if(n=n||[],r.indexOf(n,e)>=0)return;return n.push(e),a._traverse(e.attributes,t,n),t(e)}return e instanceof a.Relation||e instanceof a.File?t(e):r.isArray(e)?(r.each(e,function(r,i){var s=a._traverse(r,t,n);s&&(e[i]=s)}),t(e)):r.isObject(e)?(a._each(e,function(r,i){var s=a._traverse(r,t,n);s&&(e[i]=s)}),t(e)):t(e)},a._objectEach=a._each=function(e,t){r.isObject(e)?r.each(r.keys(e),function(n){t(e[n],n)}):r.each(e,t)},e.exports=a}).call(t,n(9))},function(e,t,n){function r(){}function i(e){if(!_(e))return e;var t=[];for(var n in e)s(t,n,e[n]);return t.join("&")}function s(e,t,n){if(null!=n)if(Array.isArray(n))n.forEach(function(n){s(e,t,n)});else if(_(n))for(var r in n)s(e,t+"["+r+"]",n[r]);else e.push(encodeURIComponent(t)+"="+encodeURIComponent(n));else null===n&&e.push(encodeURIComponent(t))}function o(e){for(var t,n,r={},i=e.split("&"),s=0,o=i.length;s=0?"&":"?")+e),this._sort){var t=this.url.indexOf("?");if(t>=0){var n=this.url.substring(t+1).split("&");v(this._sort)?n.sort(this._sort):n.sort(),this.url=this.url.substring(0,t)+"?"+n.join("&")}}},l.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},l.prototype.end=function(e){return this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=e||r,this._appendQueryString(),this._end()},l.prototype._end=function(){var e=this,t=this.xhr=g.getXHR(),n=this._formData||this._data;this._setTimeouts(),t.onreadystatechange=function(){var n=t.readyState;if(n>=2&&e._responseTimeoutTimer&&clearTimeout(e._responseTimeoutTimer),4==n){var r;try{r=t.status}catch(e){r=0}if(!r){if(e.timedout||e._aborted)return;return e.crossDomainError()}e.emit("end")}};var r=function(t,n){n.total>0&&(n.percent=n.loaded/n.total*100),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{t.onprogress=r.bind(null,"download"),t.upload&&(t.upload.onprogress=r.bind(null,"upload"))}catch(e){}try{this.username&&this.password?t.open(this.method,this.url,!0,this.username,this.password):t.open(this.method,this.url,!0)}catch(e){return this.callback(e)}if(this._withCredentials&&(t.withCredentials=!0),!this._formData&&"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof n&&!this._isHost(n)){var i=this._header["content-type"],s=this._serializer||g.serialize[i?i.split(";")[0]:""];!s&&u(i)&&(s=g.serialize["application/json"]),s&&(n=s(n))}for(var o in this.header)null!=this.header[o]&&this.header.hasOwnProperty(o)&&t.setRequestHeader(o,this.header[o]);return this._responseType&&(t.responseType=this._responseType),this.emit("request",this),t.send("undefined"!=typeof n?n:null),this},g.get=function(e,t,n){var r=g("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},g.head=function(e,t,n){var r=g("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},g.options=function(e,t,n){var r=g("OPTIONS",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},g.del=h,g.delete=h,g.patch=function(e,t,n){var r=g("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},g.post=function(e,t,n){var r=g("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},g.put=function(e,t,n){var r=g("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r}},function(e,t){function n(e){return null!==e&&"object"==typeof e}e.exports=n},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";var r=n(11),i=n(6),s=t.removeAsync=r.removeItemAsync.bind(r),o=function(e,t){try{e=JSON.parse(e)}catch(e){return null}if(e){var n=e.expiredAt&&e.expiredAt>2&63),l(r<<4&48|i>>4&15),o?l(i<<2&60|s>>6&3):"=",a?l(63&s):"="].join("")}),t.join("")};e.File=function(t,n,i){if(this.attributes={name:t,url:"",metaData:{},base64:""},r.isString(n))throw new TypeError("Creating an AV.File from a String is not yet supported.");r.isArray(n)&&(this.attributes.metaData.size=n.length,n={base64:p(n)}),this._extName="",this._data=n;var s=void 0;if(n&&n.owner)s=n.owner;else if(!e._config.disableCurrentUser)try{s=e.User.current()}catch(e){if("SYNC_API_NOT_AVAILABLE"!==e.code)throw e;console.warn("Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().")}this.attributes.metaData.owner=s?s.id:"unknown",this.set("mime_type",i)},e.File.withURL=function(t,n,r,i){if(!t||!n)throw new Error("Please provide file name and url");var s=new e.File(t,null,i);if(r)for(var o in r)s.attributes.metaData[o]||(s.attributes.metaData[o]=r[o]);return s.attributes.url=n,s.attributes.metaData.__source="external",s},e.File.createWithoutData=function(t){var n=new e.File;return n.id=t,n},e.File.prototype={className:"_File",_toFullJSON:function(t){var n=this,i=r.clone(this.attributes);return e._objectEach(i,function(n,r){i[r]=e._encode(n,t)}),e._objectEach(this._operations,function(e,t){i[t]=e}),r.has(this,"id")&&(i.objectId=this.id),r(["createdAt","updatedAt"]).each(function(e){if(r.has(n,e)){var t=n[e];i[e]=r.isDate(t)?t.toJSON():t}}),i.__type="File",i},toJSON:function(){var e=this._toFullJSON();return r.has(this,"id")&&(e.id=this.id),e},getACL:function(){return this._acl},setACL:function(t){return t instanceof e.ACL?void(this._acl=t):new a(a.OTHER_CAUSE,"ACL must be a AV.ACL.")},name:function(){return this.get("name")},url:function(){return this.get("url")},get:function(e){switch(e){case"objectId":return this.id;case"url":case"name":case"mime_type":case"metaData":case"createdAt":case"updatedAt":return this.attributes[e];default:return this.attributes.metaData[e]}},set:function e(){for(var t=this,e=function(e,n){switch(e){case"name":case"url":case"mime_type":case"base64":case"metaData":t.attributes[e]=n;break;default:t.attributes.metaData[e]=n}},n=arguments.length,r=Array(n),i=0;i100)throw new Error("Invalid quality value.");i=i||"png";var o=r?2:1;return s+"?imageView/"+o+"/w/"+e+"/h/"+t+"/q/"+n+"/format/"+i},size:function(){return this.metaData().size},ownerId:function(){return this.metaData().owner},destroy:function(e){if(!this.id)return c.reject(new Error("The file id is not eixsts."));var t=u("files",null,this.id,"DELETE",null,e);return t},_fileToken:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"fileTokens",i=this.attributes.name,s=n(i);!s&&this._extName&&(i+=this._extName,s=this._extName);var o=t()+t()+t()+t()+t()+s,a={key:o,name:i,ACL:this._acl,mime_type:e,metaData:this.attributes.metaData};return this._qiniu_key=o,u(r,null,null,"POST",a)},save:function(e){var t=this;if(this.id)throw new Error("File already saved. If you want to manipulate a file, use AV.Query to get it.");if(!this._previousSave)if(this._data){var r=this.get("mime_type");this._previousSave=this._fileToken(r).then(function(a){return a.mime_type&&(r=a.mime_type,t.set("mime_type",r)),t._token=a.token,c.resolve().then(function(){var e=t._data;if(e&&e.base64)return d(e.base64,r);if(e&&e.blob)return!e.blob.type&&r&&(e.blob.type=r),e.blob.name||(e.blob.name=t.get("name")),e.blob;if("undefined"!=typeof File&&e instanceof File)return e.size&&(t.attributes.metaData.size=e.size),e.name&&(t._extName=n(e.name)),e;if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return t.attributes.metaData.size=e.length,e;throw new TypeError("malformed file data")}).then(function(n){var r=void 0;switch(a.provider){case"s3":r=o(a,n,t,e);break;case"qcloud":r=i(a,n,t,e);break;case"qiniu":default:r=s(a,n,t,e)}return r.then(h(function(){return t._callback(!0)}),function(e){throw t._callback(!1),e})})})}else if(this.attributes.url&&"external"===this.attributes.metaData.__source){var a={name:this.attributes.name,ACL:this._acl,metaData:this.attributes.metaData,mime_type:this.mimeType,url:this.attributes.url};this._previousSave=u("files",this.attributes.name,null,"post",a).then(function(e){return t.attributes.name=e.name,t.attributes.url=e.url,t.id=e.objectId,e.size&&(t.attributes.metaData.size=e.size),t})}return this._previousSave},_callback:function(e){u("fileCallback",null,null,"post",{token:this._token,result:e}).catch(f),delete this._token,delete this._data},fetch:function(e){var e=null,t=u("files",null,this.id,"GET",e);return t.then(this._finishFetch.bind(this))},_finishFetch:function(t){var n=e.Object.prototype.parse(t);return n.attributes={name:n.name,url:n.url,mime_type:n.mime_type,bucket:n.bucket},n.attributes.metaData=n.metaData||{},n.id=n.objectId,delete n.objectId,delete n.metaData,delete n.url,delete n.name,delete n.mime_type,delete n.bucket,r.extend(this,n),this}}}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){e.GeoPoint=function(t,n){r.isArray(t)?(e.GeoPoint._validate(t[0],t[1]),this.latitude=t[0],this.longitude=t[1]):r.isObject(t)?(e.GeoPoint._validate(t.latitude,t.longitude),this.latitude=t.latitude,this.longitude=t.longitude):r.isNumber(t)&&r.isNumber(n)?(e.GeoPoint._validate(t,n),this.latitude=t,this.longitude=n):(this.latitude=0,this.longitude=0);var i=this;this.__defineGetter__&&this.__defineSetter__&&(this._latitude=this.latitude,this._longitude=this.longitude,this.__defineGetter__("latitude",function(){return i._latitude}),this.__defineGetter__("longitude",function(){return i._longitude}),this.__defineSetter__("latitude",function(t){e.GeoPoint._validate(t,i.longitude),i._latitude=t}),this.__defineSetter__("longitude",function(t){e.GeoPoint._validate(i.latitude,t),i._longitude=t}))},e.GeoPoint._validate=function(e,t){if(e<-90)throw new Error("AV.GeoPoint latitude "+e+" < -90.0.");if(e>90)throw new Error("AV.GeoPoint latitude "+e+" > 90.0.");if(t<-180)throw new Error("AV.GeoPoint longitude "+t+" < -180.0.");if(t>180)throw new Error("AV.GeoPoint longitude "+t+" > 180.0.")},e.GeoPoint.current=function(){return new e.Promise(function(t,n){navigator.geolocation.getCurrentPosition(function(n){t(new e.GeoPoint({latitude:n.coords.latitude,longitude:n.coords.longitude}))},n)})},e.GeoPoint.prototype={toJSON:function(){return e.GeoPoint._validate(this.latitude,this.longitude),{__type:"GeoPoint",latitude:this.latitude,longitude:this.longitude}},radiansTo:function(e){var t=Math.PI/180,n=this.latitude*t,r=this.longitude*t,i=e.latitude*t,s=e.longitude*t,o=n-i,a=r-s,u=Math.sin(o/2),c=Math.sin(a/2),l=u*u+Math.cos(n)*Math.cos(i)*c*c;return l=Math.min(1,l),2*Math.asin(Math.sqrt(l))},kilometersTo:function(e){return 6371*this.radiansTo(e)},milesTo:function(e){return 3958.8*this.radiansTo(e)}}}},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=n(6),s=n(2),o=function(e,t,n,r){i.applicationId&&e!==i.applicationId&&t!==i.applicationKey&&n!==i.masterKey&&console.warn("LeanCloud SDK is already initialized, please do not reinitialize it."),i.applicationId=e,i.applicationKey=t,i.masterKey=n,i._useMasterKey=!1},a=function(){console.warn("MasterKey is not supposed to be used in browser.")};i.init=function(){if(1===arguments.length){var e=arguments.length<=0?void 0:arguments[0];if("object"!==("undefined"==typeof e?"undefined":r(e)))throw new Error("AV.init(): Parameter is not correct.");e.masterKey&&a(),o(e.appId,e.appKey,e.masterKey,e.hookKey),s.setServerUrlByRegion(e.region)}else(arguments.length<=3?void 0:arguments[3])&&a(),o.apply(void 0,arguments),s.setServerUrlByRegion("cn")},i.initialize=i.init},function(e,t,n){"use strict";var r=n(0),i=n(3),s=n(2).request;e.exports=function(e){e.Insight=e.Insight||{},r.extend(e.Insight,{startJob:function(t,n){if(!t||!t.sql)throw new Error("Please provide the sql to run the job.");var r={jobConfig:t,appId:e.applicationId},i=s("bigquery","jobs",null,"POST",e._encode(r,null,!0),n);return i.then(function(t){return e._decode(t).id})},on:function(e,t){}}),e.Insight.JobQuery=function(e,t){if(!e)throw new Error("Please provide the job id.");this.id=e,this.className=t,this._skip=0,this._limit=100},e.Insight.JobQuery.prototype={skip:function(e){return this._skip=e,this},limit:function(e){return this._limit=e,this},find:function(t){var n={skip:this._skip,limit:this._limit},r=s("bigquery","jobs",this.id,"GET",n,t);return r.then(function(t){return t.error?e.Promise.reject(new i(t.code,t.error)):e.Promise.resolve(t)})}}}},function(e,t,n){"use strict";var r=n(0),i=n(3),s=n(2).request,o=n(4),a=["objectId","createdAt","updatedAt"],u=function(e){if(a.indexOf(e)!==-1)throw new Error("key["+e+"] is reserved")};e.exports=function(e){e.Object=function(t,n){if(r.isString(t))return e.Object._create.apply(this,arguments);t=t||{},n&&n.parse&&(t=this.parse(t),t=this._mergeMagicFields(t));var i=e._getValue(this,"defaults");i&&(t=r.extend({},i,t)),n&&n.collection&&(this.collection=n.collection),this._serverData={},this._opSetQueue=[{}],this._flags={},this.attributes={},this._hashedJSON={},this._escapedAttributes={},this.cid=r.uniqueId("c"),this.changed={},this._silent={},this._pending={},this.set(t,{silent:!0}),this.changed={},this._silent={},this._pending={},this._hasData=!0,this._previousAttributes=r.clone(this.attributes),this.initialize.apply(this,arguments)},e.Object.saveAll=function(t,n){return e.Object._deepSaveAsync(t,null,n)},e.Object.fetchAll=function(t,n){return e.Promise.resolve().then(function(){return s("batch",null,null,"POST",{requests:r.map(t,function(e){if(!e.className)throw new Error("object must have className to fetch");if(!e.id)throw new Error("object must have id to fetch");if(e.dirty())throw new Error("object is modified but not saved");return{method:"GET",path:"/1.1/classes/"+e.className+"/"+e.id}})},n)}).then(function(e){return r.forEach(t,function(t,n){if(!e[n].success){var r=new Error(e[n].error.error);throw r.code=e[n].error.code,r}t._finishFetch(t.parse(e[n].success))}),t})},r.extend(e.Object.prototype,e.Events,{_fetchWhenSave:!1,initialize:function(){},fetchWhenSave:function(e){if(console.warn("AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead."),!r.isBoolean(e))throw new Error("Expect boolean value for fetchWhenSave");this._fetchWhenSave=e},getObjectId:function(){return this.id},getCreatedAt:function(){return this.createdAt||this.get("createdAt")},getUpdatedAt:function(){return this.updatedAt||this.get("updatedAt")},toJSON:function(){var t=this._toFullJSON();return e._arrayEach(["__type","className"],function(e){delete t[e]}),t},_toFullJSON:function(t){var n=this,i=r.clone(this.attributes);return e._objectEach(i,function(n,r){i[r]=e._encode(n,t)}),e._objectEach(this._operations,function(e,t){i[t]=e}),r.has(this,"id")&&(i.objectId=this.id),r(["createdAt","updatedAt"]).each(function(e){if(r.has(n,e)){var t=n[e];i[e]=r.isDate(t)?t.toJSON():t}}),i.__type="Object",i.className=this.className,i},_refreshCache:function(){var t=this;t._refreshingCache||(t._refreshingCache=!0,e._objectEach(this.attributes,function(n,i){n instanceof e.Object?n._refreshCache():r.isObject(n)&&t._resetCacheForKey(i)&&t.set(i,new e.Op.Set(n),{silent:!0})}),delete t._refreshingCache)},dirty:function(e){this._refreshCache();var t=r.last(this._opSetQueue);return e?!!t[e]:!this.id||r.keys(t).length>0},_toPointer:function(){return{__type:"Pointer",className:this.className,objectId:this.id}},get:function(e){switch(e){case"objectId":return this.id;case"createdAt":case"updatedAt":return this[e];default:return this.attributes[e]}},relation:function(t){var n=this.get(t);if(n){if(!(n instanceof e.Relation))throw new Error("Called relation() on non-relation field "+t);return n._ensureParentAndKey(this,t),n}return new e.Relation(this,t)},escape:function(e){var t=this._escapedAttributes[e];if(t)return t;var n,i=this.attributes[e];return n=o.isNullOrUndefined(i)?"":r.escape(i.toString()),this._escapedAttributes[e]=n,n},has:function(e){return!o.isNullOrUndefined(this.attributes[e])},_mergeMagicFields:function(t){var n=this,i=["objectId","createdAt","updatedAt"];return e._arrayEach(i,function(i){t[i]&&("objectId"===i?n.id=t[i]:"createdAt"!==i&&"updatedAt"!==i||r.isDate(t[i])?n[i]=t[i]:n[i]=e._parseDate(t[i]),delete t[i])}),t},_startSave:function(){this._opSetQueue.push({})},_cancelSave:function(){var t=r.first(this._opSetQueue);this._opSetQueue=r.rest(this._opSetQueue);var n=r.first(this._opSetQueue);e._objectEach(t,function(e,r){var i=t[r],s=n[r];i&&s?n[r]=s._mergeWithPrevious(i):i&&(n[r]=i)}),this._saving=this._saving-1},_finishSave:function(t){var n={};e._traverse(this.attributes,function(t){t instanceof e.Object&&t.id&&t._hasData&&(n[t.id]=t)});var i=r.first(this._opSetQueue);this._opSetQueue=r.rest(this._opSetQueue),this._applyOpSet(i,this._serverData),this._mergeMagicFields(t);var s=this;e._objectEach(t,function(t,r){s._serverData[r]=e._decode(t,r);var i=e._traverse(s._serverData[r],function(t){if(t instanceof e.Object&&n[t.id])return n[t.id]});i&&(s._serverData[r]=i)}),this._rebuildAllEstimatedData(),this._saving=this._saving-1},_finishFetch:function(t,n){this._opSetQueue=[{}],this._mergeMagicFields(t);var r=this;e._objectEach(t,function(t,n){r._serverData[n]=e._decode(t,n)}),this._rebuildAllEstimatedData(),this._refreshCache(),this._opSetQueue=[{}],this._hasData=n},_applyOpSet:function(t,n){var r=this;e._objectEach(t,function(t,i){n[i]=t._estimate(n[i],r,i),n[i]===e.Op._UNSET&&delete n[i]})},_resetCacheForKey:function(t){var n=this.attributes[t];if(r.isObject(n)&&!(n instanceof e.Object)&&!(n instanceof e.File)){n=n.toJSON?n.toJSON():n;var i=JSON.stringify(n);if(this._hashedJSON[t]!==i){var s=!!this._hashedJSON[t];return this._hashedJSON[t]=i,s}}return!1},_rebuildEstimatedDataForKey:function(t){var n=this;delete this.attributes[t],this._serverData[t]&&(this.attributes[t]=this._serverData[t]),e._arrayEach(this._opSetQueue,function(r){var i=r[t];i&&(n.attributes[t]=i._estimate(n.attributes[t],n,t),n.attributes[t]===e.Op._UNSET?delete n.attributes[t]:n._resetCacheForKey(t))})},_rebuildAllEstimatedData:function(){var t=this,n=r.clone(this.attributes);this.attributes=r.clone(this._serverData),e._arrayEach(this._opSetQueue,function(n){t._applyOpSet(n,t.attributes),e._objectEach(n,function(e,n){t._resetCacheForKey(n)})}),e._objectEach(n,function(e,n){t.attributes[n]!==e&&t.trigger("change:"+n,t,t.attributes[n],{})}),e._objectEach(this.attributes,function(e,i){r.has(n,i)||t.trigger("change:"+i,t,e,{})})},set:function(t,n,i){var s;if(r.isObject(t)||o.isNullOrUndefined(t)?(s=r.mapObject(t,function(t,n){return u(n),e._decode(t,n)}),i=n):(s={},u(t),s[t]=e._decode(n,t)),i=i||{},!s)return this;s instanceof e.Object&&(s=s.attributes),i.unset&&e._objectEach(s,function(t,n){s[n]=new e.Op.Unset});var a=r.clone(s),c=this;e._objectEach(a,function(t,n){t instanceof e.Op&&(a[n]=t._estimate(c.attributes[n],c,n),a[n]===e.Op._UNSET&&delete a[n])}),this._validate(s,i),i.changes={};var l=this._escapedAttributes;this._previousAttributes||{};return e._arrayEach(r.keys(s),function(t){var n=s[t];n instanceof e.Relation&&(n.parent=c),n instanceof e.Op||(n=new e.Op.Set(n));var o=!0;n instanceof e.Op.Set&&r.isEqual(c.attributes[t],n.value)&&(o=!1),o&&(delete l[t],i.silent?c._silent[t]=!0:i.changes[t]=!0);var a=r.last(c._opSetQueue);a[t]=n._mergeWithPrevious(a[t]),c._rebuildEstimatedDataForKey(t),o?(c.changed[t]=c.attributes[t],i.silent||(c._pending[t]=!0)):(delete c.changed[t],delete c._pending[t])}),i.silent||this.change(i),this},unset:function(e,t){return t=t||{},t.unset=!0,this.set(e,null,t)},increment:function(t,n){return(r.isUndefined(n)||r.isNull(n))&&(n=1),this.set(t,new e.Op.Increment(n))},add:function(t,n){return this.set(t,new e.Op.Add(o.ensureArray(n)))},addUnique:function(t,n){return this.set(t,new e.Op.AddUnique(o.ensureArray(n)))},remove:function(t,n){return this.set(t,new e.Op.Remove(o.ensureArray(n)))},op:function(e){return r.last(this._opSetQueue)[e]},clear:function(e){e=e||{},e.unset=!0;var t=r.extend(this.attributes,this._operations);return this.set(t,e)},_getSaveJSON:function(){var t=r.clone(r.first(this._opSetQueue));return e._objectEach(t,function(e,n){t[n]=e.toJSON()}),t},_canBeSerialized:function(){return e.Object._canBeSerializedAsValue(this.attributes)},fetch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];r.isArray(e.keys)&&(e.keys=e.keys.join(",")),r.isArray(e.include)&&(e.include=e.include.join(","));var n=this,i=s("classes",this.className,this.id,"GET",e,t);return i.then(function(e){return n._finishFetch(n.parse(e),!0),n})},save:function(t,n,i){var a,u,c;r.isObject(t)||o.isNullOrUndefined(t)?(a=t,c=n):(a={},a[t]=n,c=i),c=r.clone(c)||{},c.wait&&(u=r.clone(this.attributes));var l=r.clone(c)||{};l.wait&&(l.silent=!0),a&&this.set(a,l);var h=this;h._refreshCache();var f=[],d=[];return e.Object._findUnsavedChildren(h.attributes,f,d),f.length+d.length>0?e.Object._deepSaveAsync(this.attributes,h,c).then(function(){return h.save(null,c)}):(this._startSave(),this._saving=(this._saving||0)+1,this._allPreviousSaves=this._allPreviousSaves||e.Promise.resolve(),this._allPreviousSaves=this._allPreviousSaves.catch(function(e){}).then(function(){var e=h.id?"PUT":"POST",t=h._getSaveJSON();if(h._fetchWhenSave&&(t._fetchWhenSave=!0),c.fetchWhenSave&&(t._fetchWhenSave=!0),c.query){var n;if("function"==typeof c.query.toJSON&&(n=c.query.toJSON(),n&&(t._where=n.where)),!t._where){var i=new Error("options.query is not an AV.Query");throw i}}r.extend(t,h._flags);var o="classes",f=h.className;"_User"!==h.className||h.id||(o="users",f=null);var d=c._makeRequest||s,p=d(o,f,h.id,e,t,c);return p=p.then(function(e){var t=h.parse(e);return c.wait&&(t=r.extend(a||{},t)),h._finishSave(t),c.wait&&h.set(u,l),h},function(e){throw h._cancelSave(),e})}),this._allPreviousSaves)},destroy:function(e){e=e||{};var t=this,n=function(){t.trigger("destroy",t,t.collection,e)};if(!this.id)return n();e.wait||n();var r=s("classes",this.className,this.id,"DELETE",this._flags,e);return r.then(function(){return e.wait&&n(),t})},parse:function(t){var n=r.clone(t);return r(["createdAt","updatedAt"]).each(function(t){n[t]&&(n[t]=e._parseDate(n[t]))}),n.updatedAt||(n.updatedAt=n.createdAt),n},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.id},change:function(t){t=t||{};var n=this._changing;this._changing=!0;var i=this;e._objectEach(this._silent,function(e){i._pending[e]=!0});var s=r.extend({},t.changes,this._silent);if(this._silent={},e._objectEach(s,function(e,n){i.trigger("change:"+n,i,i.get(n),t)}),n)return this;for(var o=function(e,t){i._pending[t]||i._silent[t]||delete i.changed[t]};!r.isEmpty(this._pending);)this._pending={},this.trigger("change",this,t),e._objectEach(this.changed,o),i._previousAttributes=r.clone(this.attributes); +return this._changing=!1,this},hasChanged:function(e){return arguments.length?this.changed&&r.has(this.changed,e):!r.isEmpty(this.changed)},changedAttributes:function(t){if(!t)return!!this.hasChanged()&&r.clone(this.changed);var n={},i=this._previousAttributes;return e._objectEach(t,function(e,t){r.isEqual(i[t],e)||(n[t]=e)}),n},previous:function(e){return arguments.length&&this._previousAttributes?this._previousAttributes[e]:null},previousAttributes:function(){return r.clone(this._previousAttributes)},isValid:function(){try{this.validate(this.attributes)}catch(e){return!1}return!0},validate:function(t){if(r.has(t,"ACL")&&!(t.ACL instanceof e.ACL))throw new i(i.OTHER_CAUSE,"ACL must be a AV.ACL.")},_validate:function(e,t){!t.silent&&this.validate&&(e=r.extend({},this.attributes,e),this.validate(e))},getACL:function(){return this.get("ACL")},setACL:function(e,t){return this.set("ACL",e,t)},disableBeforeHook:function(){this.ignoreHook("beforeSave"),this.ignoreHook("beforeUpdate"),this.ignoreHook("beforeDelete")},disableAfterHook:function(){this.ignoreHook("afterSave"),this.ignoreHook("afterUpdate"),this.ignoreHook("afterDelete")},ignoreHook:function(t){r.contains(["beforeSave","afterSave","beforeUpdate","afterUpdate","beforeDelete","afterDelete"],t)||console.trace("Unsupported hookName: "+t),e.hookKey||console.trace("ignoreHook required hookKey"),this._flags.__ignore_hooks||(this._flags.__ignore_hooks=[]),this._flags.__ignore_hooks.push(t)}}),e.Object.createWithoutData=function(t,n,r){var i=e.Object._create(t,void 0,void 0,!0);return i.id=n,i._hasData=r,i},e.Object.destroyAll=function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!t||0===t.length)return e.Promise.resolve();var i=r.groupBy(t,function(e){return JSON.stringify({className:e.className,flags:e._flags})}),o={requests:r.map(i,function(e){var t=r.map(e,"id").join(",");return{method:"DELETE",path:"/1.1/classes/"+e[0].className+"/"+t,body:e[0]._flags}})};return s("batch",null,null,"POST",o,n)},e.Object._getSubclass=function(t){if(!r.isString(t))throw new Error("AV.Object._getSubclass requires a string argument.");var n=e.Object._classMap[t];return n||(n=e.Object.extend(t),e.Object._classMap[t]=n),n},e.Object._create=function(t,n,r,i){var s=e.Object._getSubclass(t);return new s(n,r,i)},e.Object._classMap={},e.Object._extend=e._extend,e.Object.new=function(t,n){return new e.Object(t,n)},e.Object.extend=function(t,n,i){if(!r.isString(t)){if(t&&r.has(t,"className"))return e.Object.extend(t.className,t,n);throw new Error("AV.Object.extend's first argument should be the className.")}"User"===t&&(t="_User");var s=null;if(r.has(e.Object._classMap,t)){var o=e.Object._classMap[t];if(!n&&!i)return o;s=o._extend(n,i)}else n=n||{},n._className=t,s=this._extend(n,i);return s.extend=function(n){if(r.isString(n)||n&&r.has(n,"className"))return e.Object.extend.apply(s,arguments);var i=[t].concat(r.toArray(arguments));return e.Object.extend.apply(s,i)},s.new=function(e,t){return new s(e,t)},e.Object._classMap[t]=s,s},Object.defineProperty(e.Object.prototype,"className",{get:function(){var e=this._className||this.constructor._LCClassName||this.constructor.name;return"User"===e?"_User":e}}),e.Object.register=function(t,n){if(!(t.prototype instanceof e.Object))throw new Error("registered class is not a subclass of AV.Object");var r=n||t.name;if(!r.length)throw new Error("registered class must be named");n&&(t._LCClassName=n),e.Object._classMap[r]=t},e.Object._findUnsavedChildren=function(t,n,r){e._traverse(t,function(t){return t instanceof e.Object?(t._refreshCache(),void(t.dirty()&&n.push(t))):t instanceof e.File?void(t.url()||t.id||r.push(t)):void 0})},e.Object._canBeSerializedAsValue=function(t){var n=!0;return t instanceof e.Object||t instanceof e.File?n=!!t.id:r.isArray(t)?e._arrayEach(t,function(t){e.Object._canBeSerializedAsValue(t)||(n=!1)}):r.isObject(t)&&e._objectEach(t,function(t){e.Object._canBeSerializedAsValue(t)||(n=!1)}),n},e.Object._deepSaveAsync=function(t,n,o){var a=[],u=[];e.Object._findUnsavedChildren(t,a,u),n&&(a=r.filter(a,function(e){return e!=n}));var c=e.Promise.resolve();r.each(u,function(e){c=c.then(function(){return e.save()})});var l=r.uniq(a),h=r.uniq(l);return c.then(function(){return e.Promise._continueWhile(function(){return h.length>0},function(){var t=[],n=[];if(e._arrayEach(h,function(e){return t.length>20?void n.push(e):void(e._canBeSerialized()?t.push(e):n.push(e))}),h=n,0===t.length)return e.Promise.reject(new i(i.OTHER_CAUSE,"Tried to save a batch with a cycle."));var a=e.Promise.resolve(r.map(t,function(t){return t._allPreviousSaves||e.Promise.resolve()})),u=a.then(function(){return s("batch",null,null,"POST",{requests:r.map(t,function(e){var t=e._getSaveJSON();r.extend(t,e._flags);var n="POST",i="/1.1/classes/"+e.className;return e.id&&(i=i+"/"+e.id,n="PUT"),e._startSave(),{method:n,path:i,body:t}})},o).then(function(n){var r;if(e._arrayEach(t,function(e,t){n[t].success?e._finishSave(e.parse(n[t].success)):(r=r||n[t].error,e._cancelSave())}),r)return e.Promise.reject(new i(r.code,r.error))})});return e._arrayEach(t,function(e){e._allPreviousSaves=u}),u})}).then(function(){return t})}}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){e.Op=function(){this._initialize.apply(this,arguments)},e.Op.prototype={_initialize:function(){}},r.extend(e.Op,{_extend:e._extend,_opDecoderMap:{},_registerDecoder:function(t,n){e.Op._opDecoderMap[t]=n},_decode:function(t){var n=e.Op._opDecoderMap[t.__op];return n?n(t):void 0}}),e.Op._registerDecoder("Batch",function(t){var n=null;return e._arrayEach(t.ops,function(t){t=e.Op._decode(t),n=t._mergeWithPrevious(n)}),n}),e.Op.Set=e.Op._extend({_initialize:function(e){this._value=e},value:function(){return this._value},toJSON:function(){return e._encode(this.value())},_mergeWithPrevious:function(e){return this},_estimate:function(e){return this.value()}}),e.Op._UNSET={},e.Op.Unset=e.Op._extend({toJSON:function(){return{__op:"Delete"}},_mergeWithPrevious:function(e){return this},_estimate:function(t){return e.Op._UNSET}}),e.Op._registerDecoder("Delete",function(t){return new e.Op.Unset}),e.Op.Increment=e.Op._extend({_initialize:function(e){this._amount=e},amount:function(){return this._amount},toJSON:function(){return{__op:"Increment",amount:this._amount}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)return new e.Op.Set(this.amount());if(t instanceof e.Op.Set)return new e.Op.Set(t.value()+this.amount());if(t instanceof e.Op.Increment)return new e.Op.Increment(this.amount()+t.amount());throw new Error("Op is invalid after previous op.")}return this},_estimate:function(e){return e?e+this.amount():this.amount()}}),e.Op._registerDecoder("Increment",function(t){return new e.Op.Increment(t.amount)}),e.Op.Add=e.Op._extend({_initialize:function(e){this._objects=e},objects:function(){return this._objects},toJSON:function(){return{__op:"Add",objects:e._encode(this.objects())}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)return new e.Op.Set(this.objects());if(t instanceof e.Op.Set)return new e.Op.Set(this._estimate(t.value()));if(t instanceof e.Op.Add)return new e.Op.Add(t.objects().concat(this.objects()));throw new Error("Op is invalid after previous op.")}return this},_estimate:function(e){return e?e.concat(this.objects()):r.clone(this.objects())}}),e.Op._registerDecoder("Add",function(t){return new e.Op.Add(e._decode(t.objects))}),e.Op.AddUnique=e.Op._extend({_initialize:function(e){this._objects=r.uniq(e)},objects:function(){return this._objects},toJSON:function(){return{__op:"AddUnique",objects:e._encode(this.objects())}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)return new e.Op.Set(this.objects());if(t instanceof e.Op.Set)return new e.Op.Set(this._estimate(t.value()));if(t instanceof e.Op.AddUnique)return new e.Op.AddUnique(this._estimate(t.objects()));throw new Error("Op is invalid after previous op.")}return this},_estimate:function(t){if(t){var n=r.clone(t);return e._arrayEach(this.objects(),function(t){if(t instanceof e.Object&&t.id){var i=r.find(n,function(n){return n instanceof e.Object&&n.id===t.id});if(i){var s=r.indexOf(n,i);n[s]=t}else n.push(t)}else r.contains(n,t)||n.push(t)}),n}return r.clone(this.objects())}}),e.Op._registerDecoder("AddUnique",function(t){return new e.Op.AddUnique(e._decode(t.objects))}),e.Op.Remove=e.Op._extend({_initialize:function(e){this._objects=r.uniq(e)},objects:function(){return this._objects},toJSON:function(){return{__op:"Remove",objects:e._encode(this.objects())}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)return t;if(t instanceof e.Op.Set)return new e.Op.Set(this._estimate(t.value()));if(t instanceof e.Op.Remove)return new e.Op.Remove(r.union(t.objects(),this.objects()));throw new Error("Op is invalid after previous op.")}return this},_estimate:function(t){if(t){var n=r.difference(t,this.objects());return e._arrayEach(this.objects(),function(t){t instanceof e.Object&&t.id&&(n=r.reject(n,function(n){return n instanceof e.Object&&n.id===t.id}))}),n}return[]}}),e.Op._registerDecoder("Remove",function(t){return new e.Op.Remove(e._decode(t.objects))}),e.Op.Relation=e.Op._extend({_initialize:function(t,n){this._targetClassName=null;var i=this,s=function(t){if(t instanceof e.Object){if(!t.id)throw new Error("You can't add an unsaved AV.Object to a relation.");if(i._targetClassName||(i._targetClassName=t.className),i._targetClassName!==t.className)throw new Error("Tried to create a AV.Relation with 2 different types: "+i._targetClassName+" and "+t.className+".");return t.id}return t};this.relationsToAdd=r.uniq(r.map(t,s)),this.relationsToRemove=r.uniq(r.map(n,s))},added:function(){var t=this;return r.map(this.relationsToAdd,function(n){var r=e.Object._create(t._targetClassName);return r.id=n,r})},removed:function(){var t=this;return r.map(this.relationsToRemove,function(n){var r=e.Object._create(t._targetClassName);return r.id=n,r})},toJSON:function(){var e=null,t=null,n=this,i=function(e){return{__type:"Pointer",className:n._targetClassName,objectId:e}},s=null;return this.relationsToAdd.length>0&&(s=r.map(this.relationsToAdd,i),e={__op:"AddRelation",objects:s}),this.relationsToRemove.length>0&&(s=r.map(this.relationsToRemove,i),t={__op:"RemoveRelation",objects:s}),e&&t?{__op:"Batch",ops:[e,t]}:e||t||{}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)throw new Error("You can't modify a relation after deleting it.");if(t instanceof e.Op.Relation){if(t._targetClassName&&t._targetClassName!==this._targetClassName)throw new Error("Related object must be of class "+t._targetClassName+", but "+this._targetClassName+" was passed in.");var n=r.union(r.difference(t.relationsToAdd,this.relationsToRemove),this.relationsToAdd),i=r.union(r.difference(t.relationsToRemove,this.relationsToAdd),this.relationsToRemove),s=new e.Op.Relation(n,i);return s._targetClassName=this._targetClassName,s}throw new Error("Op is invalid after previous op.")}return this},_estimate:function(t,n,r){if(t){if(t instanceof e.Relation){if(this._targetClassName)if(t.targetClassName){if(t.targetClassName!==this._targetClassName)throw new Error("Related object must be a "+t.targetClassName+", but a "+this._targetClassName+" was passed in.")}else t.targetClassName=this._targetClassName;return t}throw new Error("Op is invalid after previous op.")}var i=new e.Relation(n,r);i.targetClassName=this._targetClassName}}),e.Op._registerDecoder("AddRelation",function(t){return new e.Op.Relation(e._decode(t.objects),[])}),e.Op._registerDecoder("RemoveRelation",function(t){return new e.Op.Relation([],e._decode(t.objects))})}},function(e,t,n){"use strict";var r=n(2).request;e.exports=function(e){e.Installation=e.Object.extend("_Installation"),e.Push=e.Push||{},e.Push.send=function(e,t){if(e.where&&(e.where=e.where.toJSON().where),e.where&&e.cql)throw new Error("Both where and cql can't be set");if(e.push_time&&(e.push_time=e.push_time.toJSON()),e.expiration_time&&(e.expiration_time=e.expiration_time.toJSON()),e.expiration_time&&e.expiration_time_interval)throw new Error("Both expiration_time and expiration_time_interval can't be set");var n=r("push",null,null,"POST",e,t);return n}}},function(e,t,n){"use strict";var r=n(0),i=n(5)("leancloud:query"),s=n(1),o=n(3),a=n(2).request,u=n(4),c=u.ensureArray,l=function(e,t){if(void 0===e)throw new Error(t)};e.exports=function(e){e.Query=function(t){r.isString(t)&&(t=e.Object._getSubclass(t)),this.objectClass=t,this.className=t.prototype.className,this._where={},this._include=[],this._select=[],this._limit=-1,this._skip=0,this._extraOptions={}},e.Query.or=function(){var t=r.toArray(arguments),n=null;e._arrayEach(t,function(e){if(r.isNull(n)&&(n=e.className),n!==e.className)throw new Error("All queries must be for the same class")});var i=new e.Query(n);return i._orQuery(t),i},e.Query.and=function(){var t=r.toArray(arguments),n=null;e._arrayEach(t,function(e){if(r.isNull(n)&&(n=e.className),n!==e.className)throw new Error("All queries must be for the same class")});var i=new e.Query(n);return i._andQuery(t),i},e.Query.doCloudQuery=function(t,n,i){var s={cql:t};r.isArray(n)?s.pvalues=n:i=n;var o=a("cloudQuery",null,null,"GET",s,i);return o.then(function(t){var n=new e.Query(t.className),i=r.map(t.results,function(e){var r=n._newObject(t);return r._finishFetch&&r._finishFetch(n._processResult(e),!0),r});return{results:i,count:t.count,className:t.className}})},e.Query._extend=e._extend,e.Query.prototype={_processResult:function(e){return e},get:function(e,t){if(!e){var n=new o(o.OBJECT_NOT_FOUND,"Object not found.");throw n}var r=this,i=r._newObject();i.id=e;var s=r.toJSON(),a={};return s.keys&&(a.keys=s.keys),s.include&&(a.include=s.include),i.fetch(a,t)},toJSON:function(){var t={where:this._where};return this._include.length>0&&(t.include=this._include.join(",")),this._select.length>0&&(t.keys=this._select.join(",")),this._limit>=0&&(t.limit=this._limit),this._skip>0&&(t.skip=this._skip),void 0!==this._order&&(t.order=this._order),e._objectEach(this._extraOptions,function(e,n){t[n]=e}),t},_newObject:function(t){var n;return n=t&&t.className?new e.Object(t.className):new this.objectClass},_createRequest:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.toJSON(),t=arguments[1];if(JSON.stringify(e).length>2e3){var n={requests:[{method:"GET",path:"/1.1/classes/"+this.className,params:e}]};return a("batch",null,null,"POST",n,t).then(function(e){var t=e[0];if(t.success)return t.success;var n=new Error(t.error.error||"Unknown batch error");throw n.code=t.error.code,n})}return a("classes",this.className,null,"GET",e,t)},_parseResponse:function(e){var t=this;return r.map(e.results,function(n){var r=t._newObject(e);return r._finishFetch&&r._finishFetch(t._processResult(n),!0),r})},find:function(e){var t=this._createRequest(void 0,e);return t.then(this._parseResponse.bind(this))},scan:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.orderedBy,o=t.batchSize,u=arguments[1],c=this.toJSON();i("scan %O",c),c.order&&(console.warn("The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan."),delete c.order),c.skip&&(console.warn("The skip option of the query is ignored for Query#scan."),delete c.skip),c.limit&&(console.warn("The limit option of the query is ignored for Query#scan."),delete c.limit),n&&(c.scan_key=n),o&&(c.limit=o);var l=s.resolve([]),h=void 0,f=!1;return{next:function(){return l=l.then(function(t){return f?[]:t.length>1?t:h||0===t.length?a("scan/classes",e.className,null,"GET",h?r.extend({},c,{cursor:h}):c,u).then(function(t){return h=t.cursor,e._parseResponse(t)}).then(function(e){return e.length||(f=!0),t.concat(e)}):(f=!0,t)}),l.then(function(e){return e.shift()}).then(function(e){return{value:e,done:f}})}}},destroyAll:function(t){var n=this;return n.find(t).then(function(n){return e.Object.destroyAll(n,t)})},count:function(e){var t=this.toJSON();t.limit=0,t.count=1;var n=this._createRequest(t,e);return n.then(function(e){return e.count})},first:function(e){var t=this,n=this.toJSON();n.limit=1;var i=this._createRequest(n,e);return i.then(function(e){return r.map(e.results,function(e){var n=t._newObject();return n._finishFetch&&n._finishFetch(t._processResult(e),!0),n})[0]})},skip:function(e){return l(e,"undefined is not a valid skip value"),this._skip=e,this},limit:function(e){return l(e,"undefined is not a valid limit value"),this._limit=e,this},equalTo:function(t,n){return l(t,"undefined is not a valid key"),l(n,"undefined is not a valid value"),this._where[t]=e._encode(n),this},_addCondition:function(t,n,r){return l(t,"undefined is not a valid condition key"),l(n,"undefined is not a valid condition"),l(r,"undefined is not a valid condition value"),this._where[t]||(this._where[t]={}),this._where[t][n]=e._encode(r),this},sizeEqualTo:function(e,t){this._addCondition(e,"$size",t)},notEqualTo:function(e,t){return this._addCondition(e,"$ne",t),this},lessThan:function(e,t){return this._addCondition(e,"$lt",t),this},greaterThan:function(e,t){return this._addCondition(e,"$gt",t),this},lessThanOrEqualTo:function(e,t){return this._addCondition(e,"$lte",t),this},greaterThanOrEqualTo:function(e,t){return this._addCondition(e,"$gte",t),this},containedIn:function(e,t){return this._addCondition(e,"$in",t),this},notContainedIn:function(e,t){return this._addCondition(e,"$nin",t),this},containsAll:function(e,t){return this._addCondition(e,"$all",t),this},exists:function(e){return this._addCondition(e,"$exists",!0),this},doesNotExist:function(e){return this._addCondition(e,"$exists",!1),this},matches:function(e,t,n){return this._addCondition(e,"$regex",t),n||(n=""),t.ignoreCase&&(n+="i"),t.multiline&&(n+="m"),n&&n.length&&this._addCondition(e,"$options",n),this},matchesQuery:function(e,t){var n=t.toJSON();return n.className=t.className,this._addCondition(e,"$inQuery",n),this},doesNotMatchQuery:function(e,t){var n=t.toJSON();return n.className=t.className,this._addCondition(e,"$notInQuery",n),this},matchesKeyInQuery:function(e,t,n){var r=n.toJSON();return r.className=n.className,this._addCondition(e,"$select",{key:t,query:r}),this},doesNotMatchKeyInQuery:function(e,t,n){var r=n.toJSON();return r.className=n.className,this._addCondition(e,"$dontSelect",{key:t,query:r}),this},_orQuery:function(e){var t=r.map(e,function(e){return e.toJSON().where});return this._where.$or=t,this},_andQuery:function(e){var t=r.map(e,function(e){return e.toJSON().where});return this._where.$and=t,this},_quote:function(e){return"\\Q"+e.replace("\\E","\\E\\\\E\\Q")+"\\E"},contains:function(e,t){return this._addCondition(e,"$regex",this._quote(t)),this},startsWith:function(e,t){return this._addCondition(e,"$regex","^"+this._quote(t)),this},endsWith:function(e,t){return this._addCondition(e,"$regex",this._quote(t)+"$"),this},ascending:function(e){return l(e,"undefined is not a valid key"),this._order=e,this},addAscending:function(e){return l(e,"undefined is not a valid key"),this._order?this._order+=","+e:this._order=e,this},descending:function(e){return l(e,"undefined is not a valid key"),this._order="-"+e,this},addDescending:function(e){return l(e,"undefined is not a valid key"),this._order?this._order+=",-"+e:this._order="-"+e,this},near:function(t,n){return n instanceof e.GeoPoint||(n=new e.GeoPoint(n)),this._addCondition(t,"$nearSphere",n),this},withinRadians:function(e,t,n){return this.near(e,t),this._addCondition(e,"$maxDistance",n),this},withinMiles:function(e,t,n){return this.withinRadians(e,t,n/3958.8)},withinKilometers:function(e,t,n){return this.withinRadians(e,t,n/6371)},withinGeoBox:function(t,n,r){return n instanceof e.GeoPoint||(n=new e.GeoPoint(n)),r instanceof e.GeoPoint||(r=new e.GeoPoint(r)),this._addCondition(t,"$within",{$box:[n,r]}),this},include:function(e){var t=this;return l(e,"undefined is not a valid key"),r(arguments).forEach(function(e){t._include=t._include.concat(c(e))}),this},select:function(e){var t=this;return l(e,"undefined is not a valid key"),r(arguments).forEach(function(e){t._select=t._select.concat(c(e))}),this},each:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._order||this._skip||this._limit>=0){var i=new Error("Cannot iterate on a query with sort, skip, or limit.");return e.Promise.reject(i)}var s=new e.Query(this.objectClass);s._limit=n.batchSize||100,s._where=r.clone(this._where),s._include=r.clone(this._include),s.ascending("objectId");var o=!1;return e.Promise._continueWhile(function(){return!o},function(){return s.find(n).then(function(n){var i=e.Promise.resolve();return r.each(n,function(e){i=i.then(function(){return t(e)})}),i.then(function(){n.length>=s._limit?s.greaterThan("objectId",n[n.length-1].id):o=!0})})})}},e.FriendShipQuery=e.Query._extend({_objectClass:e.User,_newObject:function(){return new e.User},_processResult:function(e){if(e&&e[this._friendshipTag]){var t=e[this._friendshipTag];return"Pointer"===t.__type&&"_User"===t.className&&(delete t.__type,delete t.className),t}return null}})}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){e.Relation=function(e,t){if(!r.isString(t))throw new TypeError("key must be a string");this.parent=e,this.key=t,this.targetClassName=null},e.Relation.reverseQuery=function(t,n,r){var i=new e.Query(t);return i.equalTo(n,r._toPointer()),i},e.Relation.prototype={_ensureParentAndKey:function(e,t){if(this.parent=this.parent||e,this.key=this.key||t,this.parent!==e)throw new Error("Internal Error. Relation retrieved from two different Objects.");if(this.key!==t)throw new Error("Internal Error. Relation retrieved from two different keys.")},add:function(t){r.isArray(t)||(t=[t]);var n=new e.Op.Relation(t,[]);this.parent.set(this.key,n),this.targetClassName=n._targetClassName},remove:function(t){r.isArray(t)||(t=[t]);var n=new e.Op.Relation([],t);this.parent.set(this.key,n),this.targetClassName=n._targetClassName},toJSON:function(){return{__type:"Relation",className:this.targetClassName}},query:function t(){var n,t;return this.targetClassName?(n=e.Object._getSubclass(this.targetClassName),t=new e.Query(n)):(n=e.Object._getSubclass(this.parent.className),t=new e.Query(n),t._extraOptions.redirectClassNameForKey=this.key),t._addCondition("$relatedTo","object",this.parent._toPointer()),t._addCondition("$relatedTo","key",this.key),t}}}},function(e,t,n){"use strict";var r=n(0),i=n(3);e.exports=function(e){e.Role=e.Object.extend("_Role",{constructor:function(t,n,i){if(r.isString(t)?(e.Object.prototype.constructor.call(this,null,null),this.setName(t)):e.Object.prototype.constructor.call(this,t,n),void 0===n){if(!i&&!this.getACL()){console.warn("DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.");var s=new e.ACL;s.setPublicReadAccess(!0),this.setACL(s)}}else{if(!(n instanceof e.ACL))throw new TypeError("acl must be an instance of AV.ACL");this.setACL(n)}},getName:function(){return this.get("name")},setName:function(e,t){return this.set("name",e,t)},getUsers:function(){return this.relation("users")},getRoles:function(){return this.relation("roles")},validate:function(t,n){if("name"in t&&t.name!==this.getName()){var s=t.name;if(this.id&&this.id!==t.objectId)return new i(i.OTHER_CAUSE,"A role's name can only be set before it has been saved.");if(!r.isString(s))return new i(i.OTHER_CAUSE,"A role's name must be a String.");if(!/^[0-9a-zA-Z\-_ ]+$/.test(s))return new i(i.OTHER_CAUSE,"A role's name can only contain alphanumeric characters, _, -, and spaces.")}return!!e.Object.prototype.validate&&e.Object.prototype.validate.call(this,t,n)}})}},function(e,t,n){"use strict";var r=n(0),i=n(2).request;e.exports=function(e){e.SearchSortBuilder=function(){this._sortFields=[]},e.SearchSortBuilder.prototype={_addField:function(e,t,n,r){var i={};return i[e]={order:t||"asc",mode:n||"avg",missing:"_"+(r||"last")},this._sortFields.push(i),this},ascending:function(e,t,n){return this._addField(e,"asc",t,n)},descending:function(e,t,n){return this._addField(e,"desc",t,n)},whereNear:function(e,t,n){n=n||{};var r={},i={lat:t.latitude,lon:t.longitude},s={order:n.order||"asc",mode:n.mode||"avg",unit:n.unit||"km"};return s[e]=i,r._geo_distance=s,this._sortFields.push(r),this},build:function(){return JSON.stringify(e._encode(this._sortFields))}},e.SearchQuery=e.Query._extend({_sid:null,_hits:0,_queryString:null,_highlights:null,_sortBuilder:null,_createRequest:function(e,t){return i("search/select",null,null,"GET",e||this.toJSON(),t)},sid:function(e){return this._sid=e,this},queryString:function(e){return this._queryString=e,this},highlights:function(e){var t;return t=e&&r.isString(e)?arguments:e,this._highlights=t,this},sortBy:function(e){return this._sortBuilder=e,this},hits:function(){return this._hits||(this._hits=0),this._hits},_processResult:function(e){return delete e.className,delete e._app_url,delete e._deeplink,e},hasMore:function(){return!this._hitEnd},reset:function(){this._hitEnd=!1,this._sid=null,this._hits=0},find:function(){var e=this,t=this._createRequest();return t.then(function(t){return t.sid?(e._oldSid=e._sid,e._sid=t.sid):(e._sid=null,e._hitEnd=!0),e._hits=t.hits||0,r.map(t.results,function(n){n.className&&(t.className=n.className);var r=e._newObject(t);return r.appURL=n._app_url,r._finishFetch(e._processResult(n),!0),r})})},toJSON:function(){var t=e.SearchQuery.__super__.toJSON.call(this);if(delete t.where,this.className&&(t.clazz=this.className),this._sid&&(t.sid=this._sid),!this._queryString)throw new Error("Please set query string.");if(t.q=this._queryString,this._highlights&&(t.highlights=this._highlights.join(",")),this._sortBuilder&&t.order)throw new Error("sort and order can not be set at same time.");return this._sortBuilder&&(t.sort=this._sortBuilder.build()),t}})}},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=n(0),s=n(2).request;e.exports=function(e){var t=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e.User.currentAsync().then(function(n){return n||e.User._fetchUserBySessionToken(t.sessionToken)})},n=function(n){return t(n).then(function(t){return e.Object.createWithoutData("_User",t.id)._toPointer()})};e.Status=function(e,t){return this.data={},this.inboxType="default",this.query=null,e&&"object"===("undefined"==typeof e?"undefined":r(e))?this.data=e:(e&&(this.data.image=e),t&&(this.data.message=t)),this},e.Status.prototype={get:function(e){return this.data[e]},set:function(e,t){return this.data[e]=t,this},destroy:function(t){if(!this.id)return e.Promise.reject(new Error("The status id is not exists."));var n=s("statuses",null,this.id,"DELETE",t);return n},toObject:function(){return this.id?e.Object.createWithoutData("_Status",this.id):null},_getDataJSON:function(){var t=i.clone(this.data);return e._encode(t)},send:function(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!r.sessionToken&&!e.User.current())throw new Error("Please signin an user.");return this.query?n(r).then(function(e){var n=t.query.toJSON();n.className=t.query.className;var i={};return i.query=n,t.data=t.data||{},t.data.source=t.data.source||e,i.data=t._getDataJSON(),i.inboxType=t.inboxType||"default",s("statuses",null,null,"POST",i,r)}).then(function(n){return t.id=n.objectId,t.createdAt=e._parseDate(n.createdAt),t}):e.Status.sendStatusToFollowers(this,r)},_finishFetch:function(t){this.id=t.objectId,this.createdAt=e._parseDate(t.createdAt),this.updatedAt=e._parseDate(t.updatedAt),this.messageId=t.messageId,delete t.messageId,delete t.objectId,delete t.createdAt,delete t.updatedAt,this.data=e._decode(t)}},e.Status.sendStatusToFollowers=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!r.sessionToken&&!e.User.current())throw new Error("Please signin an user.");return n(r).then(function(n){var i={};i.className="_Follower",i.keys="follower",i.where={user:n};var o={};o.query=i,t.data=t.data||{},t.data.source=t.data.source||n,o.data=t._getDataJSON(),o.inboxType=t.inboxType||"default";var a=s("statuses",null,null,"POST",o,r);return a.then(function(n){return t.id=n.objectId,t.createdAt=e._parseDate(n.createdAt),t})})},e.Status.sendPrivateStatus=function(t,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!o.sessionToken&&!e.User.current())throw new Error("Please signin an user.");if(!r)throw new Error("Invalid target user.");var a=i.isString(r)?r:r.id;if(!a)throw new Error("Invalid target user.");return n(o).then(function(n){var r={};r.className="_User",r.where={objectId:a};var i={};i.query=r,t.data=t.data||{},t.data.source=t.data.source||n,i.data=t._getDataJSON(),i.inboxType="private",t.inboxType="private";var u=s("statuses",null,null,"POST",i,o);return u.then(function(n){return t.id=n.objectId,t.createdAt=e._parseDate(n.createdAt),t})})},e.Status.countUnreadStatuses=function(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(i.isString(r)||(o=r),!o.sessionToken&&null==n&&!e.User.current())throw new Error("Please signin an user or pass the owner objectId.");return t(o).then(function(t){var n={};return n.inboxType=e._encode(r),n.owner=e._encode(t),s("subscribe/statuses/count",null,null,"GET",n,o)})},e.Status.resetUnreadCount=function(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(i.isString(r)||(o=r),!o.sessionToken&&null==n&&!e.User.current())throw new Error("Please signin an user or pass the owner objectId.");return t(o).then(function(t){var n={};return n.inboxType=e._encode(r),n.owner=e._encode(t),s("subscribe/statuses/resetUnreadCount",null,null,"POST",n,o)})},e.Status.statusQuery=function(t){var n=new e.Query("_Status");return t&&n.equalTo("source",t),n},e.InboxQuery=e.Query._extend({_objectClass:e.Status,_sinceId:0,_maxId:0,_inboxType:"default",_owner:null,_newObject:function(){return new e.Status},_createRequest:function(e,t){return s("subscribe/statuses",null,null,"GET",e||this.toJSON(),t)},sinceId:function(e){return this._sinceId=e,this},maxId:function(e){return this._maxId=e,this},owner:function(e){return this._owner=e,this},inboxType:function(e){return this._inboxType=e,this},toJSON:function(){var t=e.InboxQuery.__super__.toJSON.call(this);return t.owner=e._encode(this._owner),t.inboxType=e._encode(this._inboxType),t.sinceId=e._encode(this._sinceId),t.maxId=e._encode(this._maxId),t}}),e.Status.inboxQuery=function(t,n){var r=new e.InboxQuery(e.Status);return t&&(r._owner=t),n&&(r._inboxType=n),r}}},function(e,t,n){"use strict";var r=n(0),i=n(3),s=n(2).request,o=n(1),a=function(){if("undefined"==typeof wx||"function"!=typeof wx.login)throw new Error("Weapp Login is only available in Weapp");return new o(function(e,t){wx.login({success:function(n){var r=n.code,i=n.errMsg;r?e(r):t(new Error(i))}})})};e.exports=function(e){e.User=e.Object.extend("_User",{_isCurrentUser:!1,_mergeMagicFields:function(t){t.sessionToken&&(this._sessionToken=t.sessionToken,delete t.sessionToken),e.User.__super__._mergeMagicFields.call(this,t)},_cleanupAuthData:function(){if(this.isCurrent()){var t=this.get("authData");t&&e._objectEach(this.get("authData"),function(e,n){t[n]||delete t[n]})}},_synchronizeAllAuthData:function(){var t=this.get("authData");if(t){var n=this;e._objectEach(this.get("authData"),function(e,t){n._synchronizeAuthData(t)})}},_synchronizeAuthData:function(t){if(this.isCurrent()){var n;r.isString(t)?(n=t,t=e.User._authProviders[n]):n=t.getAuthType();var i=this.get("authData");if(i&&t){var s=t.restoreAuthentication(i[n]);s||this._unlinkFrom(t)}}},_handleSaveResult:function(t){return t&&!e._config.disableCurrentUser&&(this._isCurrentUser=!0),this._cleanupAuthData(), +this._synchronizeAllAuthData(),delete this._serverData.password,this._rebuildEstimatedDataForKey("password"),this._refreshCache(),!t&&!this.isCurrent()||e._config.disableCurrentUser?o.resolve():o.resolve(e.User._saveCurrentUser(this))},_linkWith:function(t,n){var i,s=this;if(r.isString(t)?(i=t,t=e.User._authProviders[t]):i=t.getAuthType(),n){var o=this.get("authData")||{};return o[i]=n,this.save({authData:o}).then(function(e){return e._handleSaveResult(!0).then(function(){return e})})}return t.authenticate().then(function(e){return s._linkWith(t,e)})},linkWithWeapp:function(){var e=this;return a().then(function(t){return e._linkWith("lc_weapp",{code:t})})},_unlinkFrom:function(t){var n=this;return r.isString(t)&&(t=e.User._authProviders[t]),this._linkWith(t,null).then(function(e){return n._synchronizeAuthData(t),e})},_isLinked:function(e){var t;t=r.isString(e)?e:e.getAuthType();var n=this.get("authData")||{};return!!n[t]},logOut:function(){this._logOutWithAll(),this._isCurrentUser=!1},_logOutWithAll:function(){var t=this.get("authData");if(t){var n=this;e._objectEach(this.get("authData"),function(e,t){n._logOutWith(t)})}},_logOutWith:function(t){this.isCurrent()&&(r.isString(t)&&(t=e.User._authProviders[t]),t&&t.deauthenticate&&t.deauthenticate())},signUp:function(e,t){var n,r=e&&e.username||this.get("username");if(!r||""===r)throw n=new i(i.OTHER_CAUSE,"Cannot sign up user with an empty name.");var s=e&&e.password||this.get("password");if(!s||""===s)throw n=new i(i.OTHER_CAUSE,"Cannot sign up user with an empty password.");return this.save(e,t).then(function(e){return e._handleSaveResult(!0).then(function(){return e})})},signUpOrlogInWithMobilePhone:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e&&e.mobilePhoneNumber||this.get("mobilePhoneNumber");if(!r||""===r)throw t=new i(i.OTHER_CAUSE,"Cannot sign up or login user by mobilePhoneNumber with an empty mobilePhoneNumber.");var o=e&&e.smsCode||this.get("smsCode");if(!o||""===o)throw t=new i(i.OTHER_CAUSE,"Cannot sign up or login user by mobilePhoneNumber with an empty smsCode.");return n._makeRequest=function(e,t,n,r,i){return s("usersByMobilePhone",null,null,"POST",i)},this.save(e,n).then(function(e){return delete e.attributes.smsCode,delete e._serverData.smsCode,e._handleSaveResult(!0).then(function(){return e})})},logIn:function(){var e=this,t=s("login",null,null,"POST",this.toJSON());return t.then(function(t){var n=e.parse(t);return e._finishFetch(n),e._handleSaveResult(!0).then(function(){return n.smsCode||delete e.attributes.smsCode,e})})},save:function(t,n,i){var s,o;return r.isObject(t)||r.isNull(t)||r.isUndefined(t)?(s=t,o=n):(s={},s[t]=n,o=i),o=o||{},e.Object.prototype.save.call(this,s,o).then(function(e){return e._handleSaveResult(!1).then(function(){return e})})},follow:function(e,t){if(!this.id)throw new Error("Please signin.");if(!e)throw new Error("Invalid target user.");var n=r.isString(e)?e:e.id;if(!n)throw new Error("Invalid target user.");var i="users/"+this.id+"/friendship/"+n,o=s(i,null,null,"POST",null,t);return o},unfollow:function(e,t){if(!this.id)throw new Error("Please signin.");if(!e)throw new Error("Invalid target user.");var n=r.isString(e)?e:e.id;if(!n)throw new Error("Invalid target user.");var i="users/"+this.id+"/friendship/"+n,o=s(i,null,null,"DELETE",null,t);return o},followerQuery:function(){return e.User.followerQuery(this.id)},followeeQuery:function(){return e.User.followeeQuery(this.id)},fetch:function(t,n){return e.Object.prototype.fetch.call(this,t,n).then(function(e){return e._handleSaveResult(!1).then(function(){return e})})},updatePassword:function(e,t,n){var r="users/"+this.id+"/updatePassword",i={old_password:e,new_password:t},o=s(r,null,null,"PUT",i,n);return o},isCurrent:function(){return this._isCurrentUser},getUsername:function(){return this.get("username")},getMobilePhoneNumber:function(){return this.get("mobilePhoneNumber")},setMobilePhoneNumber:function(e,t){return this.set("mobilePhoneNumber",e,t)},setUsername:function(e,t){return this.set("username",e,t)},setPassword:function(e,t){return this.set("password",e,t)},getEmail:function(){return this.get("email")},setEmail:function(e,t){return this.set("email",e,t)},authenticated:function(){return console.warn("DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。"),!!this._sessionToken&&!e._config.disableCurrentUser&&e.User.current()&&e.User.current().id===this.id},isAuthenticated:function(){var t=this;return o.resolve().then(function(){return!!t._sessionToken&&e.User._fetchUserBySessionToken(t._sessionToken).then(function(){return!0},function(e){if(211===e.code)return!1;throw e})})},getSessionToken:function(){return this._sessionToken},refreshSessionToken:function(e){var t=this;return s("users/"+this.id+"/refreshSessionToken",null,null,"PUT",null,e).then(function(e){return t._finishFetch(e),t._handleSaveResult(!0).then(function(){return t})})},getRoles:function(t){return e.Relation.reverseQuery("_Role","users",this).find(t)}},{_currentUser:null,_currentUserMatchesDisk:!1,_CURRENT_USER_KEY:"currentUser",_authProviders:{},signUp:function(t,n,r,i){r=r||{},r.username=t,r.password=n;var s=e.Object._create("_User");return s.signUp(r,i)},logIn:function(t,n,r){var i=e.Object._create("_User");return i._finishFetch({username:t,password:n}),i.logIn(r)},become:function(e){return this._fetchUserBySessionToken(e).then(function(e){return e._handleSaveResult(!0).then(function(){return e})})},_fetchUserBySessionToken:function(t){var n=e.Object._create("_User");return s("users","me",null,"GET",{session_token:t}).then(function(e){var t=n.parse(e);return n._finishFetch(t),n})},logInWithMobilePhoneSmsCode:function(t,n,r){var i=e.Object._create("_User");return i._finishFetch({mobilePhoneNumber:t,smsCode:n}),i.logIn(r)},signUpOrlogInWithMobilePhone:function(t,n,r,i){r=r||{},r.mobilePhoneNumber=t,r.smsCode=n;var s=e.Object._create("_User");return s.signUpOrlogInWithMobilePhone(r,i)},logInWithMobilePhone:function(t,n,r){var i=e.Object._create("_User");return i._finishFetch({mobilePhoneNumber:t,password:n}),i.logIn(r)},signUpOrlogInWithAuthData:function(t,n){return e.User._logInWith(n,t)},loginWithWeapp:function(){var e=this;return a().then(function(t){return e.signUpOrlogInWithAuthData({code:t},"lc_weapp")})},associateWithAuthData:function(e,t,n){return e._linkWith(t,n)},logOut:function(){return e._config.disableCurrentUser?(console.warn("AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html"),o.resolve(null)):(null!==e.User._currentUser&&(e.User._currentUser._logOutWithAll(),e.User._currentUser._isCurrentUser=!1),e.User._currentUserMatchesDisk=!0,e.User._currentUser=null,e.localStorage.removeItemAsync(e._getAVPath(e.User._CURRENT_USER_KEY)))},followerQuery:function(t){if(!t||!r.isString(t))throw new Error("Invalid user object id.");var n=new e.FriendShipQuery("_Follower");return n._friendshipTag="follower",n.equalTo("user",e.Object.createWithoutData("_User",t)),n},followeeQuery:function(t){if(!t||!r.isString(t))throw new Error("Invalid user object id.");var n=new e.FriendShipQuery("_Followee");return n._friendshipTag="followee",n.equalTo("user",e.Object.createWithoutData("_User",t)),n},requestPasswordReset:function(e){var t={email:e},n=s("requestPasswordReset",null,null,"POST",t);return n},requestEmailVerify:function(e){var t={email:e},n=s("requestEmailVerify",null,null,"POST",t);return n},requestMobilePhoneVerify:function(e){var t={mobilePhoneNumber:e},n=s("requestMobilePhoneVerify",null,null,"POST",t);return n},requestPasswordResetBySmsCode:function(e){var t={mobilePhoneNumber:e},n=s("requestPasswordResetBySmsCode",null,null,"POST",t);return n},resetPasswordBySmsCode:function(e,t){var n={password:t},r=s("resetPasswordBySmsCode",null,e,"PUT",n);return r},verifyMobilePhone:function(e){var t=s("verifyMobilePhone",null,e,"POST",null);return t},requestLoginSmsCode:function(e){var t={mobilePhoneNumber:e},n=s("requestLoginSmsCode",null,null,"POST",t);return n},currentAsync:function(){return e._config.disableCurrentUser?(console.warn("AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html"),o.resolve(null)):e.User._currentUser?o.resolve(e.User._currentUser):e.User._currentUserMatchesDisk?o.resolve(e.User._currentUser):e.localStorage.getItemAsync(e._getAVPath(e.User._CURRENT_USER_KEY)).then(function(t){if(!t)return null;e.User._currentUserMatchesDisk=!0,e.User._currentUser=e.Object._create("_User"),e.User._currentUser._isCurrentUser=!0;var n=JSON.parse(t);return e.User._currentUser.id=n._id,delete n._id,e.User._currentUser._sessionToken=n._sessionToken,delete n._sessionToken,e.User._currentUser._finishFetch(n),e.User._currentUser._synchronizeAllAuthData(),e.User._currentUser._refreshCache(),e.User._currentUser._opSetQueue=[{}],e.User._currentUser})},current:function(){if(e._config.disableCurrentUser)return console.warn("AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html"),null;if(e.User._currentUser)return e.User._currentUser;if(e.User._currentUserMatchesDisk)return e.User._currentUser;e.User._currentUserMatchesDisk=!0;var t=e.localStorage.getItem(e._getAVPath(e.User._CURRENT_USER_KEY));if(!t)return null;e.User._currentUser=e.Object._create("_User"),e.User._currentUser._isCurrentUser=!0;var n=JSON.parse(t);return e.User._currentUser.id=n._id,delete n._id,e.User._currentUser._sessionToken=n._sessionToken,delete n._sessionToken,e.User._currentUser._finishFetch(n),e.User._currentUser._synchronizeAllAuthData(),e.User._currentUser._refreshCache(),e.User._currentUser._opSetQueue=[{}],e.User._currentUser},_saveCurrentUser:function(t){var n;return n=e.User._currentUser!==t?e.User.logOut():o.resolve(),n.then(function(){t._isCurrentUser=!0,e.User._currentUser=t;var n=t.toJSON();return n._id=t.id,n._sessionToken=t._sessionToken,e.localStorage.setItemAsync(e._getAVPath(e.User._CURRENT_USER_KEY),JSON.stringify(n)).then(function(){e.User._currentUserMatchesDisk=!0})})},_registerAuthenticationProvider:function(t){e.User._authProviders[t.getAuthType()]=t,!e._config.disableCurrentUser&&e.User.current()&&e.User.current()._synchronizeAuthData(t.getAuthType())},_logInWith:function(t,n){var r=e.Object._create("_User");return r._linkWith(t,n)}})}},function(e,t,n){"use strict";var r=n(6);r._=n(0),r.version=n(12),r.Promise=n(1),r.localStorage=n(11),r.Cache=n(10),r.Error=n(3),n(19),n(16)(r),n(18)(r),n(14)(r),n(22)(r),n(25)(r),n(17)(r),n(21)(r),n(26)(r),n(29)(r),n(24)(r),n(15)(r),n(23)(r),n(28)(r),n(27)(r),n(20)(r),e.exports=r},function(e,t,n){"use strict";e.exports=[]},function(e,t,n){"use strict";var r=n(12),i=["Browser"].concat(n(31));e.exports="LeanCloud-JS-SDK/"+r+" ("+i.join("; ")+")"},function(e,t,n){"use strict";var r=n(7),i=n(5)("cos"),s=n(1);e.exports=function(e,t,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};n.attributes.url=e.url,n._bucket=e.bucket,n.id=e.objectId;var a=e.upload_url+"?sign="+encodeURIComponent(e.token);return new s(function(e,s){var u=r("POST",a).field("fileContent",t).field("op","upload");o.onprogress&&u.on("progress",o.onprogress),u.end(function(t,r){return r&&i(r.status,r.body,r.text),t?(r&&(t.statusCode=r.status,t.responseText=r.text,t.response=r.body),s(t)):void e(n)})})}},function(e,t,n){"use strict";var r=n(7),i=n(1),s=n(5)("qiniu");e.exports=function(e,t,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};n.attributes.url=e.url,n._bucket=e.bucket,n.id=e.objectId;var a=e.token;return new i(function(e,i){var u=r("POST","https://up.qbox.me").field("file",t).field("name",n.attributes.name).field("key",n._qiniu_key).field("token",a);o.onprogress&&u.on("progress",o.onprogress),u.end(function(t,r){return r&&s(r.status,r.body,r.text),t?(r&&(t.statusCode=r.status,t.responseText=r.text,t.response=r.body),i(t)):void e(n)})})}},function(e,t,n){"use strict";var r=n(7);n(1);e.exports=function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return n.attributes.url=e.url,n._bucket=e.bucket,n.id=e.objectId,new Promise(function(s,o){var a=r("PUT",e.upload_url).set("Content-Type",n.get("mime_type")).send(t);i.onprogress&&a.on("progress",i.onprogress),a.end(function(e,t){return e?(t&&(e.statusCode=t.status,e.responseText=t.text,e.response=t.body),o(e)):void s(n)})})}},function(e,t,n){"use strict";(function(t){var r=n(0),i=(n(1),{}),s=["getItem","setItem","removeItem","clear"],o=t.localStorage;try{var a="__storejs__";if(o.setItem(a,a),o.getItem(a)!=a)throw new Error;o.removeItem(a)}catch(e){o=n(43)}r(s).each(function(e){i[e]=function(){return t.localStorage[e].apply(t.localStorage,arguments)}}),i.async=!1,e.exports=i}).call(t,n(9))},function(e,t,n){"use strict";var r=function(e,t){var n;e.indexOf("base64")<0?n=atob(e):e.split(",")[0].indexOf("base64")>=0?(t=t||e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1])):n=unescape(e.split(",")[1]);for(var r=new Uint8Array(n.length),i=0;i>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return 16711935&n.rotl(e,8)|4278255360&n.rotl(e,24);for(var t=0;t0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],n=0,r=0;n>>5]|=e[n]<<24-r%32;return t},wordsToBytes:function(e){for(var t=[],n=0;n<32*e.length;n+=8)t.push(e[n>>>5]>>>24-n%32&255);return t},bytesToHex:function(e){for(var t=[],n=0;n>>4).toString(16)),t.push((15&e[n]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],n=0;n>>6*(3-s)&63)):n.push("=");return n.join("")},base64ToBytes:function(e){e=e.replace(/[^A-Z0-9+\/]/gi,"");for(var n=[],r=0,i=0;r>>6-2*i);return n}};e.exports=n}()},function(e,t,n){function r(e){var n,r=0;for(n in e)r=(r<<5)-r+e.charCodeAt(n),r|=0;return t.colors[Math.abs(r)%t.colors.length]}function i(e){function n(){if(n.enabled){var e=n,r=+new Date,i=r-(c||r);e.diff=i,e.prev=c,e.curr=r,c=r;for(var s=new Array(arguments.length),o=0;o>>24)|4278255360&(a[d]<<24|a[d]>>>8);a[u>>>5]|=128<>>9<<4)+14]=u;for(var p=o._ff,_=o._gg,v=o._hh,m=o._ii,d=0;d>>0,l=l+g>>>0,h=h+b>>>0,f=f+w>>>0}return t.endian([c,l,h,f])};o._ff=function(e,t,n,r,i,s,o){var a=e+(t&n|~t&r)+(i>>>0)+o;return(a<>>32-s)+t},o._gg=function(e,t,n,r,i,s,o){var a=e+(t&r|n&~r)+(i>>>0)+o;return(a<>>32-s)+t},o._hh=function(e,t,n,r,i,s,o){var a=e+(t^n^r)+(i>>>0)+o;return(a<>>32-s)+t},o._ii=function(e,t,n,r,i,s,o){var a=e+(n^(t|~r))+(i>>>0)+o;return(a<>>32-s)+t},o._blocksize=16,o._digestsize=16,e.exports=function(e,n){if(void 0===e||null===e)throw new Error("Illegal argument "+e);var r=t.wordsToBytes(o(e,n));return n&&n.asBytes?r:n&&n.asString?s.bytesToString(r):t.bytesToHex(r)}}()},function(e,t){function n(e){if(e=String(e),!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*c;case"hours":case"hour":case"hrs":case"hr":case"h":return n*u;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*o;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function r(e){return e>=c?Math.round(e/c)+"d":e>=u?Math.round(e/u)+"h":e>=a?Math.round(e/a)+"m":e>=o?Math.round(e/o)+"s":e+"ms"}function i(e){return s(e,c,"day")||s(e,u,"hour")||s(e,a,"minute")||s(e,o,"second")||e+" ms"}function s(e,t,n){if(!(e0)return n(e);if("number"===s&&isNaN(e)===!1)return t.long?i(e):r(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},function(e,t,n){function r(e){var t=i(e)?Object.prototype.toString.call(e):"";return"[object Function]"===t}var i=n(8);e.exports=r},function(e,t,n){function r(e){if(e)return i(e)}function i(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}var s=n(8);e.exports=r,r.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,this},r.prototype.parse=function(e){return this._parser=e,this},r.prototype.responseType=function(e){return this._responseType=e,this},r.prototype.serialize=function(e){return this._serializer=e,this},r.prototype.timeout=function(e){if(!e||"object"!=typeof e)return this._timeout=e,this._responseTimeout=0,this;for(var t in e)switch(t){case"deadline":this._timeout=e.deadline;break;case"response":this._responseTimeout=e.response;break;default:console.warn("Unknown timeout option",t)}return this},r.prototype.retry=function(e){return 0!==arguments.length&&e!==!0||(e=1),e<=0&&(e=0),this._maxRetries=e,this._retries=0,this},r.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this._end()},r.prototype.then=function(e,t){if(!this._fullfilledPromise){var n=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(function(e,t){n.end(function(n,r){n?t(n):e(r)})})}return this._fullfilledPromise.then(e,t)},r.prototype.catch=function(e){return this.then(void 0,e)},r.prototype.use=function(e){return e(this),this},r.prototype.ok=function(e){if("function"!=typeof e)throw Error("Callback required");return this._okCallback=e,this},r.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},r.prototype.get=function(e){return this._header[e.toLowerCase()]},r.prototype.getHeader=r.prototype.get,r.prototype.set=function(e,t){if(s(e)){for(var n in e)this.set(n,e[n]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},r.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},r.prototype.field=function(e,t){if(null===e||void 0===e)throw new Error(".field(name, val) name can not be empty");if(this._data&&console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"),s(e)){for(var n in e)this.field(n,e[n]);return this}if(Array.isArray(t)){for(var r in t)this.field(e,t[r]);return this}if(null===t||void 0===t)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof t&&(t=""+t),this._getFormData().append(e,t),this},r.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},r.prototype.withCredentials=function(e){return void 0==e&&(e=!0),this._withCredentials=e,this},r.prototype.redirects=function(e){return this._maxRedirects=e,this},r.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},r.prototype.send=function(e){var t=s(e),n=this._header["content-type"];if(this._formData&&console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"), +t&&!this._data)Array.isArray(e)?this._data=[]:this._isHost(e)||(this._data={});else if(e&&this._data&&this._isHost(this._data))throw Error("Can't merge these send calls");if(t&&s(this._data))for(var r in e)this._data[r]=e[r];else"string"==typeof e?(n||this.type("form"),n=this._header["content-type"],"application/x-www-form-urlencoded"==n?this._data=this._data?this._data+"&"+e:e:this._data=(this._data||"")+e):this._data=e;return!t||this._isHost(e)?this:(n||this.type("json"),this)},r.prototype.sortQuery=function(e){return this._sort="undefined"==typeof e||e,this},r.prototype._timeoutError=function(e,t,n){if(!this._aborted){var r=new Error(e+t+"ms exceeded");r.timeout=t,r.code="ECONNABORTED",r.errno=n,this.timedout=!0,this.abort(),this.callback(r)}},r.prototype._setTimeouts=function(){var e=this;this._timeout&&!this._timer&&(this._timer=setTimeout(function(){e._timeoutError("Timeout of ",e._timeout,"ETIME")},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){e._timeoutError("Response timeout of ",e._responseTimeout,"ETIMEDOUT")},this._responseTimeout))}},function(e,t,n){function r(e){if(e)return i(e)}function i(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}var s=n(50);e.exports=r,r.prototype.get=function(e){return this.header[e.toLowerCase()]},r.prototype._setHeaderProperties=function(e){var t=e["content-type"]||"";this.type=s.type(t);var n=s.params(t);for(var r in n)this[r]=n[r];this.links={};try{e.link&&(this.links=s.parseLinks(e.link))}catch(e){}},r.prototype._setStatusProperties=function(e){var t=e/100|0;this.status=this.statusCode=e,this.statusType=t,this.info=1==t,this.ok=2==t,this.redirect=3==t,this.clientError=4==t,this.serverError=5==t,this.error=(4==t||5==t)&&this.toError(),this.accepted=202==e,this.noContent=204==e,this.badRequest=400==e,this.unauthorized=401==e,this.notAcceptable=406==e,this.forbidden=403==e,this.notFound=404==e}},function(e,t){var n=["ECONNRESET","ETIMEDOUT","EADDRINFO","ESOCKETTIMEDOUT"];e.exports=function(e,t){return!!(e&&e.code&&~n.indexOf(e.code))||(!!(t&&t.status&&t.status>=500)||(!!(e&&"timeout"in e&&"ECONNABORTED"==e.code)||!!(e&&"crossDomain"in e)))}},function(e,t){t.type=function(e){return e.split(/ *; */).shift()},t.params=function(e){return e.split(/ *; */).reduce(function(e,t){var n=t.split(/ *= */),r=n.shift(),i=n.shift();return r&&i&&(e[r]=i),e},{})},t.parseLinks=function(e){return e.split(/ *, */).reduce(function(e,t){var n=t.split(/ *; */),r=n[0].slice(1,-1),i=n[1].split(/ *= */)[1].slice(1,-1);return e[i]=r,e},{})},t.cleanHeader=function(e,t){return delete e["content-type"],delete e["content-length"],delete e["transfer-encoding"],delete e.host,t&&delete e.cookie,e}},function(e,t){}])}); +//# sourceMappingURL=av-min.js.map \ No newline at end of file diff --git a/dist/av-min.js.map b/dist/av-min.js.map new file mode 100644 index 000000000..efb3732f2 --- /dev/null +++ b/dist/av-min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:/webpack/bootstrap fda3052434ab8851837a","webpack:///~/underscore/underscore.js","webpack:///src/promise.js","webpack:///src/request.js","webpack:///src/error.js","webpack:///src/utils/index.js","webpack:///~/debug/src/browser.js","webpack:///src/av.js","webpack:///~/superagent/lib/client.js","webpack:///~/superagent/lib/is-object.js","webpack:///(webpack)/buildin/global.js","webpack:///src/cache.js","webpack:///src/localstorage.js","webpack:///src/version.js","webpack:///~/charenc/charenc.js","webpack:///src/acl.js","webpack:///src/cloudfunction.js","webpack:///src/event.js","webpack:///src/file.js","webpack:///src/geopoint.js","webpack:///src/init.js","webpack:///src/insight.js","webpack:///src/object.js","webpack:///src/op.js","webpack:///src/push.js","webpack:///src/query.js","webpack:///src/relation.js","webpack:///src/role.js","webpack:///src/search.js","webpack:///src/status.js","webpack:///src/user.js","webpack:///src/index.js","webpack:///src/ua/comments-browser.js","webpack:///src/ua/index.js","webpack:///src/uploader/cos.js","webpack:///src/uploader/qiniu-browser.js","webpack:///src/uploader/s3.js","webpack:///src/utils/localstorage-browser.js","webpack:///src/utils/parse-base64-browser.js","webpack:///~/component-emitter/index.js","webpack:///~/crypt/crypt.js","webpack:///~/debug/src/debug.js","webpack:///~/es6-promise/dist/es6-promise.js","webpack:///~/is-buffer/index.js","webpack:///~/localstorage-memory/lib/localstorage-memory.js","webpack:///~/md5/md5.js","webpack:///~/ms/index.js","webpack:///~/superagent/lib/is-function.js","webpack:///~/superagent/lib/request-base.js","webpack:///~/superagent/lib/response-base.js","webpack:///~/superagent/lib/should-retry.js","webpack:///~/superagent/lib/utils.js"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","moduleId","installedModules","i","l","modules","call","m","c","value","d","name","getter","o","Object","defineProperty","configurable","enumerable","get","n","__esModule","object","property","prototype","hasOwnProperty","p","s","__WEBPACK_AMD_DEFINE_ARRAY__","__WEBPACK_AMD_DEFINE_RESULT__","createReduce","dir","iterator","obj","iteratee","memo","keys","index","length","currentKey","context","optimizeCb","isArrayLike","_","arguments","createPredicateIndexFinder","array","predicate","cb","getLength","createIndexFinder","predicateFind","sortedIndex","item","idx","Math","max","min","slice","isNaN","collectNonEnumProps","nonEnumIdx","nonEnumerableProps","constructor","proto","isFunction","ObjProto","prop","has","contains","push","previousUnderscore","ArrayProto","Array","FuncProto","Function","toString","nativeIsArray","isArray","nativeKeys","nativeBind","bind","nativeCreate","create","Ctor","_wrapped","VERSION","func","argCount","other","collection","accumulator","apply","identity","isObject","matcher","Infinity","createAssigner","keysFunc","undefinedOnly","source","key","baseCreate","result","MAX_ARRAY_INDEX","pow","each","forEach","map","collect","results","reduce","foldl","inject","reduceRight","foldr","find","detect","findIndex","findKey","filter","select","list","reject","negate","every","all","some","any","includes","include","fromIndex","guard","values","indexOf","invoke","method","args","isFunc","pluck","where","attrs","findWhere","computed","lastComputed","shuffle","rand","set","shuffled","random","sample","sortBy","criteria","sort","left","right","a","b","group","behavior","groupBy","indexBy","countBy","toArray","size","partition","pass","fail","first","head","take","initial","last","rest","tail","drop","compact","flatten","input","shallow","strict","startIndex","output","isArguments","j","len","without","difference","uniq","unique","isSorted","isBoolean","seen","union","intersection","argsLength","zip","unzip","findLastIndex","low","high","mid","floor","lastIndexOf","range","start","stop","step","ceil","executeBound","sourceFunc","boundFunc","callingContext","self","TypeError","bound","concat","partial","boundArgs","position","bindAll","Error","memoize","hasher","cache","address","delay","wait","setTimeout","defer","throttle","options","timeout","previous","later","leading","now","remaining","clearTimeout","trailing","debounce","immediate","timestamp","callNow","wrap","wrapper","compose","after","times","before","once","hasEnumBug","propertyIsEnumerable","allKeys","mapObject","pairs","invert","functions","methods","names","extend","extendOwn","assign","pick","oiteratee","omit","String","defaults","props","clone","tap","interceptor","isMatch","eq","aStack","bStack","className","areArrays","aCtor","bCtor","pop","isEqual","isEmpty","isString","isElement","nodeType","type","Int8Array","isFinite","parseFloat","isNumber","isNull","isUndefined","noConflict","constant","noop","propertyOf","matches","accum","Date","getTime","escapeMap","&","<",">","\"","'","`","unescapeMap","createEscaper","escaper","match","join","testRegexp","RegExp","replaceRegexp","string","test","replace","escape","unescape","fallback","idCounter","uniqueId","prefix","id","templateSettings","evaluate","interpolate","noMatch","escapes","\\","\r","\n","
","
","escapeChar","template","text","settings","oldSettings","offset","variable","render","e","data","argument","chain","instance","_chain","mixin","valueOf","toJSON","undefined","Promise","_continueWhile","asyncFunction","then","resolve","request","debug","md5","Cache","AVError","AV","getSessionToken","getServerURLPromise","API_HOST","cn","us","sign","isMasterKey","signature","requestsCount","ajax","resourceUrl","headers","onprogress","count","req","send","on","end","err","res","status","body","header","statusCode","responseText","response","setAppKey","signKey","applicationKey","setHeaders","authOptions","X-LC-Id","applicationId","Content-Type","useMasterKey","_useMasterKey","masterKey","console","warn","hookKey","_config","applicationProduction","userAgent","sessionToken","disableCurrentUser","User","currentAsync","currentUser","_sessionToken","createApiUrl","route","objectId","dataObject","serverURL","APIServerURL","apiURL","charAt","_fetchWhenSave","_where","encodeURIComponent","JSON","stringify","toLowerCase","k","_typeof","cacheServerURL","ttl","setAsync","handleError","error","api_server","location","catch","errorJSON","code","message","parse","setServerUrl","newRegion","region","refreshServerUrlByRouter","url","servers","setServerUrlByRegion","getAsync","AVRequest","OTHER_CAUSE","INTERNAL_SERVER_ERROR","CONNECTION_FAILED","OBJECT_NOT_FOUND","INVALID_QUERY","INVALID_CLASS_NAME","MISSING_OBJECT_ID","INVALID_KEY_NAME","INVALID_POINTER","INVALID_JSON","COMMAND_UNAVAILABLE","NOT_INITIALIZED","INCORRECT_TYPE","INVALID_CHANNEL_NAME","PUSH_MISCONFIGURED","OBJECT_TOO_LARGE","OPERATION_FORBIDDEN","CACHE_MISS","INVALID_NESTED_KEY","INVALID_FILE_NAME","INVALID_ACL","TIMEOUT","INVALID_EMAIL_ADDRESS","MISSING_CONTENT_TYPE","MISSING_CONTENT_LENGTH","INVALID_CONTENT_LENGTH","FILE_TOO_LARGE","FILE_SAVE_ERROR","FILE_DELETE_ERROR","DUPLICATE_VALUE","INVALID_ROLE_NAME","EXCEEDED_QUOTA","SCRIPT_FAILED","VALIDATION_ERROR","INVALID_IMAGE_DATA","UNSAVED_FILE_ERROR","INVALID_PUSH_TIME_ERROR","USERNAME_MISSING","PASSWORD_MISSING","USERNAME_TAKEN","EMAIL_TAKEN","EMAIL_MISSING","EMAIL_NOT_FOUND","SESSION_MISSING","MUST_CREATE_USER_THROUGH_SIGNUP","ACCOUNT_ALREADY_LINKED","LINKED_ID_MISSING","INVALID_LINKED_SESSION","UNSUPPORTED_SERVICE","X_DOMAIN_REQUEST","isNullOrUndefined","x","ensureArray","target","user","useColors","window","process","document","documentElement","style","firebug","exception","table","navigator","parseInt","$1","formatArgs","namespace","humanize","diff","color","splice","lastC","log","save","namespaces","storage","removeItem","load","r","env","DEBUG","localstorage","localStorage","chrome","local","colors","formatters","v","enable","global","AVConfig","EmptyConstructor","inherits","parent","protoProps","staticProps","child","__super__","setProduction","production","_getAVPath","path","substring","_installationId","_getInstallationId","getItemAsync","hexOctet","setItemAsync","_parseDate","iso8601","regexp","exec","year","month","day","hour","minute","second","milli","UTC","_extend","classProps","_getValue","_encode","seenObjects","disallowObjects","_hasData","_toPointer","dirty","_toFullJSON","ACL","isDate","__type","iso","GeoPoint","isRegExp","Relation","Op","File","_decode","__op","pointer","_create","_finishFetch","latitude","longitude","relation","targetClassName","file","_encodeObjectOrArray","encodeAVObject","_arrayEach","_traverse","attributes","newChild","_each","_objectEach","callback","serialize","pushEncodedKeyValuePair","val","subkey","parseString","str","pair","pos","split","decodeURIComponent","parseHeader","line","field","lines","fields","trim","isJSON","mime","Response","xhr","responseType","statusText","_setStatusProperties","getAllResponseHeaders","getResponseHeader","_setHeaderProperties","_responseType","_parseBody","Request","_query","_header","original","rawResponse","emit","new_err","_isResponseOK","del","fn","Emitter","RequestBase","ResponseBase","shouldRetry","getXHR","XMLHttpRequest","protocol","ActiveXObject","serializeObject","types","html","json","xml","urlencoded","form","form-data","application/x-www-form-urlencoded","application/json","_parser","toError","msg","accept","auth","btoa","username","password","query","attach","_data","_getFormData","append","_formData","FormData","_maxRetries","_retries","_retry","_callback","retries","crossDomainError","crossDomain","buffer","ca","agent","pipe","write","_appendQueryString","_sort","queryArr","_isHost","_endCalled","_end","_setTimeouts","onreadystatechange","readyState","_responseTimeoutTimer","timedout","_aborted","handleProgress","direction","total","percent","loaded","hasListeners","upload","open","_withCredentials","withCredentials","contentType","_serializer","setRequestHeader","patch","post","put","g","eval","removeAsync","removeItemAsync","getCacheData","cacheData","expired","expiredAt","syncApiNames","async","apiName","charenc","utf8","stringToBytes","bin","bytesToString","bytes","charCodeAt","fromCharCode","PUBLIC_KEY","arg1","permissionsById","setReadAccess","setWriteAccess","accessList","userId","allowed","permission","_setAccess","accessType","Role","getName","permissions","_getAccess","getReadAccess","getWriteAccess","setPublicReadAccess","getPublicReadAccess","setPublicWriteAccess","getPublicWriteAccess","getRoleReadAccess","role","getRoleWriteAccess","setRoleReadAccess","setRoleWriteAccess","Cloud","run","resp","rpc","getServerDate","requestSmsCode","mobilePhoneNumber","verifySmsCode","phone","params","eventSplitter","Events","events","calls","event","node","_callbacks","shift","next","off","ctx","trigger","unbind","cos","qiniu","s3","parseBase64","extname","b64Digit","number","encodeBase64","chunks","b1","b2","b3","has2","has3","mimeType","metaData","base64","_extName","owner","current","withURL","__source","createWithoutData","_this","_operations","getACL","_acl","setACL","acl","attrName","_this2","_len","_key","attr","thumbnailURL","width","height","quality","scaleToFit","fmt","mode","ownerId","destroy","_fileToken","extName","mime_type","_qiniu_key","_this3","_previousSave","uploadInfo","_token","token","blob","Buffer","isBuffer","uploadPromise","provider","success","fetch","bucket","arg2","_validate","__defineGetter__","__defineSetter__","_latitude","_longitude","geolocation","getCurrentPosition","coords","radiansTo","point","d2r","PI","lat1rad","long1rad","lat2rad","long2rad","deltaLat","deltaLong","sinDeltaLatDiv2","sin","sinDeltaLongDiv2","asin","sqrt","kilometersTo","milesTo","initialize","appId","appKey","masterKeyWarn","init","Insight","startJob","jobConfig","sql","JobQuery","_skip","_limit","skip","limit","utils","RESERVED_KEYS","checkReservedKey","_mergeMagicFields","_serverData","_opSetQueue","_flags","_hashedJSON","_escapedAttributes","cid","changed","_silent","_pending","silent","_previousAttributes","saveAll","_deepSaveAsync","fetchAll","objects","requests","fetchWhenSave","getObjectId","getCreatedAt","createdAt","getUpdatedAt","updatedAt","_refreshCache","_refreshingCache","_resetCacheForKey","Set","currentChanges","_ensureParentAndKey","escaped","model","specialFields","_startSave","_cancelSave","failedChanges","nextChanges","op","op1","op2","_mergeWithPrevious","_saving","_finishSave","serverData","fetchedObjects","savedChanges","_applyOpSet","fetched","_rebuildAllEstimatedData","hasData","opSet","change","_estimate","_UNSET","wasSet","_rebuildEstimatedDataForKey","previousAttributes","oldValue","newValue","unset","unused_value","Unset","dataToValidate","changes","isRealChange","increment","amount","Increment","add","Add","addUnique","AddUnique","remove","Remove","clear","keysToClear","_getSaveJSON","_canBeSerialized","_canBeSerializedAsValue","fetchOptions","arg3","setOptions","unsavedChildren","unsavedFiles","_findUnsavedChildren","_allPreviousSaves","queryJSON","makeRequest","_makeRequest","serverAttrs","triggerDestroy","isNew","changing","_changing","deleteChanged","hasChanged","changedAttributes","old","diffVal","isValid","validate","disableBeforeHook","ignoreHook","disableAfterHook","hookName","trace","__ignore_hooks","destroyAll","objectsByClassNameAndFlags","flags","ids","_getSubclass","ObjectClass","_classMap","noDefaultACL","NewClassObject","OldClassObject","_className","arg0","newArguments","_LCClassName","register","klass","children","files","canBeSerializedAsValue","promise","batch","newRemaining","readyToStart","bathSavePromise","_initialize","_opDecoderMap","_registerDecoder","opName","decoder","ops","nextOp","_value","_amount","_objects","matchingObj","anObj","adds","removes","_targetClassName","pointerToId","relationsToAdd","relationsToRemove","added","removed","idToPointer","pointers","newAdd","newRemove","newRelation","Installation","Push","cql","push_time","expiration_time","expiration_time_interval","requires","Query","objectClass","_include","_select","_extraOptions","or","queries","q","_orQuery","and","_andQuery","doCloudQuery","pvalues","_newObject","_processResult","errorObject","_order","order","_createRequest","_parseResponse","scan","_ref","orderedBy","batchSize","condition","scan_key","cursor","done","remainResults","equalTo","_addCondition","sizeEqualTo","notEqualTo","lessThan","greaterThan","lessThanOrEqualTo","greaterThanOrEqualTo","containedIn","notContainedIn","containsAll","exists","doesNotExist","regex","modifiers","ignoreCase","multiline","matchesQuery","doesNotMatchQuery","matchesKeyInQuery","queryKey","doesNotMatchKeyInQuery","$or","$and","_quote","startsWith","endsWith","ascending","addAscending","descending","addDescending","near","withinRadians","distance","withinMiles","withinKilometers","withinGeoBox","southwest","northeast","$box","_this4","finished","callbacksDone","FriendShipQuery","_objectClass","_friendshipTag","reverseQuery","parentClass","relationKey","targetClass","redirectClassNameForKey","setName","defaultAcl","getUsers","getRoles","newName","SearchSortBuilder","_sortFields","_addField","missing","whereNear","geo","lat","lon","unit","build","SearchQuery","_sid","_hits","_queryString","_highlights","_sortBuilder","sid","queryString","highlights","builder","hits","hasMore","_hitEnd","reset","_oldSid","appURL","clazz","getUser","currUser","_fetchUserBySessionToken","getUserPointer","Status","imageUrl","inboxType","image","toObject","_getDataJSON","sendStatusToFollowers","messageId","sendPrivateStatus","userObjectId","countUnreadStatuses","resetUnreadCount","statusQuery","InboxQuery","_sinceId","_maxId","_inboxType","_owner","sinceId","maxId","inboxQuery","getWeappLoginCode","wx","login","errMsg","_isCurrentUser","_cleanupAuthData","isCurrent","authData","_synchronizeAllAuthData","_synchronizeAuthData","authType","_authProviders","getAuthType","restoreAuthentication","_unlinkFrom","_handleSaveResult","makeCurrent","_saveCurrentUser","_linkWith","authenticate","linkWithWeapp","_isLinked","logOut","_logOutWithAll","_logOutWith","deauthenticate","signUp","signUpOrlogInWithMobilePhone","smsCode","logIn","follow","unfollow","followerQuery","followeeQuery","updatePassword","oldPassword","newPassword","old_password","new_password","getUsername","getMobilePhoneNumber","setMobilePhoneNumber","setUsername","setPassword","getEmail","setEmail","email","authenticated","isAuthenticated","refreshSessionToken","_this5","_currentUser","_currentUserMatchesDisk","_CURRENT_USER_KEY","become","session_token","logInWithMobilePhoneSmsCode","mobilePhone","logInWithMobilePhone","signUpOrlogInWithAuthData","platform","_logInWith","loginWithWeapp","_this6","associateWithAuthData","userObj","requestPasswordReset","requestEmailVerify","requestMobilePhoneVerify","requestPasswordResetBySmsCode","resetPasswordBySmsCode","verifyMobilePhone","requestLoginSmsCode","userData","_id","getItem","_registerAuthenticationProvider","version","comments","saveOptions","_bucket","uploadUrl","upload_url","uptoken","Storage","apiNames","testKey","setItem","dataURItoBlob","dataURI","byteString","atob","ia","Uint8Array","Blob","addEventListener","removeListener","removeAllListeners","removeEventListener","callbacks","listeners","base64map","crypt","rotl","rotr","endian","Number","randomBytes","bytesToWords","words","wordsToBytes","bytesToHex","hex","hexToBytes","substr","bytesToBase64","triplet","base64ToBytes","imod4","selectColor","hash","abs","createDebug","enabled","curr","ms","prevTime","prev","coerce","unshift","format","formatter","logFn","skips","disable","stack","objectOrFunction","setScheduler","scheduleFn","customSchedulerFn","setAsap","asapFn","asap","useNextTick","nextTick","flush","useVertxTimer","vertxNext","useSetTimeout","useMutationObserver","iterations","observer","BrowserMutationObserver","createTextNode","observe","characterData","useMessageChannel","channel","MessageChannel","port1","onmessage","port2","postMessage","globalSetTimeout","queue","arg","attemptVertx","vertx","runOnLoop","runOnContext","onFulfillment","onRejection","_arguments","PROMISE_ID","makePromise","_state","invokeCallback","_result","subscribe","Constructor","_resolve","selfFulfillment","cannotReturnOwn","getThen","GET_THEN_ERROR","tryThen","fulfillmentHandler","rejectionHandler","handleForeignThenable","thenable","sealed","fulfill","reason","_reject","_label","handleOwnThenable","FULFILLED","REJECTED","handleMaybeThenable","maybeThenable","then$$","publishRejection","_onerror","publish","PENDING","_subscribers","subscribers","settled","detail","ErrorObject","tryCatch","TRY_CATCH_ERROR","hasCallback","succeeded","failed","initializePromise","resolver","nextId","Enumerator","_instanceConstructor","_input","_remaining","_enumerate","validationError","entries","race","needsResolver","needsNew","polyfill","P","promiseToString","cast","_isArray","scheduleFlush","browserWindow","browserGlobal","MutationObserver","WebKitMutationObserver","isNode","isWorker","Uint8ClampedArray","importScripts","_eachEntry","entry","resolve$$","_then","_settledAt","_willSettleAt","state","enumerator","_setScheduler","_setAsap","_asap","isSlowBuffer","readFloatLE","_isBuffer","localStorageMemory","encoding","FF","_ff","GG","_gg","HH","_hh","II","_ii","aa","bb","cc","dd","t","_blocksize","_digestsize","digestbytes","asBytes","asString","y","h","fmtShort","round","fmtLong","plural","long","tag","_timer","_timeout","_responseTimeout","option","deadline","retry","_fullfilledPromise","innerResolve","innerReject","use","ok","_okCallback","getHeader","abort","redirects","_maxRedirects","isObj","sortQuery","_timeoutError","errno","ct","links","link","parseLinks","statusType","info","redirect","clientError","serverError","accepted","noContent","badRequest","unauthorized","notAc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,SAAAmY,EAAAC,GACA,SAAAD,GAAAA,EAAAwD,OAAAijC,EAAAl2C,QAAAyP,EAAAwD,YACAvD,GAAAA,EAAAC,QAAAD,EAAAC,QAAA,UAEAF,GAAA,WAAAA,IAAA,gBAAAA,EAAAwD,UACAxD,GAAA,eAAAA,sBCXAnY,EAAAkS,KAAA,SAAA0U,GACA,MAAAA,GAAAG,MAAA,SAAuBqK,SAWvBpxB,EAAA4wB,OAAA,SAAAhK,GACA,MAAAA,GAAAG,MAAA,SAAuB5f,OAAA,SAAA9E,EAAAukB,GACvB,GAAAi4B,GAAAj4B,EAAAG,MAAA,SACAtgB,EAAAo4C,EAAAztB,QACA3K,EAAAo4B,EAAAztB,OAGA,OADA3qB,IAAAggB,IAAApkB,EAAAoE,GAAAggB,GACApkB,QAYArC,EAAA+9C,WAAA,SAAAn3B,GACA,MAAAA,GAAAG,MAAA,SAAA5f,OAAA,SAAA9E,EAAAukB,GACA,GAAAi4B,GAAAj4B,EAAAG,MAAA,SACA7K,EAAA2iC,EAAA,GAAA/6C,MAAA,GAAA,GACAg7C,EAAAD,EAAA,GAAA93B,MAAA,SAAA,GAAAjjB,MAAA,GAAA,EAEA,OADAzB,GAAAy8C,GAAA5iC,EACA7Z,QAYArC,EAAA++C,YAAA,SAAAxmC,EAAAymC,GAQA,aAPAzmC,GAAA,sBACAA,GAAA,wBACAA,GAAA,2BACAA,GAAA,KACAymC,SACAzmC,GAAA,OAEAA","file":"av-min.js","sourceRoot":"","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"AV\"] = factory();\n\telse\n\t\troot[\"AV\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// identity function for calling harmony imports with the correct context\n \t__webpack_require__.i = function(value) { return value; };\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 30);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap fda3052434ab8851837a","// Underscore.js 1.8.3\n// http://underscorejs.org\n// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n// Underscore may be freely distributed under the MIT license.\n\n(function() {\n\n // Baseline setup\n // --------------\n\n // Establish the root object, `window` in the browser, or `exports` on the server.\n var root = this;\n\n // Save the previous value of the `_` variable.\n var previousUnderscore = root._;\n\n // Save bytes in the minified (but not gzipped) version:\n var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;\n\n // Create quick reference variables for speed access to core prototypes.\n var\n push = ArrayProto.push,\n slice = ArrayProto.slice,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty;\n\n // All **ECMAScript 5** native function implementations that we hope to use\n // are declared here.\n var\n nativeIsArray = Array.isArray,\n nativeKeys = Object.keys,\n nativeBind = FuncProto.bind,\n nativeCreate = Object.create;\n\n // Naked function reference for surrogate-prototype-swapping.\n var Ctor = function(){};\n\n // Create a safe reference to the Underscore object for use below.\n var _ = function(obj) {\n if (obj instanceof _) return obj;\n if (!(this instanceof _)) return new _(obj);\n this._wrapped = obj;\n };\n\n // Export the Underscore object for **Node.js**, with\n // backwards-compatibility for the old `require()` API. If we're in\n // the browser, add `_` as a global object.\n if (typeof exports !== 'undefined') {\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = _;\n }\n exports._ = _;\n } else {\n root._ = _;\n }\n\n // Current version.\n _.VERSION = '1.8.3';\n\n // Internal function that returns an efficient (for current engines) version\n // of the passed-in callback, to be repeatedly applied in other Underscore\n // functions.\n var optimizeCb = function(func, context, argCount) {\n if (context === void 0) return func;\n switch (argCount == null ? 3 : argCount) {\n case 1: return function(value) {\n return func.call(context, value);\n };\n case 2: return function(value, other) {\n return func.call(context, value, other);\n };\n case 3: return function(value, index, collection) {\n return func.call(context, value, index, collection);\n };\n case 4: return function(accumulator, value, index, collection) {\n return func.call(context, accumulator, value, index, collection);\n };\n }\n return function() {\n return func.apply(context, arguments);\n };\n };\n\n // A mostly-internal function to generate callbacks that can be applied\n // to each element in a collection, returning the desired result — either\n // identity, an arbitrary callback, a property matcher, or a property accessor.\n var cb = function(value, context, argCount) {\n if (value == null) return _.identity;\n if (_.isFunction(value)) return optimizeCb(value, context, argCount);\n if (_.isObject(value)) return _.matcher(value);\n return _.property(value);\n };\n _.iteratee = function(value, context) {\n return cb(value, context, Infinity);\n };\n\n // An internal function for creating assigner functions.\n var createAssigner = function(keysFunc, undefinedOnly) {\n return function(obj) {\n var length = arguments.length;\n if (length < 2 || obj == null) return obj;\n for (var index = 1; index < length; index++) {\n var source = arguments[index],\n keys = keysFunc(source),\n l = keys.length;\n for (var i = 0; i < l; i++) {\n var key = keys[i];\n if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];\n }\n }\n return obj;\n };\n };\n\n // An internal function for creating a new object that inherits from another.\n var baseCreate = function(prototype) {\n if (!_.isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n };\n\n var property = function(key) {\n return function(obj) {\n return obj == null ? void 0 : obj[key];\n };\n };\n\n // Helper for collection methods to determine whether a collection\n // should be iterated as an array or as an object\n // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength\n // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094\n var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;\n var getLength = property('length');\n var isArrayLike = function(collection) {\n var length = getLength(collection);\n return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;\n };\n\n // Collection Functions\n // --------------------\n\n // The cornerstone, an `each` implementation, aka `forEach`.\n // Handles raw objects in addition to array-likes. Treats all\n // sparse array-likes as if they were dense.\n _.each = _.forEach = function(obj, iteratee, context) {\n iteratee = optimizeCb(iteratee, context);\n var i, length;\n if (isArrayLike(obj)) {\n for (i = 0, length = obj.length; i < length; i++) {\n iteratee(obj[i], i, obj);\n }\n } else {\n var keys = _.keys(obj);\n for (i = 0, length = keys.length; i < length; i++) {\n iteratee(obj[keys[i]], keys[i], obj);\n }\n }\n return obj;\n };\n\n // Return the results of applying the iteratee to each element.\n _.map = _.collect = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n results = Array(length);\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n results[index] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Create a reducing function iterating left or right.\n function createReduce(dir) {\n // Optimized iterator function as using arguments.length\n // in the main function will deoptimize the, see #1991.\n function iterator(obj, iteratee, memo, keys, index, length) {\n for (; index >= 0 && index < length; index += dir) {\n var currentKey = keys ? keys[index] : index;\n memo = iteratee(memo, obj[currentKey], currentKey, obj);\n }\n return memo;\n }\n\n return function(obj, iteratee, memo, context) {\n iteratee = optimizeCb(iteratee, context, 4);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n index = dir > 0 ? 0 : length - 1;\n // Determine the initial value if none is provided.\n if (arguments.length < 3) {\n memo = obj[keys ? keys[index] : index];\n index += dir;\n }\n return iterator(obj, iteratee, memo, keys, index, length);\n };\n }\n\n // **Reduce** builds up a single result from a list of values, aka `inject`,\n // or `foldl`.\n _.reduce = _.foldl = _.inject = createReduce(1);\n\n // The right-associative version of reduce, also known as `foldr`.\n _.reduceRight = _.foldr = createReduce(-1);\n\n // Return the first value which passes a truth test. Aliased as `detect`.\n _.find = _.detect = function(obj, predicate, context) {\n var key;\n if (isArrayLike(obj)) {\n key = _.findIndex(obj, predicate, context);\n } else {\n key = _.findKey(obj, predicate, context);\n }\n if (key !== void 0 && key !== -1) return obj[key];\n };\n\n // Return all the elements that pass a truth test.\n // Aliased as `select`.\n _.filter = _.select = function(obj, predicate, context) {\n var results = [];\n predicate = cb(predicate, context);\n _.each(obj, function(value, index, list) {\n if (predicate(value, index, list)) results.push(value);\n });\n return results;\n };\n\n // Return all the elements for which a truth test fails.\n _.reject = function(obj, predicate, context) {\n return _.filter(obj, _.negate(cb(predicate)), context);\n };\n\n // Determine whether all of the elements match a truth test.\n // Aliased as `all`.\n _.every = _.all = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (!predicate(obj[currentKey], currentKey, obj)) return false;\n }\n return true;\n };\n\n // Determine if at least one element in the object matches a truth test.\n // Aliased as `any`.\n _.some = _.any = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (predicate(obj[currentKey], currentKey, obj)) return true;\n }\n return false;\n };\n\n // Determine if the array or object contains a given item (using `===`).\n // Aliased as `includes` and `include`.\n _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n if (typeof fromIndex != 'number' || guard) fromIndex = 0;\n return _.indexOf(obj, item, fromIndex) >= 0;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n var isFunc = _.isFunction(method);\n return _.map(obj, function(value) {\n var func = isFunc ? method : value[method];\n return func == null ? func : func.apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, _.property(key));\n };\n\n // Convenience version of a common use case of `filter`: selecting only objects\n // containing specific `key:value` pairs.\n _.where = function(obj, attrs) {\n return _.filter(obj, _.matcher(attrs));\n };\n\n // Convenience version of a common use case of `find`: getting the first object\n // containing specific `key:value` pairs.\n _.findWhere = function(obj, attrs) {\n return _.find(obj, _.matcher(attrs));\n };\n\n // Return the maximum element (or element-based computation).\n _.max = function(obj, iteratee, context) {\n var result = -Infinity, lastComputed = -Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value > result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed > lastComputed || computed === -Infinity && result === -Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iteratee, context) {\n var result = Infinity, lastComputed = Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value < result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed < lastComputed || computed === Infinity && result === Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Shuffle a collection, using the modern version of the\n // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).\n _.shuffle = function(obj) {\n var set = isArrayLike(obj) ? obj : _.values(obj);\n var length = set.length;\n var shuffled = Array(length);\n for (var index = 0, rand; index < length; index++) {\n rand = _.random(0, index);\n if (rand !== index) shuffled[index] = shuffled[rand];\n shuffled[rand] = set[index];\n }\n return shuffled;\n };\n\n // Sample **n** random values from a collection.\n // If **n** is not specified, returns a single random element.\n // The internal `guard` argument allows it to work with `map`.\n _.sample = function(obj, n, guard) {\n if (n == null || guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n return obj[_.random(obj.length - 1)];\n }\n return _.shuffle(obj).slice(0, Math.max(0, n));\n };\n\n // Sort the object's values by a criterion produced by an iteratee.\n _.sortBy = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value: value,\n index: index,\n criteria: iteratee(value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria;\n var b = right.criteria;\n if (a !== b) {\n if (a > b || a === void 0) return 1;\n if (a < b || b === void 0) return -1;\n }\n return left.index - right.index;\n }), 'value');\n };\n\n // An internal function used for aggregate \"group by\" operations.\n var group = function(behavior) {\n return function(obj, iteratee, context) {\n var result = {};\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index) {\n var key = iteratee(value, index, obj);\n behavior(result, value, key);\n });\n return result;\n };\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key].push(value); else result[key] = [value];\n });\n\n // Indexes the object's values by a criterion, similar to `groupBy`, but for\n // when you know that your index values will be unique.\n _.indexBy = group(function(result, value, key) {\n result[key] = value;\n });\n\n // Counts instances of an object that group by a certain criterion. Pass\n // either a string attribute to count by, or a function that returns the\n // criterion.\n _.countBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key]++; else result[key] = 1;\n });\n\n // Safely create a real, live array from anything iterable.\n _.toArray = function(obj) {\n if (!obj) return [];\n if (_.isArray(obj)) return slice.call(obj);\n if (isArrayLike(obj)) return _.map(obj, _.identity);\n return _.values(obj);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n if (obj == null) return 0;\n return isArrayLike(obj) ? obj.length : _.keys(obj).length;\n };\n\n // Split a collection into two arrays: one whose elements all satisfy the given\n // predicate, and one whose elements all do not satisfy the predicate.\n _.partition = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var pass = [], fail = [];\n _.each(obj, function(value, key, obj) {\n (predicate(value, key, obj) ? pass : fail).push(value);\n });\n return [pass, fail];\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head` and `take`. The **guard** check\n // allows it to work with `_.map`.\n _.first = _.head = _.take = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[0];\n return _.initial(array, array.length - n);\n };\n\n // Returns everything but the last entry of the array. Especially useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array.\n _.last = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[array.length - 1];\n return _.rest(array, Math.max(0, array.length - n));\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.\n // Especially useful on the arguments object. Passing an **n** will return\n // the rest N values in the array.\n _.rest = _.tail = _.drop = function(array, n, guard) {\n return slice.call(array, n == null || guard ? 1 : n);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, _.identity);\n };\n\n // Internal implementation of a recursive `flatten` function.\n var flatten = function(input, shallow, strict, startIndex) {\n var output = [], idx = 0;\n for (var i = startIndex || 0, length = getLength(input); i < length; i++) {\n var value = input[i];\n if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {\n //flatten current level of array or arguments object\n if (!shallow) value = flatten(value, shallow, strict);\n var j = 0, len = value.length;\n output.length += len;\n while (j < len) {\n output[idx++] = value[j++];\n }\n } else if (!strict) {\n output[idx++] = value;\n }\n }\n return output;\n };\n\n // Flatten out an array, either recursively (by default), or just one level.\n _.flatten = function(array, shallow) {\n return flatten(array, shallow, false);\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iteratee, context) {\n if (!_.isBoolean(isSorted)) {\n context = iteratee;\n iteratee = isSorted;\n isSorted = false;\n }\n if (iteratee != null) iteratee = cb(iteratee, context);\n var result = [];\n var seen = [];\n for (var i = 0, length = getLength(array); i < length; i++) {\n var value = array[i],\n computed = iteratee ? iteratee(value, i, array) : value;\n if (isSorted) {\n if (!i || seen !== computed) result.push(value);\n seen = computed;\n } else if (iteratee) {\n if (!_.contains(seen, computed)) {\n seen.push(computed);\n result.push(value);\n }\n } else if (!_.contains(result, value)) {\n result.push(value);\n }\n }\n return result;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(flatten(arguments, true, true));\n };\n\n // Produce an array that contains every item shared between all the\n // passed-in arrays.\n _.intersection = function(array) {\n var result = [];\n var argsLength = arguments.length;\n for (var i = 0, length = getLength(array); i < length; i++) {\n var item = array[i];\n if (_.contains(result, item)) continue;\n for (var j = 1; j < argsLength; j++) {\n if (!_.contains(arguments[j], item)) break;\n }\n if (j === argsLength) result.push(item);\n }\n return result;\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = flatten(arguments, true, true, 1);\n return _.filter(array, function(value){\n return !_.contains(rest, value);\n });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function() {\n return _.unzip(arguments);\n };\n\n // Complement of _.zip. Unzip accepts an array of arrays and groups\n // each array's elements on shared indices\n _.unzip = function(array) {\n var length = array && _.max(array, getLength).length || 0;\n var result = Array(length);\n\n for (var index = 0; index < length; index++) {\n result[index] = _.pluck(array, index);\n }\n return result;\n };\n\n // Converts lists into objects. Pass either a single array of `[key, value]`\n // pairs, or two parallel arrays of the same length -- one of keys, and one of\n // the corresponding values.\n _.object = function(list, values) {\n var result = {};\n for (var i = 0, length = getLength(list); i < length; i++) {\n if (values) {\n result[list[i]] = values[i];\n } else {\n result[list[i][0]] = list[i][1];\n }\n }\n return result;\n };\n\n // Generator function to create the findIndex and findLastIndex functions\n function createPredicateIndexFinder(dir) {\n return function(array, predicate, context) {\n predicate = cb(predicate, context);\n var length = getLength(array);\n var index = dir > 0 ? 0 : length - 1;\n for (; index >= 0 && index < length; index += dir) {\n if (predicate(array[index], index, array)) return index;\n }\n return -1;\n };\n }\n\n // Returns the first index on an array-like that passes a predicate test\n _.findIndex = createPredicateIndexFinder(1);\n _.findLastIndex = createPredicateIndexFinder(-1);\n\n // Use a comparator function to figure out the smallest index at which\n // an object should be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iteratee, context) {\n iteratee = cb(iteratee, context, 1);\n var value = iteratee(obj);\n var low = 0, high = getLength(array);\n while (low < high) {\n var mid = Math.floor((low + high) / 2);\n if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;\n }\n return low;\n };\n\n // Generator function to create the indexOf and lastIndexOf functions\n function createIndexFinder(dir, predicateFind, sortedIndex) {\n return function(array, item, idx) {\n var i = 0, length = getLength(array);\n if (typeof idx == 'number') {\n if (dir > 0) {\n i = idx >= 0 ? idx : Math.max(idx + length, i);\n } else {\n length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;\n }\n } else if (sortedIndex && idx && length) {\n idx = sortedIndex(array, item);\n return array[idx] === item ? idx : -1;\n }\n if (item !== item) {\n idx = predicateFind(slice.call(array, i, length), _.isNaN);\n return idx >= 0 ? idx + i : -1;\n }\n for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {\n if (array[idx] === item) return idx;\n }\n return -1;\n };\n }\n\n // Return the position of the first occurrence of an item in an array,\n // or -1 if the item is not included in the array.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);\n _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (stop == null) {\n stop = start || 0;\n start = 0;\n }\n step = step || 1;\n\n var length = Math.max(Math.ceil((stop - start) / step), 0);\n var range = Array(length);\n\n for (var idx = 0; idx < length; idx++, start += step) {\n range[idx] = start;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Determines whether to execute a function as a constructor\n // or a normal function with the provided arguments\n var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {\n if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);\n var self = baseCreate(sourceFunc.prototype);\n var result = sourceFunc.apply(self, args);\n if (_.isObject(result)) return result;\n return self;\n };\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if\n // available.\n _.bind = function(func, context) {\n if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');\n var args = slice.call(arguments, 2);\n var bound = function() {\n return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));\n };\n return bound;\n };\n\n // Partially apply a function by creating a version that has had some of its\n // arguments pre-filled, without changing its dynamic `this` context. _ acts\n // as a placeholder, allowing any combination of arguments to be pre-filled.\n _.partial = function(func) {\n var boundArgs = slice.call(arguments, 1);\n var bound = function() {\n var position = 0, length = boundArgs.length;\n var args = Array(length);\n for (var i = 0; i < length; i++) {\n args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];\n }\n while (position < arguments.length) args.push(arguments[position++]);\n return executeBound(func, bound, this, this, args);\n };\n return bound;\n };\n\n // Bind a number of an object's methods to that object. Remaining arguments\n // are the method names to be bound. Useful for ensuring that all callbacks\n // defined on an object belong to it.\n _.bindAll = function(obj) {\n var i, length = arguments.length, key;\n if (length <= 1) throw new Error('bindAll must be passed function names');\n for (i = 1; i < length; i++) {\n key = arguments[i];\n obj[key] = _.bind(obj[key], obj);\n }\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memoize = function(key) {\n var cache = memoize.cache;\n var address = '' + (hasher ? hasher.apply(this, arguments) : key);\n if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);\n return cache[address];\n };\n memoize.cache = {};\n return memoize;\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){\n return func.apply(null, args);\n }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack has\n // cleared.\n _.defer = _.partial(_.delay, _, 1);\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time. Normally, the throttled function will run\n // as much as it can, without ever going more than once per `wait` duration;\n // but if you'd like to disable the execution on the leading edge, pass\n // `{leading: false}`. To disable execution on the trailing edge, ditto.\n _.throttle = function(func, wait, options) {\n var context, args, result;\n var timeout = null;\n var previous = 0;\n if (!options) options = {};\n var later = function() {\n previous = options.leading === false ? 0 : _.now();\n timeout = null;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n };\n return function() {\n var now = _.now();\n if (!previous && options.leading === false) previous = now;\n var remaining = wait - (now - previous);\n context = this;\n args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(later, remaining);\n }\n return result;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being called for\n // N milliseconds. If `immediate` is passed, trigger the function on the\n // leading edge, instead of the trailing.\n _.debounce = function(func, wait, immediate) {\n var timeout, args, context, timestamp, result;\n\n var later = function() {\n var last = _.now() - timestamp;\n\n if (last < wait && last >= 0) {\n timeout = setTimeout(later, wait - last);\n } else {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n }\n }\n };\n\n return function() {\n context = this;\n args = arguments;\n timestamp = _.now();\n var callNow = immediate && !timeout;\n if (!timeout) timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n context = args = null;\n }\n\n return result;\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return _.partial(wrapper, func);\n };\n\n // Returns a negated version of the passed-in predicate.\n _.negate = function(predicate) {\n return function() {\n return !predicate.apply(this, arguments);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var args = arguments;\n var start = args.length - 1;\n return function() {\n var i = start;\n var result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n };\n\n // Returns a function that will only be executed on and after the Nth call.\n _.after = function(times, func) {\n return function() {\n if (--times < 1) {\n return func.apply(this, arguments);\n }\n };\n };\n\n // Returns a function that will only be executed up to (but not including) the Nth call.\n _.before = function(times, func) {\n var memo;\n return function() {\n if (--times > 0) {\n memo = func.apply(this, arguments);\n }\n if (times <= 1) func = null;\n return memo;\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = _.partial(_.before, 2);\n\n // Object Functions\n // ----------------\n\n // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.\n var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n function collectNonEnumProps(obj, keys) {\n var nonEnumIdx = nonEnumerableProps.length;\n var constructor = obj.constructor;\n var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;\n\n // Constructor is a special case.\n var prop = 'constructor';\n if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);\n\n while (nonEnumIdx--) {\n prop = nonEnumerableProps[nonEnumIdx];\n if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {\n keys.push(prop);\n }\n }\n }\n\n // Retrieve the names of an object's own properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = function(obj) {\n if (!_.isObject(obj)) return [];\n if (nativeKeys) return nativeKeys(obj);\n var keys = [];\n for (var key in obj) if (_.has(obj, key)) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve all the property names of an object.\n _.allKeys = function(obj) {\n if (!_.isObject(obj)) return [];\n var keys = [];\n for (var key in obj) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var values = Array(length);\n for (var i = 0; i < length; i++) {\n values[i] = obj[keys[i]];\n }\n return values;\n };\n\n // Returns the results of applying the iteratee to each element of the object\n // In contrast to _.map it returns an object\n _.mapObject = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = _.keys(obj),\n length = keys.length,\n results = {},\n currentKey;\n for (var index = 0; index < length; index++) {\n currentKey = keys[index];\n results[currentKey] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Convert an object into a list of `[key, value]` pairs.\n _.pairs = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var pairs = Array(length);\n for (var i = 0; i < length; i++) {\n pairs[i] = [keys[i], obj[keys[i]]];\n }\n return pairs;\n };\n\n // Invert the keys and values of an object. The values must be serializable.\n _.invert = function(obj) {\n var result = {};\n var keys = _.keys(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n result[obj[keys[i]]] = keys[i];\n }\n return result;\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = createAssigner(_.allKeys);\n\n // Assigns a given object with all the own properties in the passed-in object(s)\n // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n _.extendOwn = _.assign = createAssigner(_.keys);\n\n // Returns the first key on an object that passes a predicate test\n _.findKey = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = _.keys(obj), key;\n for (var i = 0, length = keys.length; i < length; i++) {\n key = keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n };\n\n // Return a copy of the object only containing the whitelisted properties.\n _.pick = function(object, oiteratee, context) {\n var result = {}, obj = object, iteratee, keys;\n if (obj == null) return result;\n if (_.isFunction(oiteratee)) {\n keys = _.allKeys(obj);\n iteratee = optimizeCb(oiteratee, context);\n } else {\n keys = flatten(arguments, false, false, 1);\n iteratee = function(value, key, obj) { return key in obj; };\n obj = Object(obj);\n }\n for (var i = 0, length = keys.length; i < length; i++) {\n var key = keys[i];\n var value = obj[key];\n if (iteratee(value, key, obj)) result[key] = value;\n }\n return result;\n };\n\n // Return a copy of the object without the blacklisted properties.\n _.omit = function(obj, iteratee, context) {\n if (_.isFunction(iteratee)) {\n iteratee = _.negate(iteratee);\n } else {\n var keys = _.map(flatten(arguments, false, false, 1), String);\n iteratee = function(value, key) {\n return !_.contains(keys, key);\n };\n }\n return _.pick(obj, iteratee, context);\n };\n\n // Fill in a given object with default properties.\n _.defaults = createAssigner(_.allKeys, true);\n\n // Creates an object that inherits from the given prototype object.\n // If additional properties are provided then they will be added to the\n // created object.\n _.create = function(prototype, props) {\n var result = baseCreate(prototype);\n if (props) _.extendOwn(result, props);\n return result;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Returns whether an object has a given set of `key:value` pairs.\n _.isMatch = function(object, attrs) {\n var keys = _.keys(attrs), length = keys.length;\n if (object == null) return !length;\n var obj = Object(object);\n for (var i = 0; i < length; i++) {\n var key = keys[i];\n if (attrs[key] !== obj[key] || !(key in obj)) return false;\n }\n return true;\n };\n\n\n // Internal recursive comparison function for `isEqual`.\n var eq = function(a, b, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) return a !== 0 || 1 / a === 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwrap any wrapped objects.\n if (a instanceof _) a = a._wrapped;\n if (b instanceof _) b = b._wrapped;\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case '[object RegExp]':\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return '' + a === '' + b;\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN\n if (+a !== +a) return +b !== +b;\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case '[object Date]':\n case '[object Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n }\n\n var areArrays = className === '[object Array]';\n if (!areArrays) {\n if (typeof a != 'object' || typeof b != 'object') return false;\n\n // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n var aCtor = a.constructor, bCtor = b.constructor;\n if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&\n _.isFunction(bCtor) && bCtor instanceof bCtor)\n && ('constructor' in a && 'constructor' in b)) {\n return false;\n }\n }\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) return bStack[length] === b;\n }\n\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n\n // Recursively compare objects and arrays.\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n if (length !== b.length) return false;\n // Deep compare the contents, ignoring non-numeric properties.\n while (length--) {\n if (!eq(a[length], b[length], aStack, bStack)) return false;\n }\n } else {\n // Deep compare objects.\n var keys = _.keys(a), key;\n length = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n if (_.keys(b).length !== length) return false;\n while (length--) {\n // Deep compare each member\n key = keys[length];\n if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return true;\n };\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (obj == null) return true;\n if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;\n return _.keys(obj).length === 0;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj.nodeType === 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) === '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n var type = typeof obj;\n return type === 'function' || type === 'object' && !!obj;\n };\n\n // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.\n _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {\n _['is' + name] = function(obj) {\n return toString.call(obj) === '[object ' + name + ']';\n };\n });\n\n // Define a fallback version of the method in browsers (ahem, IE < 9), where\n // there isn't any inspectable \"Arguments\" type.\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return _.has(obj, 'callee');\n };\n }\n\n // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,\n // IE 11 (#1621), and in Safari 8 (#1929).\n if (typeof /./ != 'function' && typeof Int8Array != 'object') {\n _.isFunction = function(obj) {\n return typeof obj == 'function' || false;\n };\n }\n\n // Is a given object a finite number?\n _.isFinite = function(obj) {\n return isFinite(obj) && !isNaN(parseFloat(obj));\n };\n\n // Is the given value `NaN`? (NaN is the only number which does not equal itself).\n _.isNaN = function(obj) {\n return _.isNumber(obj) && obj !== +obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) === '[object Boolean]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Shortcut function for checking if an object has a given property directly\n // on itself (in other words, not on a prototype).\n _.has = function(obj, key) {\n return obj != null && hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning the `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iteratees.\n _.identity = function(value) {\n return value;\n };\n\n // Predicate-generating functions. Often useful outside of Underscore.\n _.constant = function(value) {\n return function() {\n return value;\n };\n };\n\n _.noop = function(){};\n\n _.property = property;\n\n // Generates a function for a given object that returns a given property.\n _.propertyOf = function(obj) {\n return obj == null ? function(){} : function(key) {\n return obj[key];\n };\n };\n\n // Returns a predicate for checking whether an object has a given set of\n // `key:value` pairs.\n _.matcher = _.matches = function(attrs) {\n attrs = _.extendOwn({}, attrs);\n return function(obj) {\n return _.isMatch(obj, attrs);\n };\n };\n\n // Run a function **n** times.\n _.times = function(n, iteratee, context) {\n var accum = Array(Math.max(0, n));\n iteratee = optimizeCb(iteratee, context, 1);\n for (var i = 0; i < n; i++) accum[i] = iteratee(i);\n return accum;\n };\n\n // Return a random integer between min and max (inclusive).\n _.random = function(min, max) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n };\n\n // A (possibly faster) way to get the current timestamp as an integer.\n _.now = Date.now || function() {\n return new Date().getTime();\n };\n\n // List of HTML entities for escaping.\n var escapeMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`'\n };\n var unescapeMap = _.invert(escapeMap);\n\n // Functions for escaping and unescaping strings to/from HTML interpolation.\n var createEscaper = function(map) {\n var escaper = function(match) {\n return map[match];\n };\n // Regexes for identifying a key that needs to be escaped\n var source = '(?:' + _.keys(map).join('|') + ')';\n var testRegexp = RegExp(source);\n var replaceRegexp = RegExp(source, 'g');\n return function(string) {\n string = string == null ? '' : '' + string;\n return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;\n };\n };\n _.escape = createEscaper(escapeMap);\n _.unescape = createEscaper(unescapeMap);\n\n // If the value of the named `property` is a function then invoke it with the\n // `object` as context; otherwise, return it.\n _.result = function(object, property, fallback) {\n var value = object == null ? void 0 : object[property];\n if (value === void 0) {\n value = fallback;\n }\n return _.isFunction(value) ? value.call(object) : value;\n };\n\n // Generate a unique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = ++idCounter + '';\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /(.)^/;\n\n // Certain characters need to be escaped so that they can be put into a\n // string literal.\n var escapes = {\n \"'\": \"'\",\n '\\\\': '\\\\',\n '\\r': 'r',\n '\\n': 'n',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n var escaper = /\\\\|'|\\r|\\n|\\u2028|\\u2029/g;\n\n var escapeChar = function(match) {\n return '\\\\' + escapes[match];\n };\n\n // JavaScript micro-templating, similar to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n // NB: `oldSettings` only exists for backwards compatibility.\n _.template = function(text, settings, oldSettings) {\n if (!settings && oldSettings) settings = oldSettings;\n settings = _.defaults({}, settings, _.templateSettings);\n\n // Combine delimiters into one regular expression via alternation.\n var matcher = RegExp([\n (settings.escape || noMatch).source,\n (settings.interpolate || noMatch).source,\n (settings.evaluate || noMatch).source\n ].join('|') + '|$', 'g');\n\n // Compile the template source, escaping string literals appropriately.\n var index = 0;\n var source = \"__p+='\";\n text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {\n source += text.slice(index, offset).replace(escaper, escapeChar);\n index = offset + match.length;\n\n if (escape) {\n source += \"'+\\n((__t=(\" + escape + \"))==null?'':_.escape(__t))+\\n'\";\n } else if (interpolate) {\n source += \"'+\\n((__t=(\" + interpolate + \"))==null?'':__t)+\\n'\";\n } else if (evaluate) {\n source += \"';\\n\" + evaluate + \"\\n__p+='\";\n }\n\n // Adobe VMs need the match returned to produce the correct offest.\n return match;\n });\n source += \"';\\n\";\n\n // If a variable is not specified, place data values in local scope.\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = \"var __t,__p='',__j=Array.prototype.join,\" +\n \"print=function(){__p+=__j.call(arguments,'');};\\n\" +\n source + 'return __p;\\n';\n\n try {\n var render = new Function(settings.variable || 'obj', '_', source);\n } catch (e) {\n e.source = source;\n throw e;\n }\n\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n // Provide the compiled source as a convenience for precompilation.\n var argument = settings.variable || 'obj';\n template.source = 'function(' + argument + '){\\n' + source + '}';\n\n return template;\n };\n\n // Add a \"chain\" function. Start chaining a wrapped Underscore object.\n _.chain = function(obj) {\n var instance = _(obj);\n instance._chain = true;\n return instance;\n };\n\n // OOP\n // ---------------\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n\n // Helper function to continue chaining intermediate results.\n var result = function(instance, obj) {\n return instance._chain ? _(obj).chain() : obj;\n };\n\n // Add your own custom functions to the Underscore object.\n _.mixin = function(obj) {\n _.each(_.functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return result(this, func.apply(_, args));\n };\n });\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n var obj = this._wrapped;\n method.apply(obj, arguments);\n if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];\n return result(this, obj);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n _.each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n return result(this, method.apply(this._wrapped, arguments));\n };\n });\n\n // Extracts the result from a wrapped and chained object.\n _.prototype.value = function() {\n return this._wrapped;\n };\n\n // Provide unwrapping proxy for some methods used in engine operations\n // such as arithmetic and JSON stringification.\n _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;\n\n _.prototype.toString = function() {\n return '' + this._wrapped;\n };\n\n // AMD registration happens at the end for compatibility with AMD loaders\n // that may not enforce next-turn semantics on modules. Even though general\n // practice for AMD registration is to be anonymous, underscore registers\n // as a named module because, like jQuery, it is a base library that is\n // popular enough to be bundled in a third party lib, but not be part of\n // an AMD load request. Those cases could generate an error when an\n // anonymous define() is called outside of a loader request.\n if (typeof define === 'function' && define.amd) {\n define('underscore', [], function() {\n return _;\n });\n }\n}.call(this));\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/underscore/underscore.js\n// module id = 0\n// module chunks = 0","var _ = require('underscore');\nvar Promise = require('es6-promise').Promise;\n\nPromise._continueWhile = function(predicate, asyncFunction) {\n if (predicate()) {\n return asyncFunction().then(function() {\n return Promise._continueWhile(predicate, asyncFunction);\n });\n }\n return Promise.resolve();\n};\n\nmodule.exports = Promise;\n\n\n\n// WEBPACK FOOTER //\n// ./src/promise.js","const request = require('superagent');\nconst debug = require('debug')('leancloud:request');\nconst md5 = require('md5');\nconst Promise = require('./promise');\nconst Cache = require('./cache');\nconst AVError = require('./error');\nconst AV = require('./av');\nconst _ = require('underscore');\nconst {\n getSessionToken,\n} = require('./utils');\n\nlet getServerURLPromise;\n\n// 服务器请求的节点 host\nconst API_HOST = {\n cn: 'https://api.leancloud.cn',\n us: 'https://us-api.leancloud.cn',\n};\n\n// 计算 X-LC-Sign 的签名方法\nconst sign = (key, isMasterKey) => {\n const now = new Date().getTime();\n const signature = md5(now + key);\n if (isMasterKey) {\n return `${signature},${now},master`;\n }\n return `${signature},${now}`;\n};\n\nlet requestsCount = 0;\n\nconst ajax = (method, resourceUrl, data, headers = {}, onprogress) => {\n const count = requestsCount++;\n\n debug(`request(${count})`, method, resourceUrl, data, headers);\n\n return new Promise((resolve, reject) => {\n const req = request(method, resourceUrl)\n .set(headers)\n .send(data);\n if (onprogress) {\n req.on('progress', onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(`response(${count})`, res.status, res.body || res.text, res.header);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n return resolve(res.body);\n });\n });\n};\n\nconst setAppKey = (headers, signKey) => {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.applicationKey);\n } else {\n headers['X-LC-Key'] = AV.applicationKey;\n }\n};\n\nconst setHeaders = (authOptions = {}, signKey) => {\n const headers = {\n 'X-LC-Id': AV.applicationId,\n 'Content-Type': 'application/json;charset=UTF-8',\n };\n let useMasterKey = false;\n if (typeof authOptions.useMasterKey === 'boolean') {\n useMasterKey = authOptions.useMasterKey;\n } else if (typeof AV._useMasterKey === 'boolean') {\n useMasterKey = AV._useMasterKey;\n }\n if (useMasterKey) {\n if (AV.masterKey) {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.masterKey, true);\n } else {\n headers['X-LC-Key'] = `${AV.masterKey},master`;\n }\n } else {\n console.warn('masterKey is not set, fall back to use appKey');\n setAppKey(headers, signKey);\n }\n } else {\n setAppKey(headers, signKey);\n }\n if (AV.hookKey) {\n headers['X-LC-Hook-Key'] = AV.hookKey;\n }\n if (AV._config.applicationProduction !== null) {\n headers['X-LC-Prod'] = String(AV._config.applicationProduction);\n }\n headers[!process.env.CLIENT_PLATFORM ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent;\n\n return Promise.resolve().then(() => {\n // Pass the session token\n const sessionToken = getSessionToken(authOptions);\n if (sessionToken) {\n headers['X-LC-Session'] = sessionToken;\n } else if (!AV._config.disableCurrentUser) {\n return AV.User.currentAsync().then((currentUser) => {\n if (currentUser && currentUser._sessionToken) {\n headers['X-LC-Session'] = currentUser._sessionToken;\n }\n return headers;\n });\n }\n return headers;\n });\n};\n\nconst createApiUrl = (route, className, objectId, method, dataObject) => {\n // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉\n if (AV.serverURL) {\n AV._config.APIServerURL = AV.serverURL;\n console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.');\n }\n\n let apiURL = AV._config.APIServerURL || API_HOST.cn;\n\n if (apiURL.charAt(apiURL.length - 1) !== '/') {\n apiURL += '/';\n }\n apiURL += `1.1/${route}`;\n if (className) {\n apiURL += `/${className}`;\n }\n if (objectId) {\n apiURL += `/${objectId}`;\n }\n if ((route === 'users' || route === 'classes') && dataObject) {\n apiURL += '?';\n if (dataObject._fetchWhenSave) {\n delete dataObject._fetchWhenSave;\n apiURL += '&new=true';\n }\n if (dataObject._where) {\n apiURL += `&where=${encodeURIComponent(JSON.stringify(dataObject._where))}`;\n delete dataObject._where;\n }\n }\n\n if (method.toLowerCase() === 'get') {\n if (apiURL.indexOf('?') === -1) {\n apiURL += '?';\n }\n for (const k in dataObject) {\n if (typeof dataObject[k] === 'object') {\n dataObject[k] = JSON.stringify(dataObject[k]);\n }\n apiURL += `&${k}=${encodeURIComponent(dataObject[k])}`;\n }\n }\n\n return apiURL;\n};\n\nconst cacheServerURL = (serverURL, ttl) => {\n if (typeof ttl !== 'number') {\n ttl = 3600;\n }\n return Cache.setAsync('APIServerURL', serverURL, ttl * 1000);\n};\n\n// handle AV._request Error\nconst handleError = (error) => {\n return new Promise((resolve, reject) => {\n /**\n When API request need to redirect to the right location,\n can't use browser redirect by http status 307, as the reason of CORS,\n so API server response http status 410 and the param \"location\" for this case.\n */\n if (error.statusCode === 410) {\n cacheServerURL(error.response.api_server, error.response.ttl).then(() => {\n resolve(error.response.location);\n }).catch(reject);\n } else {\n let errorJSON = {\n code: error.code || -1,\n error: error.message || error.responseText\n };\n if (error.response && error.response.code) {\n errorJSON = error.response;\n } else if (error.responseText) {\n try {\n errorJSON = JSON.parse(error.responseText);\n } catch (e) {\n // If we fail to parse the error text, that's okay.\n }\n }\n\n // Transform the error into an instance of AVError by trying to parse\n // the error string as JSON.\n reject(new AVError(errorJSON.code, errorJSON.error));\n }\n });\n};\n\nconst setServerUrl = (serverURL) => {\n AV._config.APIServerURL = `https://${serverURL}`;\n\n // 根据新 URL 重新设置区域\n const newRegion = _.findKey(API_HOST, item => item === AV._config.APIServerURL);\n if (newRegion) {\n AV._config.region = newRegion;\n }\n};\n\nconst refreshServerUrlByRouter = () => {\n const url = `https://app-router.leancloud.cn/1/route?appId=${AV.applicationId}`;\n return ajax('get', url).then(servers => {\n if (servers.api_server) {\n setServerUrl(servers.api_server);\n return cacheServerURL(servers.api_server, servers.ttl);\n }\n }, error => {\n // bypass all non-4XX errors\n if (error.statusCode >= 400 && error.statusCode < 500) {\n throw error;\n }\n });\n};\n\nconst setServerUrlByRegion = (region = 'cn') => {\n getServerURLPromise = new Promise((resolve, reject) => {\n // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router\n if (AV._config.APIServerURL) {\n resolve();\n return;\n }\n // if not china server region, do not use router\n if (region === 'cn') {\n return Cache.getAsync('APIServerURL').then((serverURL) => {\n if (serverURL) {\n setServerUrl(serverURL);\n } else {\n return refreshServerUrlByRouter();\n }\n }).then(() => {\n resolve();\n }).catch((error) => {\n reject(error);\n });\n } else {\n AV._config.region = region;\n AV._config.APIServerURL = API_HOST[region];\n resolve();\n }\n });\n};\n\n/**\n * route is classes, users, login, etc.\n * objectId is null if there is no associated objectId.\n * method is the http method for the REST API.\n * dataObject is the payload as an object, or null if there is none.\n * @ignore\n */\nconst AVRequest = (route, className, objectId, method, dataObject = {}, authOptions) => {\n if (!AV.applicationId) {\n throw new Error('You must specify your applicationId using AV.init()');\n }\n\n if (!AV.applicationKey && !AV.masterKey) {\n throw new Error('You must specify a AppKey using AV.init()');\n }\n\n if (!getServerURLPromise) {\n return Promise.reject(new Error('Not initialized'));\n }\n return getServerURLPromise.then(() => {\n const apiURL = createApiUrl(route, className, objectId, method, dataObject);\n return setHeaders(authOptions, route !== 'bigquery').then(\n headers => ajax(method, apiURL, dataObject, headers)\n .then(\n null,\n res => handleError(res)\n .then(location => ajax(method, location, dataObject, headers))\n )\n );\n });\n};\n\nmodule.exports = {\n ajax,\n request: AVRequest,\n setServerUrlByRegion,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/request.js","const _ = require('underscore');\n\n/**\n * @class AV.Error\n */\n\nfunction AVError(code, message) {\n const error = new Error(message);\n error.code = code;\n return error;\n}\n\n_.extend(AVError, /** @lends AV.Error */ {\n /**\n * Error code indicating some error other than those enumerated here.\n * @constant\n */\n OTHER_CAUSE: -1,\n\n /**\n * Error code indicating that something has gone wrong with the server.\n * If you get this error code, it is AV's fault. Contact us at\n * https://avoscloud.com/help\n * @constant\n */\n INTERNAL_SERVER_ERROR: 1,\n\n /**\n * Error code indicating the connection to the AV servers failed.\n * @constant\n */\n CONNECTION_FAILED: 100,\n\n /**\n * Error code indicating the specified object doesn't exist.\n * @constant\n */\n OBJECT_NOT_FOUND: 101,\n\n /**\n * Error code indicating you tried to query with a datatype that doesn't\n * support it, like exact matching an array or object.\n * @constant\n */\n INVALID_QUERY: 102,\n\n /**\n * Error code indicating a missing or invalid classname. Classnames are\n * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the\n * only valid characters.\n * @constant\n */\n INVALID_CLASS_NAME: 103,\n\n /**\n * Error code indicating an unspecified object id.\n * @constant\n */\n MISSING_OBJECT_ID: 104,\n\n /**\n * Error code indicating an invalid key name. Keys are case-sensitive. They\n * must start with a letter, and a-zA-Z0-9_ are the only valid characters.\n * @constant\n */\n INVALID_KEY_NAME: 105,\n\n /**\n * Error code indicating a malformed pointer. You should not see this unless\n * you have been mucking about changing internal AV code.\n * @constant\n */\n INVALID_POINTER: 106,\n\n /**\n * Error code indicating that badly formed JSON was received upstream. This\n * either indicates you have done something unusual with modifying how\n * things encode to JSON, or the network is failing badly.\n * @constant\n */\n INVALID_JSON: 107,\n\n /**\n * Error code indicating that the feature you tried to access is only\n * available internally for testing purposes.\n * @constant\n */\n COMMAND_UNAVAILABLE: 108,\n\n /**\n * You must call AV.initialize before using the AV library.\n * @constant\n */\n NOT_INITIALIZED: 109,\n\n /**\n * Error code indicating that a field was set to an inconsistent type.\n * @constant\n */\n INCORRECT_TYPE: 111,\n\n /**\n * Error code indicating an invalid channel name. A channel name is either\n * an empty string (the broadcast channel) or contains only a-zA-Z0-9_\n * characters.\n * @constant\n */\n INVALID_CHANNEL_NAME: 112,\n\n /**\n * Error code indicating that push is misconfigured.\n * @constant\n */\n PUSH_MISCONFIGURED: 115,\n\n /**\n * Error code indicating that the object is too large.\n * @constant\n */\n OBJECT_TOO_LARGE: 116,\n\n /**\n * Error code indicating that the operation isn't allowed for clients.\n * @constant\n */\n OPERATION_FORBIDDEN: 119,\n\n /**\n * Error code indicating the result was not found in the cache.\n * @constant\n */\n CACHE_MISS: 120,\n\n /**\n * Error code indicating that an invalid key was used in a nested\n * JSONObject.\n * @constant\n */\n INVALID_NESTED_KEY: 121,\n\n /**\n * Error code indicating that an invalid filename was used for AVFile.\n * A valid file name contains only a-zA-Z0-9_. characters and is between 1\n * and 128 characters.\n * @constant\n */\n INVALID_FILE_NAME: 122,\n\n /**\n * Error code indicating an invalid ACL was provided.\n * @constant\n */\n INVALID_ACL: 123,\n\n /**\n * Error code indicating that the request timed out on the server. Typically\n * this indicates that the request is too expensive to run.\n * @constant\n */\n TIMEOUT: 124,\n\n /**\n * Error code indicating that the email address was invalid.\n * @constant\n */\n INVALID_EMAIL_ADDRESS: 125,\n\n /**\n * Error code indicating a missing content type.\n * @constant\n */\n MISSING_CONTENT_TYPE: 126,\n\n /**\n * Error code indicating a missing content length.\n * @constant\n */\n MISSING_CONTENT_LENGTH: 127,\n\n /**\n * Error code indicating an invalid content length.\n * @constant\n */\n INVALID_CONTENT_LENGTH: 128,\n\n /**\n * Error code indicating a file that was too large.\n * @constant\n */\n FILE_TOO_LARGE: 129,\n\n /**\n * Error code indicating an error saving a file.\n * @constant\n */\n FILE_SAVE_ERROR: 130,\n\n /**\n * Error code indicating an error deleting a file.\n * @constant\n */\n FILE_DELETE_ERROR: 153,\n\n /**\n * Error code indicating that a unique field was given a value that is\n * already taken.\n * @constant\n */\n DUPLICATE_VALUE: 137,\n\n /**\n * Error code indicating that a role's name is invalid.\n * @constant\n */\n INVALID_ROLE_NAME: 139,\n\n /**\n * Error code indicating that an application quota was exceeded. Upgrade to\n * resolve.\n * @constant\n */\n EXCEEDED_QUOTA: 140,\n\n /**\n * Error code indicating that a Cloud Code script failed.\n * @constant\n */\n SCRIPT_FAILED: 141,\n\n /**\n * Error code indicating that a Cloud Code validation failed.\n * @constant\n */\n VALIDATION_ERROR: 142,\n\n /**\n * Error code indicating that invalid image data was provided.\n * @constant\n */\n INVALID_IMAGE_DATA: 150,\n\n /**\n * Error code indicating an unsaved file.\n * @constant\n */\n UNSAVED_FILE_ERROR: 151,\n\n /**\n * Error code indicating an invalid push time.\n */\n INVALID_PUSH_TIME_ERROR: 152,\n\n /**\n * Error code indicating that the username is missing or empty.\n * @constant\n */\n USERNAME_MISSING: 200,\n\n /**\n * Error code indicating that the password is missing or empty.\n * @constant\n */\n PASSWORD_MISSING: 201,\n\n /**\n * Error code indicating that the username has already been taken.\n * @constant\n */\n USERNAME_TAKEN: 202,\n\n /**\n * Error code indicating that the email has already been taken.\n * @constant\n */\n EMAIL_TAKEN: 203,\n\n /**\n * Error code indicating that the email is missing, but must be specified.\n * @constant\n */\n EMAIL_MISSING: 204,\n\n /**\n * Error code indicating that a user with the specified email was not found.\n * @constant\n */\n EMAIL_NOT_FOUND: 205,\n\n /**\n * Error code indicating that a user object without a valid session could\n * not be altered.\n * @constant\n */\n SESSION_MISSING: 206,\n\n /**\n * Error code indicating that a user can only be created through signup.\n * @constant\n */\n MUST_CREATE_USER_THROUGH_SIGNUP: 207,\n\n /**\n * Error code indicating that an an account being linked is already linked\n * to another user.\n * @constant\n */\n ACCOUNT_ALREADY_LINKED: 208,\n\n /**\n * Error code indicating that a user cannot be linked to an account because\n * that account's id could not be found.\n * @constant\n */\n LINKED_ID_MISSING: 250,\n\n /**\n * Error code indicating that a user with a linked (e.g. Facebook) account\n * has an invalid session.\n * @constant\n */\n INVALID_LINKED_SESSION: 251,\n\n /**\n * Error code indicating that a service being linked (e.g. Facebook or\n * Twitter) is unsupported.\n * @constant\n */\n UNSUPPORTED_SERVICE: 252,\n /**\n * Error code indicating a real error code is unavailable because\n * we had to use an XDomainRequest object to allow CORS requests in\n * Internet Explorer, which strips the body from HTTP responses that have\n * a non-2XX status code.\n * @constant\n */\n X_DOMAIN_REQUEST: 602,\n});\n\nmodule.exports = AVError;\n\n\n\n// WEBPACK FOOTER //\n// ./src/error.js","const _ = require('underscore');\n\n// Helper function to check null or undefined.\nconst isNullOrUndefined = (x) => _.isNull(x) || _.isUndefined(x);\n\nconst ensureArray = target => {\n if (_.isArray(target)) {\n return target;\n }\n if (target === undefined || target === null) {\n return [];\n }\n return [target];\n};\n\nconst getSessionToken = (authOptions) => {\n if (authOptions.sessionToken) {\n return authOptions.sessionToken;\n }\n if (\n authOptions.user && typeof authOptions.user.getSessionToken === 'function'\n ) {\n return authOptions.user.getSessionToken();\n }\n};\n\nconst tap = interceptor => value => ((interceptor(value), value));\n\nmodule.exports = {\n isNullOrUndefined,\n ensureArray,\n getSessionToken,\n tap,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/index.js","/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n 'lightseagreen',\n 'forestgreen',\n 'goldenrod',\n 'dodgerblue',\n 'darkorchid',\n 'crimson'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/browser.js\n// module id = 5\n// module chunks = 0","const _ = require('underscore');\nconst userAgent = require('./ua');\nconst {\n isNullOrUndefined,\n} = require('./utils');\n\nconst AV = global.AV || {};\n\n// All internal configuration items\nAV._config = AV._config || {};\nconst AVConfig = AV._config;\n\n_.extend(AVConfig, {\n\n // 服务器节点地区,默认中国大陆\n region: 'cn',\n\n // 服务器的 URL,默认初始化时被设置为大陆节点地址\n APIServerURL: AVConfig.APIServerURL || '',\n\n // 禁用 currentUser,通常用于多用户环境\n disableCurrentUser: false,\n\n // Internal config can modifie the UserAgent\n userAgent,\n\n // set production environment or test environment\n // 1: production environment, 0: test environment, null: default environment\n applicationProduction: null,\n});\n\n/**\n * Contains all AV API classes and functions.\n * @namespace AV\n */\n\n// Helpers\n// -------\n\n// Shared empty constructor function to aid in prototype-chain creation.\nvar EmptyConstructor = function() {};\n\n// Helper function to correctly set up the prototype chain, for subclasses.\n// Similar to `goog.inherits`, but uses a hash of prototype properties and\n// class properties to be extended.\nvar inherits = function(parent, protoProps, staticProps) {\n var child;\n\n // The constructor function for the new subclass is either defined by you\n // (the \"constructor\" property in your `extend` definition), or defaulted\n // by us to simply call the parent's constructor.\n if (protoProps && protoProps.hasOwnProperty('constructor')) {\n child = protoProps.constructor;\n } else {\n /** @ignore */\n child = function(){ parent.apply(this, arguments); };\n }\n\n // Inherit class (static) properties from parent.\n _.extend(child, parent);\n\n // Set the prototype chain to inherit from `parent`, without calling\n // `parent`'s constructor function.\n EmptyConstructor.prototype = parent.prototype;\n child.prototype = new EmptyConstructor();\n\n // Add prototype properties (instance properties) to the subclass,\n // if supplied.\n if (protoProps) {\n _.extend(child.prototype, protoProps);\n }\n\n // Add static properties to the constructor function, if supplied.\n if (staticProps) {\n _.extend(child, staticProps);\n }\n\n // Correctly set child's `prototype.constructor`.\n child.prototype.constructor = child;\n\n // Set a convenience property in case the parent's prototype is\n // needed later.\n child.__super__ = parent.prototype;\n\n return child;\n};\n\n/**\n * Call this method to set production environment variable.\n * @function AV.setProduction\n * @param {Boolean} production True is production environment,and\n * it's true by default.\n */\nAV.setProduction = (production) => {\n if (!isNullOrUndefined(production)) {\n AVConfig.applicationProduction = production ? 1 : 0;\n } else {\n // change to default value\n AVConfig.applicationProduction = null;\n }\n};\n\n/**\n * Returns prefix for localStorage keys used by this instance of AV.\n * @param {String} path The relative suffix to append to it.\n * null or undefined is treated as the empty string.\n * @return {String} The full key name.\n * @private\n */\nAV._getAVPath = function(path) {\n if (!AV.applicationId) {\n throw new Error(\"You need to call AV.initialize before using AV.\");\n }\n if (!path) {\n path = \"\";\n }\n if (!_.isString(path)) {\n throw new Error(\"Tried to get a localStorage path that wasn't a String.\");\n }\n if (path[0] === \"/\") {\n path = path.substring(1);\n }\n return \"AV/\" + AV.applicationId + \"/\" + path;\n};\n\n/**\n * Returns the unique string for this app on this machine.\n * Gets reset when localStorage is cleared.\n * @private\n */\nAV._installationId = null;\nAV._getInstallationId = function() {\n // See if it's cached in RAM.\n if (AV._installationId) {\n return AV.Promise.resolve(AV._installationId);\n }\n\n // Try to get it from localStorage.\n var path = AV._getAVPath(\"installationId\");\n return AV.localStorage.getItemAsync(path).then(function(_installationId){\n AV._installationId = _installationId;\n if (!AV._installationId) {\n // It wasn't in localStorage, so create a new one.\n var hexOctet = function() {\n return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);\n };\n AV._installationId = (\n hexOctet() + hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + hexOctet() + hexOctet());\n return AV.localStorage.setItemAsync(path, AV._installationId);\n }\n else {\n return _installationId;\n }\n });\n};\n\nAV._parseDate = function(iso8601) {\n var regexp = new RegExp(\n \"^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})\" + \"T\" +\n \"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\" +\n \"(.([0-9]+))?\" + \"Z$\");\n var match = regexp.exec(iso8601);\n if (!match) {\n return null;\n }\n\n var year = match[1] || 0;\n var month = (match[2] || 1) - 1;\n var day = match[3] || 0;\n var hour = match[4] || 0;\n var minute = match[5] || 0;\n var second = match[6] || 0;\n var milli = match[8] || 0;\n\n return new Date(Date.UTC(year, month, day, hour, minute, second, milli));\n};\n\n// A self-propagating extend function.\nAV._extend = function(protoProps, classProps) {\n var child = inherits(this, protoProps, classProps);\n child.extend = this.extend;\n return child;\n};\n\n// Helper function to get a value from a Backbone object as a property\n// or as a function.\nAV._getValue = function(object, prop) {\n if (!(object && object[prop])) {\n return null;\n }\n return _.isFunction(object[prop]) ? object[prop]() : object[prop];\n};\n\n/**\n * Converts a value in a AV Object into the appropriate representation.\n * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object)\n * if seenObjects is falsey. Otherwise any AV.Objects not in\n * seenObjects will be fully embedded rather than encoded\n * as a pointer. This array will be used to prevent going into an infinite\n * loop because we have circular references. If \n * is set, then none of the AV Objects that are serialized can be dirty.\n * @private\n */\nAV._encode = function(value, seenObjects, disallowObjects) {\n if (value instanceof AV.Object) {\n if (disallowObjects) {\n throw new Error(\"AV.Objects not allowed here\");\n }\n if (!seenObjects || _.include(seenObjects, value) || !value._hasData) {\n return value._toPointer();\n }\n if (!value.dirty()) {\n seenObjects = seenObjects.concat(value);\n return AV._encode(value._toFullJSON(seenObjects),\n seenObjects,\n disallowObjects);\n }\n throw new Error(\"Tried to save an object with a pointer to a new, unsaved object.\");\n }\n if (value instanceof AV.ACL) {\n return value.toJSON();\n }\n if (_.isDate(value)) {\n return { \"__type\": \"Date\", \"iso\": value.toJSON() };\n }\n if (value instanceof AV.GeoPoint) {\n return value.toJSON();\n }\n if (_.isArray(value)) {\n return _.map(value, function(x) {\n return AV._encode(x, seenObjects, disallowObjects);\n });\n }\n if (_.isRegExp(value)) {\n return value.source;\n }\n if (value instanceof AV.Relation) {\n return value.toJSON();\n }\n if (value instanceof AV.Op) {\n return value.toJSON();\n }\n if (value instanceof AV.File) {\n if (!value.url() && !value.id) {\n throw new Error(\"Tried to save an object containing an unsaved file.\");\n }\n return value._toFullJSON();\n }\n if (_.isObject(value)) {\n return _.mapObject(value, (v, k) => AV._encode(v, seenObjects, disallowObjects));\n }\n return value;\n};\n\n/**\n * The inverse function of AV._encode.\n * @private\n */\nAV._decode = function(value, key) {\n if (!_.isObject(value) || _.isDate(value)) {\n return value;\n }\n if (_.isArray(value)) {\n return _.map(value, v => AV._decode(v));\n }\n if (value instanceof AV.Object) {\n return value;\n }\n if (value instanceof AV.File) {\n return value;\n }\n if (value instanceof AV.Op) {\n return value;\n }\n if (value instanceof AV.GeoPoint) {\n return value;\n }\n if (value instanceof AV.ACL) {\n return value;\n }\n if (key === 'ACL') {\n return new AV.ACL(value);\n }\n if (value.__op) {\n return AV.Op._decode(value);\n }\n var className;\n if (value.__type === \"Pointer\") {\n className = value.className;\n var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n if(Object.keys(value).length > 3) {\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n pointer._finishFetch(v, true);\n }else{\n pointer._finishFetch({ objectId: value.objectId }, false);\n }\n return pointer;\n }\n if (value.__type === \"Object\") {\n // It's an Object included in a query result.\n className = value.className;\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n object._finishFetch(v, true);\n return object;\n }\n if (value.__type === \"Date\") {\n return AV._parseDate(value.iso);\n }\n if (value.__type === \"GeoPoint\") {\n return new AV.GeoPoint({\n latitude: value.latitude,\n longitude: value.longitude\n });\n }\n if (value.__type === \"Relation\") {\n if (!key) throw new Error('key missing decoding a Relation');\n var relation = new AV.Relation(null, key);\n relation.targetClassName = value.className;\n return relation;\n }\n if (value.__type === 'File') {\n var file = new AV.File(value.name);\n const v = _.clone(value);\n delete v.__type;\n file._finishFetch(v);\n return file;\n }\n return _.mapObject(value, AV._decode);\n};\n\nAV._encodeObjectOrArray = function(value) {\n var encodeAVObject = function(object) {\n if (object && object._toFullJSON){\n object = object._toFullJSON([]);\n }\n\n return _.mapObject(object, function(value) {\n return AV._encode(value, []);\n });\n };\n\n if (_.isArray(value)) {\n return value.map(function(object) {\n return encodeAVObject(object);\n });\n } else {\n return encodeAVObject(value);\n }\n};\n\nAV._arrayEach = _.each;\n\n/**\n * Does a deep traversal of every item in object, calling func on every one.\n * @param {Object} object The object or array to traverse deeply.\n * @param {Function} func The function to call for every item. It will\n * be passed the item as an argument. If it returns a truthy value, that\n * value will replace the item in its parent container.\n * @returns {} the result of calling func on the top-level object itself.\n * @private\n */\nAV._traverse = function(object, func, seen) {\n if (object instanceof AV.Object) {\n seen = seen || [];\n if (_.indexOf(seen, object) >= 0) {\n // We've already visited this object in this call.\n return;\n }\n seen.push(object);\n AV._traverse(object.attributes, func, seen);\n return func(object);\n }\n if (object instanceof AV.Relation || object instanceof AV.File) {\n // Nothing needs to be done, but we don't want to recurse into the\n // object's parent infinitely, so we catch this case.\n return func(object);\n }\n if (_.isArray(object)) {\n _.each(object, function(child, index) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[index] = newChild;\n }\n });\n return func(object);\n }\n if (_.isObject(object)) {\n AV._each(object, function(child, key) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[key] = newChild;\n }\n });\n return func(object);\n }\n return func(object);\n};\n\n/**\n * This is like _.each, except:\n * * it doesn't work for so-called array-like objects,\n * * it does work for dictionaries with a \"length\" attribute.\n * @private\n */\nAV._objectEach = AV._each = function(obj, callback) {\n if (_.isObject(obj)) {\n _.each(_.keys(obj), function(key) {\n callback(obj[key], key);\n });\n } else {\n _.each(obj, callback);\n }\n};\n\nmodule.exports = AV;\n\n\n\n// WEBPACK FOOTER //\n// ./src/av.js","/**\n * Root reference for iframes.\n */\n\nvar root;\nif (typeof window !== 'undefined') { // Browser window\n root = window;\n} else if (typeof self !== 'undefined') { // Web Worker\n root = self;\n} else { // Other environments\n console.warn(\"Using browser-only version of superagent in non-browser environment\");\n root = this;\n}\n\nvar Emitter = require('component-emitter');\nvar RequestBase = require('./request-base');\nvar isObject = require('./is-object');\nvar isFunction = require('./is-function');\nvar ResponseBase = require('./response-base');\nvar shouldRetry = require('./should-retry');\n\n/**\n * Noop.\n */\n\nfunction noop(){};\n\n/**\n * Expose `request`.\n */\n\nvar request = exports = module.exports = function(method, url) {\n // callback\n if ('function' == typeof url) {\n return new exports.Request('GET', method).end(url);\n }\n\n // url first\n if (1 == arguments.length) {\n return new exports.Request('GET', method);\n }\n\n return new exports.Request(method, url);\n}\n\nexports.Request = Request;\n\n/**\n * Determine XHR.\n */\n\nrequest.getXHR = function () {\n if (root.XMLHttpRequest\n && (!root.location || 'file:' != root.location.protocol\n || !root.ActiveXObject)) {\n return new XMLHttpRequest;\n } else {\n try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}\n }\n throw Error(\"Browser-only verison of superagent could not find XHR\");\n};\n\n/**\n * Removes leading and trailing whitespace, added to support IE.\n *\n * @param {String} s\n * @return {String}\n * @api private\n */\n\nvar trim = ''.trim\n ? function(s) { return s.trim(); }\n : function(s) { return s.replace(/(^\\s*|\\s*$)/g, ''); };\n\n/**\n * Serialize the given `obj`.\n *\n * @param {Object} obj\n * @return {String}\n * @api private\n */\n\nfunction serialize(obj) {\n if (!isObject(obj)) return obj;\n var pairs = [];\n for (var key in obj) {\n pushEncodedKeyValuePair(pairs, key, obj[key]);\n }\n return pairs.join('&');\n}\n\n/**\n * Helps 'serialize' with serializing arrays.\n * Mutates the pairs array.\n *\n * @param {Array} pairs\n * @param {String} key\n * @param {Mixed} val\n */\n\nfunction pushEncodedKeyValuePair(pairs, key, val) {\n if (val != null) {\n if (Array.isArray(val)) {\n val.forEach(function(v) {\n pushEncodedKeyValuePair(pairs, key, v);\n });\n } else if (isObject(val)) {\n for(var subkey in val) {\n pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);\n }\n } else {\n pairs.push(encodeURIComponent(key)\n + '=' + encodeURIComponent(val));\n }\n } else if (val === null) {\n pairs.push(encodeURIComponent(key));\n }\n}\n\n/**\n * Expose serialization method.\n */\n\n request.serializeObject = serialize;\n\n /**\n * Parse the given x-www-form-urlencoded `str`.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseString(str) {\n var obj = {};\n var pairs = str.split('&');\n var pair;\n var pos;\n\n for (var i = 0, len = pairs.length; i < len; ++i) {\n pair = pairs[i];\n pos = pair.indexOf('=');\n if (pos == -1) {\n obj[decodeURIComponent(pair)] = '';\n } else {\n obj[decodeURIComponent(pair.slice(0, pos))] =\n decodeURIComponent(pair.slice(pos + 1));\n }\n }\n\n return obj;\n}\n\n/**\n * Expose parser.\n */\n\nrequest.parseString = parseString;\n\n/**\n * Default MIME type map.\n *\n * superagent.types.xml = 'application/xml';\n *\n */\n\nrequest.types = {\n html: 'text/html',\n json: 'application/json',\n xml: 'application/xml',\n urlencoded: 'application/x-www-form-urlencoded',\n 'form': 'application/x-www-form-urlencoded',\n 'form-data': 'application/x-www-form-urlencoded'\n};\n\n/**\n * Default serialization map.\n *\n * superagent.serialize['application/xml'] = function(obj){\n * return 'generated xml here';\n * };\n *\n */\n\n request.serialize = {\n 'application/x-www-form-urlencoded': serialize,\n 'application/json': JSON.stringify\n };\n\n /**\n * Default parsers.\n *\n * superagent.parse['application/xml'] = function(str){\n * return { object parsed from str };\n * };\n *\n */\n\nrequest.parse = {\n 'application/x-www-form-urlencoded': parseString,\n 'application/json': JSON.parse\n};\n\n/**\n * Parse the given header `str` into\n * an object containing the mapped fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseHeader(str) {\n var lines = str.split(/\\r?\\n/);\n var fields = {};\n var index;\n var line;\n var field;\n var val;\n\n lines.pop(); // trailing CRLF\n\n for (var i = 0, len = lines.length; i < len; ++i) {\n line = lines[i];\n index = line.indexOf(':');\n field = line.slice(0, index).toLowerCase();\n val = trim(line.slice(index + 1));\n fields[field] = val;\n }\n\n return fields;\n}\n\n/**\n * Check if `mime` is json or has +json structured syntax suffix.\n *\n * @param {String} mime\n * @return {Boolean}\n * @api private\n */\n\nfunction isJSON(mime) {\n return /[\\/+]json\\b/.test(mime);\n}\n\n/**\n * Initialize a new `Response` with the given `xhr`.\n *\n * - set flags (.ok, .error, etc)\n * - parse header\n *\n * Examples:\n *\n * Aliasing `superagent` as `request` is nice:\n *\n * request = superagent;\n *\n * We can use the promise-like API, or pass callbacks:\n *\n * request.get('/').end(function(res){});\n * request.get('/', function(res){});\n *\n * Sending data can be chained:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' })\n * .end(function(res){});\n *\n * Or passed to `.send()`:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' }, function(res){});\n *\n * Or passed to `.post()`:\n *\n * request\n * .post('/user', { name: 'tj' })\n * .end(function(res){});\n *\n * Or further reduced to a single call for simple cases:\n *\n * request\n * .post('/user', { name: 'tj' }, function(res){});\n *\n * @param {XMLHTTPRequest} xhr\n * @param {Object} options\n * @api private\n */\n\nfunction Response(req) {\n this.req = req;\n this.xhr = this.req.xhr;\n // responseText is accessible only if responseType is '' or 'text' and on older browsers\n this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')\n ? this.xhr.responseText\n : null;\n this.statusText = this.req.xhr.statusText;\n var status = this.xhr.status;\n // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request\n if (status === 1223) {\n status = 204;\n }\n this._setStatusProperties(status);\n this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());\n // getAllResponseHeaders sometimes falsely returns \"\" for CORS requests, but\n // getResponseHeader still works. so we get content-type even if getting\n // other headers fails.\n this.header['content-type'] = this.xhr.getResponseHeader('content-type');\n this._setHeaderProperties(this.header);\n\n if (null === this.text && req._responseType) {\n this.body = this.xhr.response;\n } else {\n this.body = this.req.method != 'HEAD'\n ? this._parseBody(this.text ? this.text : this.xhr.response)\n : null;\n }\n}\n\nResponseBase(Response.prototype);\n\n/**\n * Parse the given body `str`.\n *\n * Used for auto-parsing of bodies. Parsers\n * are defined on the `superagent.parse` object.\n *\n * @param {String} str\n * @return {Mixed}\n * @api private\n */\n\nResponse.prototype._parseBody = function(str){\n var parse = request.parse[this.type];\n if(this.req._parser) {\n return this.req._parser(this, str);\n }\n if (!parse && isJSON(this.type)) {\n parse = request.parse['application/json'];\n }\n return parse && str && (str.length || str instanceof Object)\n ? parse(str)\n : null;\n};\n\n/**\n * Return an `Error` representative of this response.\n *\n * @return {Error}\n * @api public\n */\n\nResponse.prototype.toError = function(){\n var req = this.req;\n var method = req.method;\n var url = req.url;\n\n var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';\n var err = new Error(msg);\n err.status = this.status;\n err.method = method;\n err.url = url;\n\n return err;\n};\n\n/**\n * Expose `Response`.\n */\n\nrequest.Response = Response;\n\n/**\n * Initialize a new `Request` with the given `method` and `url`.\n *\n * @param {String} method\n * @param {String} url\n * @api public\n */\n\nfunction Request(method, url) {\n var self = this;\n this._query = this._query || [];\n this.method = method;\n this.url = url;\n this.header = {}; // preserves header name case\n this._header = {}; // coerces header names to lowercase\n this.on('end', function(){\n var err = null;\n var res = null;\n\n try {\n res = new Response(self);\n } catch(e) {\n err = new Error('Parser is unable to parse the response');\n err.parse = true;\n err.original = e;\n // issue #675: return the raw response if the response parsing fails\n if (self.xhr) {\n // ie9 doesn't have 'response' property\n err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;\n // issue #876: return the http status code if the response parsing fails\n err.status = self.xhr.status ? self.xhr.status : null;\n err.statusCode = err.status; // backwards-compat only\n } else {\n err.rawResponse = null;\n err.status = null;\n }\n\n return self.callback(err);\n }\n\n self.emit('response', res);\n\n var new_err;\n try {\n if (!self._isResponseOK(res)) {\n new_err = new Error(res.statusText || 'Unsuccessful HTTP response');\n new_err.original = err;\n new_err.response = res;\n new_err.status = res.status;\n }\n } catch(e) {\n new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android\n }\n\n // #1000 don't catch errors from the callback to avoid double calling it\n if (new_err) {\n self.callback(new_err, res);\n } else {\n self.callback(null, res);\n }\n });\n}\n\n/**\n * Mixin `Emitter` and `RequestBase`.\n */\n\nEmitter(Request.prototype);\nRequestBase(Request.prototype);\n\n/**\n * Set Content-Type to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.xml = 'application/xml';\n *\n * request.post('/')\n * .type('xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * request.post('/')\n * .type('application/xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * @param {String} type\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.type = function(type){\n this.set('Content-Type', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Accept to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.json = 'application/json';\n *\n * request.get('/agent')\n * .accept('json')\n * .end(callback);\n *\n * request.get('/agent')\n * .accept('application/json')\n * .end(callback);\n *\n * @param {String} accept\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.accept = function(type){\n this.set('Accept', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Authorization field value with `user` and `pass`.\n *\n * @param {String} user\n * @param {String} [pass] optional in case of using 'bearer' as type\n * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.auth = function(user, pass, options){\n if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options\n options = pass;\n }\n if (!options) {\n options = {\n type: 'function' === typeof btoa ? 'basic' : 'auto',\n }\n }\n\n switch (options.type) {\n case 'basic':\n this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));\n break;\n\n case 'auto':\n this.username = user;\n this.password = pass;\n break;\n \n case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })\n this.set('Authorization', 'Bearer ' + user);\n break; \n }\n return this;\n};\n\n/**\n * Add query-string `val`.\n *\n * Examples:\n *\n * request.get('/shoes')\n * .query('size=10')\n * .query({ color: 'blue' })\n *\n * @param {Object|String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.query = function(val){\n if ('string' != typeof val) val = serialize(val);\n if (val) this._query.push(val);\n return this;\n};\n\n/**\n * Queue the given `file` as an attachment to the specified `field`,\n * with optional `options` (or filename).\n *\n * ``` js\n * request.post('/upload')\n * .attach('content', new Blob(['hey!'], { type: \"text/html\"}))\n * .end(callback);\n * ```\n *\n * @param {String} field\n * @param {Blob|File} file\n * @param {String|Object} options\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.attach = function(field, file, options){\n if (file) {\n if (this._data) {\n throw Error(\"superagent can't mix .send() and .attach()\");\n }\n\n this._getFormData().append(field, file, options || file.name);\n }\n return this;\n};\n\nRequest.prototype._getFormData = function(){\n if (!this._formData) {\n this._formData = new root.FormData();\n }\n return this._formData;\n};\n\n/**\n * Invoke the callback with `err` and `res`\n * and handle arity check.\n *\n * @param {Error} err\n * @param {Response} res\n * @api private\n */\n\nRequest.prototype.callback = function(err, res){\n // console.log(this._retries, this._maxRetries)\n if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) {\n return this._retry();\n }\n\n var fn = this._callback;\n this.clearTimeout();\n\n if (err) {\n if (this._maxRetries) err.retries = this._retries - 1;\n this.emit('error', err);\n }\n\n fn(err, res);\n};\n\n/**\n * Invoke callback with x-domain error.\n *\n * @api private\n */\n\nRequest.prototype.crossDomainError = function(){\n var err = new Error('Request has been terminated\\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');\n err.crossDomain = true;\n\n err.status = this.status;\n err.method = this.method;\n err.url = this.url;\n\n this.callback(err);\n};\n\n// This only warns, because the request is still likely to work\nRequest.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){\n console.warn(\"This is not supported in browser version of superagent\");\n return this;\n};\n\n// This throws, because it can't send/receive data as expected\nRequest.prototype.pipe = Request.prototype.write = function(){\n throw Error(\"Streaming is not supported in browser version of superagent\");\n};\n\n/**\n * Compose querystring to append to req.url\n *\n * @api private\n */\n\nRequest.prototype._appendQueryString = function(){\n var query = this._query.join('&');\n if (query) {\n this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;\n }\n\n if (this._sort) {\n var index = this.url.indexOf('?');\n if (index >= 0) {\n var queryArr = this.url.substring(index + 1).split('&');\n if (isFunction(this._sort)) {\n queryArr.sort(this._sort);\n } else {\n queryArr.sort();\n }\n this.url = this.url.substring(0, index) + '?' + queryArr.join('&');\n }\n }\n};\n\n/**\n * Check if `obj` is a host object,\n * we don't want to serialize these :)\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\nRequest.prototype._isHost = function _isHost(obj) {\n // Native objects stringify to [object File], [object Blob], [object FormData], etc.\n return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';\n}\n\n/**\n * Initiate request, invoking callback `fn(res)`\n * with an instanceof `Response`.\n *\n * @param {Function} fn\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.end = function(fn){\n if (this._endCalled) {\n console.warn(\"Warning: .end() was called twice. This is not supported in superagent\");\n }\n this._endCalled = true;\n\n // store callback\n this._callback = fn || noop;\n\n // querystring\n this._appendQueryString();\n\n return this._end();\n};\n\nRequest.prototype._end = function() {\n var self = this;\n var xhr = this.xhr = request.getXHR();\n var data = this._formData || this._data;\n\n this._setTimeouts();\n\n // state change\n xhr.onreadystatechange = function(){\n var readyState = xhr.readyState;\n if (readyState >= 2 && self._responseTimeoutTimer) {\n clearTimeout(self._responseTimeoutTimer);\n }\n if (4 != readyState) {\n return;\n }\n\n // In IE9, reads to any property (e.g. status) off of an aborted XHR will\n // result in the error \"Could not complete the operation due to error c00c023f\"\n var status;\n try { status = xhr.status } catch(e) { status = 0; }\n\n if (!status) {\n if (self.timedout || self._aborted) return;\n return self.crossDomainError();\n }\n self.emit('end');\n };\n\n // progress\n var handleProgress = function(direction, e) {\n if (e.total > 0) {\n e.percent = e.loaded / e.total * 100;\n }\n e.direction = direction;\n self.emit('progress', e);\n }\n if (this.hasListeners('progress')) {\n try {\n xhr.onprogress = handleProgress.bind(null, 'download');\n if (xhr.upload) {\n xhr.upload.onprogress = handleProgress.bind(null, 'upload');\n }\n } catch(e) {\n // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.\n // Reported here:\n // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context\n }\n }\n\n // initiate request\n try {\n if (this.username && this.password) {\n xhr.open(this.method, this.url, true, this.username, this.password);\n } else {\n xhr.open(this.method, this.url, true);\n }\n } catch (err) {\n // see #1149\n return this.callback(err);\n }\n\n // CORS\n if (this._withCredentials) xhr.withCredentials = true;\n\n // body\n if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {\n // serialize stuff\n var contentType = this._header['content-type'];\n var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];\n if (!serialize && isJSON(contentType)) {\n serialize = request.serialize['application/json'];\n }\n if (serialize) data = serialize(data);\n }\n\n // set header fields\n for (var field in this.header) {\n if (null == this.header[field]) continue;\n\n if (this.header.hasOwnProperty(field))\n xhr.setRequestHeader(field, this.header[field]);\n }\n\n if (this._responseType) {\n xhr.responseType = this._responseType;\n }\n\n // send stuff\n this.emit('request', this);\n\n // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)\n // We need null here if data is undefined\n xhr.send(typeof data !== 'undefined' ? data : null);\n return this;\n};\n\n/**\n * GET `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.get = function(url, data, fn){\n var req = request('GET', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.query(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * HEAD `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.head = function(url, data, fn){\n var req = request('HEAD', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * OPTIONS query to `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.options = function(url, data, fn){\n var req = request('OPTIONS', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * DELETE `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nfunction del(url, data, fn){\n var req = request('DELETE', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\nrequest['del'] = del;\nrequest['delete'] = del;\n\n/**\n * PATCH `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.patch = function(url, data, fn){\n var req = request('PATCH', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * POST `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.post = function(url, data, fn){\n var req = request('POST', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * PUT `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.put = function(url, data, fn){\n var req = request('PUT', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/client.js\n// module id = 7\n// module chunks = 0","/**\n * Check if `obj` is an object.\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\n\nfunction isObject(obj) {\n return null !== obj && 'object' === typeof obj;\n}\n\nmodule.exports = isObject;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-object.js\n// module id = 8\n// module chunks = 0","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/global.js\n// module id = 9\n// module chunks = 0","const storage = require('./localstorage');\nconst AV = require('./av');\n\nconst removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage);\n\nconst getCacheData = (cacheData, key) => {\n try {\n cacheData = JSON.parse(cacheData);\n } catch (e) {\n return null;\n }\n if (cacheData) {\n const expired = cacheData.expiredAt && cacheData.expiredAt < Date.now();\n if (!expired) {\n return cacheData.value;\n }\n return removeAsync(key).then(() => null);\n }\n return null;\n};\n\nexports.getAsync = (key) => {\n key = `${AV.applicationId}/${key}`;\n return storage.getItemAsync(key)\n .then(cache => getCacheData(cache, key));\n};\n\nexports.setAsync = (key, value, ttl) => {\n const cache = { value };\n if (typeof ttl === 'number') {\n cache.expiredAt = Date.now() + ttl;\n }\n return storage.setItemAsync(\n `${AV.applicationId}/${key}`,\n JSON.stringify(cache)\n );\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cache.js","var _ = require('underscore');\nvar Promise = require('./promise');\nvar localStorage = require('./utils/localstorage');\n\nvar syncApiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nif (!localStorage.async) {\n // wrap sync apis with async ones.\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] === 'function') {\n localStorage[apiName + 'Async'] = function() {\n return Promise.resolve(localStorage[apiName].apply(localStorage, arguments));\n };\n }\n });\n} else {\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] !== 'function') {\n localStorage[apiName] = function() {\n const error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.');\n error.code = 'SYNC_API_NOT_AVAILABLE';\n throw error;\n };\n }\n });\n}\n\nmodule.exports = localStorage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/localstorage.js","module.exports = '2.1.4';\n\n\n\n// WEBPACK FOOTER //\n// ./src/version.js","var charenc = {\n // UTF-8 encoding\n utf8: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n }\n },\n\n // Binary encoding\n bin: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n for (var bytes = [], i = 0; i < str.length; i++)\n bytes.push(str.charCodeAt(i) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n for (var str = [], i = 0; i < bytes.length; i++)\n str.push(String.fromCharCode(bytes[i]));\n return str.join('');\n }\n }\n};\n\nmodule.exports = charenc;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/charenc/charenc.js\n// module id = 13\n// module chunks = 0","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var PUBLIC_KEY = \"*\";\n\n /**\n * Creates a new ACL.\n * If no argument is given, the ACL has no permissions for anyone.\n * If the argument is a AV.User, the ACL will have read and write\n * permission for only that user.\n * If the argument is any other JSON object, that object will be interpretted\n * as a serialized ACL created with toJSON().\n * @see AV.Object#setACL\n * @class\n *\n *

An ACL, or Access Control List can be added to any\n * AV.Object to restrict access to only a subset of users\n * of your application.

\n */\n AV.ACL = function(arg1) {\n var self = this;\n self.permissionsById = {};\n if (_.isObject(arg1)) {\n if (arg1 instanceof AV.User) {\n self.setReadAccess(arg1, true);\n self.setWriteAccess(arg1, true);\n } else {\n if (_.isFunction(arg1)) {\n throw new Error('AV.ACL() called with a function. Did you forget ()?');\n }\n AV._objectEach(arg1, function(accessList, userId) {\n if (!_.isString(userId)) {\n throw new Error('Tried to create an ACL with an invalid userId.');\n }\n self.permissionsById[userId] = {};\n AV._objectEach(accessList, function(allowed, permission) {\n if (permission !== \"read\" && permission !== \"write\") {\n throw new Error('Tried to create an ACL with an invalid permission type.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('Tried to create an ACL with an invalid permission value.');\n }\n self.permissionsById[userId][permission] = allowed;\n });\n });\n }\n }\n };\n\n /**\n * Returns a JSON-encoded version of the ACL.\n * @return {Object}\n */\n AV.ACL.prototype.toJSON = function() {\n return _.clone(this.permissionsById);\n };\n\n AV.ACL.prototype._setAccess = function(accessType, userId, allowed) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n if (!_.isString(userId)) {\n throw new Error('userId must be a string.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('allowed must be either true or false.');\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n if (!allowed) {\n // The user already doesn't have this permission, so no action needed.\n return;\n } else {\n permissions = {};\n this.permissionsById[userId] = permissions;\n }\n }\n\n if (allowed) {\n this.permissionsById[userId][accessType] = true;\n } else {\n delete permissions[accessType];\n if (_.isEmpty(permissions)) {\n delete this.permissionsById[userId];\n }\n }\n };\n\n AV.ACL.prototype._getAccess = function(accessType, userId) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n return false;\n }\n return permissions[accessType] ? true : false;\n };\n\n /**\n * Set whether the given user is allowed to read this object.\n * @param userId An instance of AV.User or its objectId.\n * @param {Boolean} allowed Whether that user should have read access.\n */\n AV.ACL.prototype.setReadAccess = function(userId, allowed) {\n this._setAccess(\"read\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to read this object.\n * Even if this returns false, the user may still be able to access it if\n * getPublicReadAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getReadAccess = function(userId) {\n return this._getAccess(\"read\", userId);\n };\n\n /**\n * Set whether the given user id is allowed to write this object.\n * @param userId An instance of AV.User or its objectId, or a AV.Role..\n * @param {Boolean} allowed Whether that user should have write access.\n */\n AV.ACL.prototype.setWriteAccess = function(userId, allowed) {\n this._setAccess(\"write\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to write this object.\n * Even if this returns false, the user may still be able to write it if\n * getPublicWriteAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getWriteAccess = function(userId) {\n return this._getAccess(\"write\", userId);\n };\n\n /**\n * Set whether the public is allowed to read this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicReadAccess = function(allowed) {\n this.setReadAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to read this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicReadAccess = function() {\n return this.getReadAccess(PUBLIC_KEY);\n };\n\n /**\n * Set whether the public is allowed to write this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicWriteAccess = function(allowed) {\n this.setWriteAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to write this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicWriteAccess = function() {\n return this.getWriteAccess(PUBLIC_KEY);\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to read this object. Even if this returns false, the role may\n * still be able to write it if a parent role has read access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has read access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleReadAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getReadAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to write this object. Even if this returns false, the role may\n * still be able to write it if a parent role has write access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has write access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleWriteAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getWriteAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to read this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can read this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleReadAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setReadAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to write this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can write this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleWriteAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setWriteAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/acl.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * Contains functions for calling and declaring\n *

\n * Some functions are only available from Cloud Code.\n *

\n *\n * @namespace\n */\n AV.Cloud = AV.Cloud || {};\n\n _.extend(AV.Cloud, /** @lends AV.Cloud */ {\n /**\n * Makes a call to a cloud function.\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n run: function(name, data, options) {\n var request = AVRequest('functions', name, null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response\n * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object}\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result of the function.\n */\n rpc: function(name, data, options) {\n if (_.isArray(data)) {\n return Promise.reject(new Error('Can\\'t pass Array as the param of rpc function in JavaScript SDK.'));\n }\n\n return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Make a call to request server date time.\n * @return {Promise.} A promise that will be resolved with the result\n * of the function.\n * @since 0.5.9\n */\n getServerDate: function() {\n var request = AVRequest(\"date\", null, null, 'GET');\n\n return request.then(function(resp) {\n return AV._decode(resp);\n });\n },\n\n /**\n * Makes a call to request a sms code for operation verification.\n * @param {Object} data The mobile phone number string or a JSON\n * object that contains mobilePhoneNumber,template,op,ttl,name etc.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n requestSmsCode: function(data){\n if(_.isString(data)) {\n data = { mobilePhoneNumber: data };\n }\n if(!data.mobilePhoneNumber) {\n throw new Error('Missing mobilePhoneNumber.');\n }\n var request = AVRequest(\"requestSmsCode\", null, null, 'POST',\n data);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode\n * @param {String} code The sms code sent by AV.Cloud.requestSmsCode\n * @param {phone} phone The mobile phoner number(optional).\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifySmsCode: function(code, phone){\n if(!code)\n throw new Error('Missing sms code.');\n var params = {};\n if(_.isString(phone)) {\n params['mobilePhoneNumber'] = phone;\n }\n\n var request = AVRequest(\"verifySmsCode\", code, null, 'POST',\n params);\n return request;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cloudfunction.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var eventSplitter = /\\s+/;\n var slice = Array.prototype.slice;\n\n /**\n * @class\n *\n *

AV.Events is a fork of Backbone's Events module, provided for your\n * convenience.

\n *\n *

A module that can be mixed in to any object in order to provide\n * it with custom events. You may bind callback functions to an event\n * with `on`, or remove these functions with `off`.\n * Triggering an event fires all callbacks in the order that `on` was\n * called.\n *\n * @private\n * @example\n * var object = {};\n * _.extend(object, AV.Events);\n * object.on('expand', function(){ alert('expanded'); });\n * object.trigger('expand');

\n *\n */\n AV.Events = {\n /**\n * Bind one or more space separated events, `events`, to a `callback`\n * function. Passing `\"all\"` will bind the callback to all events fired.\n */\n on: function(events, callback, context) {\n\n var calls, event, node, tail, list;\n if (!callback) {\n return this;\n }\n events = events.split(eventSplitter);\n calls = this._callbacks || (this._callbacks = {});\n\n // Create an immutable callback list, allowing traversal during\n // modification. The tail is an empty object that will always be used\n // as the next node.\n event = events.shift();\n while (event) {\n list = calls[event];\n node = list ? list.tail : {};\n node.next = tail = {};\n node.context = context;\n node.callback = callback;\n calls[event] = {tail: tail, next: list ? list.next : node};\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Remove one or many callbacks. If `context` is null, removes all callbacks\n * with that function. If `callback` is null, removes all callbacks for the\n * event. If `events` is null, removes all bound callbacks for all events.\n */\n off: function(events, callback, context) {\n var event, calls, node, tail, cb, ctx;\n\n // No events, or removing *all* events.\n if (!(calls = this._callbacks)) {\n return;\n }\n if (!(events || callback || context)) {\n delete this._callbacks;\n return this;\n }\n\n // Loop through the listed events and contexts, splicing them out of the\n // linked list of callbacks if appropriate.\n events = events ? events.split(eventSplitter) : _.keys(calls);\n event = events.shift();\n while (event) {\n node = calls[event];\n delete calls[event];\n if (!node || !(callback || context)) {\n continue;\n }\n // Create a new list, omitting the indicated callbacks.\n tail = node.tail;\n node = node.next;\n while (node !== tail) {\n cb = node.callback;\n ctx = node.context;\n if ((callback && cb !== callback) || (context && ctx !== context)) {\n this.on(event, cb, ctx);\n }\n node = node.next;\n }\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Trigger one or many events, firing all bound callbacks. Callbacks are\n * passed the same arguments as `trigger` is, apart from the event name\n * (unless you're listening on `\"all\"`, which will cause your callback to\n * receive the true name of the event as the first argument).\n */\n trigger: function(events) {\n var event, node, calls, tail, args, all, rest;\n if (!(calls = this._callbacks)) {\n return this;\n }\n all = calls.all;\n events = events.split(eventSplitter);\n rest = slice.call(arguments, 1);\n\n // For each event, walk through the linked list of callbacks twice,\n // first to trigger the event, then to trigger any `\"all\"` callbacks.\n event = events.shift();\n while (event) {\n node = calls[event];\n if (node) {\n tail = node.tail;\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, rest);\n }\n }\n node = all;\n if (node) {\n tail = node.tail;\n args = [event].concat(rest);\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, args);\n }\n }\n event = events.shift();\n }\n\n return this;\n }\n };\n\n /**\n * @function\n */\n AV.Events.bind = AV.Events.on;\n\n /**\n * @function\n */\n AV.Events.unbind = AV.Events.off;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/event.js","const _ = require('underscore');\nconst cos = require('./uploader/cos');\nconst qiniu = require('./uploader/qiniu');\nconst s3 = require('./uploader/s3');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\nconst { tap } = require('./utils');\nconst debug = require('debug')('leancloud:file');\nconst parseBase64 = require('./utils/parse-base64');\n\nmodule.exports = function(AV) {\n\n // 挂载一些配置\n let avConfig = AV._config;\n\n const hexOctet = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);\n\n // port from browserify path module\n // since react-native packager won't shim node modules.\n const extname = (path) => {\n return path.match(/^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/)[4];\n };\n\n const b64Digit = (number) => {\n if (number < 26) {\n return String.fromCharCode(65 + number);\n }\n if (number < 52) {\n return String.fromCharCode(97 + (number - 26));\n }\n if (number < 62) {\n return String.fromCharCode(48 + (number - 52));\n }\n if (number === 62) {\n return '+';\n }\n if (number === 63) {\n return '/';\n }\n throw new Error('Tried to encode large digit ' + number + ' in base64.');\n };\n\n var encodeBase64 = function(array) {\n var chunks = [];\n chunks.length = Math.ceil(array.length / 3);\n _.times(chunks.length, function(i) {\n var b1 = array[i * 3];\n var b2 = array[i * 3 + 1] || 0;\n var b3 = array[i * 3 + 2] || 0;\n\n var has2 = (i * 3 + 1) < array.length;\n var has3 = (i * 3 + 2) < array.length;\n\n chunks[i] = [\n b64Digit((b1 >> 2) & 0x3F),\n b64Digit(((b1 << 4) & 0x30) | ((b2 >> 4) & 0x0F)),\n has2 ? b64Digit(((b2 << 2) & 0x3C) | ((b3 >> 6) & 0x03)) : \"=\",\n has3 ? b64Digit(b3 & 0x3F) : \"=\"\n ].join(\"\");\n });\n return chunks.join(\"\");\n };\n\n /**\n * An AV.File is a local representation of a file that is saved to the AV\n * cloud.\n * @param name {String} The file's name. This will change to a unique value\n * once the file has finished saving.\n * @param data {Array} The data for the file, as either:\n * 1. an Array of byte value Numbers, or\n * 2. an Object like { base64: \"...\" } with a base64-encoded String.\n * 3. a File object selected with a file upload control. (3) only works\n * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.\n * 4.a Buffer object in Node.js runtime.\n *\n * For example:
\n   * var fileUploadControl = $(\"#profilePhotoFileUpload\")[0];\n   * if (fileUploadControl.files.length > 0) {\n   *   var file = fileUploadControl.files[0];\n   *   var name = \"photo.jpg\";\n   *   var file = new AV.File(name, file);\n   *   file.save().then(function() {\n   *     // The file has been saved to AV.\n   *   }, function(error) {\n   *     // The file either could not be read, or could not be saved to AV.\n   *   });\n   * }
\n *\n * @class\n * @param [mimeType] {String} Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n */\n AV.File = function(name, data, mimeType) {\n\n this.attributes = {\n name,\n url: '',\n metaData: {},\n // 用来存储转换后要上传的 base64 String\n base64: '',\n };\n\n if (_.isString(data)) {\n throw new TypeError(\"Creating an AV.File from a String is not yet supported.\");\n }\n if (_.isArray(data)) {\n this.attributes.metaData.size = data.length;\n data = { base64: encodeBase64(data) };\n }\n\n this._extName = '';\n this._data = data;\n\n let owner;\n if (data && data.owner) {\n owner = data.owner;\n } else if (!AV._config.disableCurrentUser) {\n try {\n owner = AV.User.current();\n } catch (error) {\n if ('SYNC_API_NOT_AVAILABLE' === error.code) {\n console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().');\n } else {\n throw error;\n }\n }\n }\n \n this.attributes.metaData.owner = owner ? owner.id : 'unknown';\n\n this.set('mime_type', mimeType);\n };\n\n /**\n * Creates a fresh AV.File object with exists url for saving to AVOS Cloud.\n * @param {String} name the file name\n * @param {String} url the file url.\n * @param {Object} [metaData] the file metadata object.\n * @param {String} [type] Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n * @return {AV.File} the file object\n */\n AV.File.withURL = function(name, url, metaData, type) {\n if (!name || !url){\n throw new Error(\"Please provide file name and url\");\n }\n var file = new AV.File(name, null, type);\n //copy metaData properties to file.\n if (metaData){\n for(var prop in metaData){\n if (!file.attributes.metaData[prop])\n file.attributes.metaData[prop] = metaData[prop];\n }\n }\n file.attributes.url = url;\n //Mark the file is from external source.\n file.attributes.metaData.__source = 'external';\n return file;\n };\n\n /**\n * Creates a file object with exists objectId.\n * @param {String} objectId The objectId string\n * @return {AV.File} the file object\n */\n AV.File.createWithoutData = function(objectId) {\n var file = new AV.File();\n file.id = objectId;\n return file;\n };\n\n AV.File.prototype = {\n className: '_File',\n\n _toFullJSON(seenObjects) {\n var json = _.clone(this.attributes);\n AV._objectEach(json, function(val, key) {\n json[key] = AV._encode(val, seenObjects);\n });\n AV._objectEach(this._operations, function(val, key) {\n json[key] = val;\n });\n\n if (_.has(this, \"id\")) {\n json.objectId = this.id;\n }\n _(['createdAt', 'updatedAt']).each((key) => {\n if (_.has(this, key)) {\n const val = this[key];\n json[key] = _.isDate(val) ? val.toJSON() : val;\n }\n });\n json.__type = \"File\";\n return json;\n },\n\n toJSON() {\n const json = this._toFullJSON();\n // add id and keep __type for backward compatible\n if (_.has(this, 'id')) {\n json.id = this.id;\n }\n return json;\n },\n\n /**\n * Returns the ACL for this file.\n * @returns {AV.ACL} An instance of AV.ACL.\n */\n getACL: function() {\n return this._acl;\n },\n\n /**\n * Sets the ACL to be used for this file.\n * @param {AV.ACL} acl An instance of AV.ACL.\n */\n setACL: function(acl) {\n if (!(acl instanceof AV.ACL)) {\n return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.');\n }\n this._acl = acl;\n },\n\n /**\n * Gets the name of the file. Before save is called, this is the filename\n * given by the user. After save is called, that name gets prefixed with a\n * unique identifier.\n */\n name: function() {\n return this.get('name');\n },\n\n /**\n * Gets the url of the file. It is only available after you save the file or\n * after you get the file from a AV.Object.\n * @return {String}\n */\n url: function() {\n return this.get('url');\n },\n\n /**\n * Gets the attributs of the file object.\n * @param {String} The attribute name which want to get.\n * @returns {Any}\n */\n get: function(attrName) {\n switch (attrName) {\n case 'objectId':\n return this.id;\n case 'url':\n case 'name':\n case 'mime_type':\n case 'metaData':\n case 'createdAt':\n case 'updatedAt':\n return this.attributes[attrName];\n default:\n return this.attributes.metaData[attrName];\n }\n },\n\n /**\n * Set the metaData of the file object.\n * @param {Object} Object is an key value Object for setting metaData.\n * @param {String} attr is an optional metadata key.\n * @param {Object} value is an optional metadata value.\n * @returns {String|Number|Array|Object}\n */\n set: function(...args) {\n const set = (attrName, value) => {\n switch (attrName) {\n case 'name':\n case 'url':\n case 'mime_type':\n case 'base64':\n case 'metaData':\n this.attributes[attrName] = value;\n break;\n default:\n // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面\n this.attributes.metaData[attrName] = value;\n break;\n }\n };\n\n switch (args.length) {\n case 1:\n // 传入一个 Object\n for (var k in args[0]) {\n set(k, args[0][k]);\n }\n break;\n case 2:\n set(args[0], args[1]);\n break;\n }\n },\n\n /**\n *

Returns the file's metadata JSON object if no arguments is given.Returns the\n * metadata value if a key is given.Set metadata value if key and value are both given.

\n *

\n    *  var metadata = file.metaData(); //Get metadata JSON object.\n    *  var size = file.metaData('size');  // Get the size metadata value.\n    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.\n    *

\n * @return {Object} The file's metadata JSON object.\n * @param {String} attr an optional metadata key.\n * @param {Object} value an optional metadata value.\n **/\n metaData: function(attr, value) {\n if (attr && value) {\n this.attributes.metaData[attr] = value;\n return this;\n } else if (attr && !value) {\n return this.attributes.metaData[attr];\n } else {\n return this.attributes.metaData;\n }\n },\n\n /**\n * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。\n * @return {String} 缩略图URL\n * @param {Number} width 宽度,单位:像素\n * @param {Number} heigth 高度,单位:像素\n * @param {Number} quality 质量,1-100的数字,默认100\n * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。\n * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。\n */\n\n thumbnailURL: function(width, height, quality, scaleToFit, fmt) {\n const url = this.attributes.url;\n if (!url) {\n throw new Error('Invalid url.');\n }\n if (!width || !height || width <= 0 || height <= 0 ) {\n throw new Error('Invalid width or height value.');\n }\n quality = quality || 100;\n scaleToFit = !scaleToFit ? true : scaleToFit;\n if (quality <= 0 || quality > 100) {\n throw new Error('Invalid quality value.');\n }\n fmt = fmt || 'png';\n const mode = scaleToFit ? 2: 1;\n return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt;\n },\n\n /**\n * Returns the file's size.\n * @return {Number} The file's size in bytes.\n **/\n size: function() {\n return this.metaData().size;\n },\n\n /**\n * Returns the file's owner.\n * @return {String} The file's owner id.\n */\n ownerId: function() {\n return this.metaData().owner;\n },\n\n /**\n * Destroy the file.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n if (!this.id) {\n return Promise.reject(new Error('The file id is not eixsts.'));\n }\n var request = AVRequest(\"files\", null, this.id, 'DELETE', null, options);\n return request;\n },\n\n /**\n * Request Qiniu upload token\n * @param {string} type\n * @return {Promise} Resolved with the response\n * @private\n */\n _fileToken(type, route = 'fileTokens') {\n let name = this.attributes.name;\n\n let extName = extname(name);\n if (!extName && this._extName) {\n name += this._extName;\n extName = this._extName;\n }\n // Create 16-bits uuid as qiniu key.\n const key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName;\n const data = {\n key,\n name,\n ACL: this._acl,\n mime_type: type,\n metaData: this.attributes.metaData,\n };\n this._qiniu_key = key;\n return AVRequest(route, null, null, 'POST', data);\n },\n\n /**\n * @callback UploadProgressCallback\n * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes\n */\n /**\n * Saves the file to the AV cloud.\n * @param {Object} [options]\n * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。\n * @return {Promise} Promise that is resolved when the save finishes.\n */\n save(options) {\n if (this.id) {\n throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.');\n }\n if (!this._previousSave) {\n if (this._data) {\n let mimeType = this.get('mime_type');\n this._previousSave = this._fileToken(mimeType).then(uploadInfo => {\n if (uploadInfo.mime_type) {\n mimeType = uploadInfo.mime_type;\n this.set('mime_type', mimeType);\n }\n this._token = uploadInfo.token;\n return Promise.resolve().then(() => {\n const data = this._data;\n if (data && data.base64) {\n return parseBase64(data.base64, mimeType);\n }\n if (data && data.blob) {\n if (!data.blob.type && mimeType) {\n data.blob.type = mimeType;\n }\n if (!data.blob.name) {\n data.blob.name = this.get('name');\n }\n if (process.env.CLIENT_PLATFORM === 'ReactNative' || process.env.CLIENT_PLATFORM === 'Weapp') {\n this._extName = extname(data.blob.uri);\n }\n return data.blob;\n }\n if (typeof File !== \"undefined\" && data instanceof File) {\n if (data.size) {\n this.attributes.metaData.size = data.size;\n }\n if (data.name) {\n this._extName = extname(data.name);\n }\n return data;\n }\n if (typeof Buffer !== \"undefined\" && Buffer.isBuffer(data)) {\n this.attributes.metaData.size = data.length;\n return data;\n }\n throw new TypeError('malformed file data');\n }).then(data => {\n let uploadPromise;\n switch (uploadInfo.provider) {\n case 's3':\n uploadPromise = s3(uploadInfo, data, this, options);\n break;\n case 'qcloud':\n uploadPromise = cos(uploadInfo, data, this, options);\n break;\n case 'qiniu':\n default:\n uploadPromise = qiniu(uploadInfo, data, this, options);\n break;\n }\n return uploadPromise.then(\n tap(() => this._callback(true)),\n (error) => {\n this._callback(false);\n throw error;\n }\n );\n });\n });\n } else if (this.attributes.url && this.attributes.metaData.__source === 'external') {\n // external link file.\n const data = {\n name: this.attributes.name,\n ACL: this._acl,\n metaData: this.attributes.metaData,\n mime_type: this.mimeType,\n url: this.attributes.url,\n };\n this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then((response) => {\n this.attributes.name = response.name;\n this.attributes.url = response.url;\n this.id = response.objectId;\n if (response.size) {\n this.attributes.metaData.size = response.size;\n }\n return this;\n });\n }\n }\n return this._previousSave;\n },\n\n _callback(success) {\n AVRequest('fileCallback', null, null, 'post', {\n token: this._token,\n result: success,\n }).catch(debug);\n delete this._token;\n delete this._data;\n },\n\n /**\n * fetch the file from server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option.\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(options) {\n var options = null;\n\n var request = AVRequest('files', null, this.id, 'GET', options);\n return request.then(this._finishFetch.bind(this));\n },\n _finishFetch: function(response) {\n var value = AV.Object.prototype.parse(response);\n value.attributes = {\n name: value.name,\n url: value.url,\n mime_type: value.mime_type,\n bucket: value.bucket,\n };\n value.attributes.metaData = value.metaData || {};\n value.id = value.objectId;\n // clean\n delete value.objectId;\n delete value.metaData;\n delete value.url;\n delete value.name;\n delete value.mime_type;\n delete value.bucket;\n _.extend(this, value);\n return this;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/file.js","var _ = require('underscore');\n\n/*global navigator: false */\nmodule.exports = function(AV) {\n /**\n * Creates a new GeoPoint with any of the following forms:
\n * @example\n * new GeoPoint(otherGeoPoint)\n * new GeoPoint(30, 30)\n * new GeoPoint([30, 30])\n * new GeoPoint({latitude: 30, longitude: 30})\n * new GeoPoint() // defaults to (0, 0)\n * @class\n *\n *

Represents a latitude / longitude point that may be associated\n * with a key in a AVObject or used as a reference point for geo queries.\n * This allows proximity-based queries on the key.

\n *\n *

Only one key in a class may contain a GeoPoint.

\n *\n *

Example:

\n   *   var point = new AV.GeoPoint(30.0, -20.0);\n   *   var object = new AV.Object(\"PlaceObject\");\n   *   object.set(\"location\", point);\n   *   object.save();

\n */\n AV.GeoPoint = function(arg1, arg2) {\n if (_.isArray(arg1)) {\n AV.GeoPoint._validate(arg1[0], arg1[1]);\n this.latitude = arg1[0];\n this.longitude = arg1[1];\n } else if (_.isObject(arg1)) {\n AV.GeoPoint._validate(arg1.latitude, arg1.longitude);\n this.latitude = arg1.latitude;\n this.longitude = arg1.longitude;\n } else if (_.isNumber(arg1) && _.isNumber(arg2)) {\n AV.GeoPoint._validate(arg1, arg2);\n this.latitude = arg1;\n this.longitude = arg2;\n } else {\n this.latitude = 0;\n this.longitude = 0;\n }\n\n // Add properties so that anyone using Webkit or Mozilla will get an error\n // if they try to set values that are out of bounds.\n var self = this;\n if (this.__defineGetter__ && this.__defineSetter__) {\n // Use _latitude and _longitude to actually store the values, and add\n // getters and setters for latitude and longitude.\n this._latitude = this.latitude;\n this._longitude = this.longitude;\n this.__defineGetter__(\"latitude\", function() {\n return self._latitude;\n });\n this.__defineGetter__(\"longitude\", function() {\n return self._longitude;\n });\n this.__defineSetter__(\"latitude\", function(val) {\n AV.GeoPoint._validate(val, self.longitude);\n self._latitude = val;\n });\n this.__defineSetter__(\"longitude\", function(val) {\n AV.GeoPoint._validate(self.latitude, val);\n self._longitude = val;\n });\n }\n };\n\n /**\n * @lends AV.GeoPoint.prototype\n * @property {float} latitude North-south portion of the coordinate, in range\n * [-90, 90]. Throws an exception if set out of range in a modern browser.\n * @property {float} longitude East-west portion of the coordinate, in range\n * [-180, 180]. Throws if set out of range in a modern browser.\n */\n\n /**\n * Throws an exception if the given lat-long is out of bounds.\n * @private\n */\n AV.GeoPoint._validate = function(latitude, longitude) {\n if (latitude < -90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" < -90.0.\");\n }\n if (latitude > 90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" > 90.0.\");\n }\n if (longitude < -180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" < -180.0.\");\n }\n if (longitude > 180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" > 180.0.\");\n }\n };\n\n /**\n * Creates a GeoPoint with the user's current location, if available.\n * @return {Promise.}\n */\n AV.GeoPoint.current = () => new AV.Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(function(location) {\n resolve(new AV.GeoPoint({\n latitude: location.coords.latitude,\n longitude: location.coords.longitude\n }));\n }, reject);\n });\n\n AV.GeoPoint.prototype = {\n /**\n * Returns a JSON representation of the GeoPoint, suitable for AV.\n * @return {Object}\n */\n toJSON: function() {\n AV.GeoPoint._validate(this.latitude, this.longitude);\n return {\n \"__type\": \"GeoPoint\",\n latitude: this.latitude,\n longitude: this.longitude\n };\n },\n\n /**\n * Returns the distance from this GeoPoint to another in radians.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n radiansTo: function(point) {\n var d2r = Math.PI / 180.0;\n var lat1rad = this.latitude * d2r;\n var long1rad = this.longitude * d2r;\n var lat2rad = point.latitude * d2r;\n var long2rad = point.longitude * d2r;\n var deltaLat = lat1rad - lat2rad;\n var deltaLong = long1rad - long2rad;\n var sinDeltaLatDiv2 = Math.sin(deltaLat / 2);\n var sinDeltaLongDiv2 = Math.sin(deltaLong / 2);\n // Square of half the straight line chord distance between both points.\n var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) +\n (Math.cos(lat1rad) * Math.cos(lat2rad) *\n sinDeltaLongDiv2 * sinDeltaLongDiv2));\n a = Math.min(1.0, a);\n return 2 * Math.asin(Math.sqrt(a));\n },\n\n /**\n * Returns the distance from this GeoPoint to another in kilometers.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n kilometersTo: function(point) {\n return this.radiansTo(point) * 6371.0;\n },\n\n /**\n * Returns the distance from this GeoPoint to another in miles.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n milesTo: function(point) {\n return this.radiansTo(point) * 3958.8;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/geopoint.js","const AV = require('./av');\nconst request = require('./request');\n\nconst initialize = (appId, appKey, masterKey, hookKey) => {\n if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) {\n console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.');\n }\n AV.applicationId = appId;\n AV.applicationKey = appKey;\n AV.masterKey = masterKey;\n if (!process.env.CLIENT_PLATFORM) {\n AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY;\n }\n AV._useMasterKey = false;\n};\n\nconst masterKeyWarn = () => {\n console.warn('MasterKey is not supposed to be used in browser.');\n};\n\n/**\n * Call this method first to set up your authentication tokens for AV.\n * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .\n * @function AV.init\n * @param {Object} options\n * @param {String} options.appId application id\n * @param {String} options.appKey application key\n * @param {String} options.masterKey application master key\n*/\n\nAV.init = (...args) => {\n if (args.length === 1) {\n const options = args[0];\n if (typeof options === 'object') {\n if (process.env.CLIENT_PLATFORM && options.masterKey) {\n masterKeyWarn();\n }\n initialize(options.appId, options.appKey, options.masterKey, options.hookKey);\n request.setServerUrlByRegion(options.region);\n } else {\n throw new Error('AV.init(): Parameter is not correct.');\n }\n } else {\n // 兼容旧版本的初始化方法\n if (process.env.CLIENT_PLATFORM && args[3]) {\n masterKeyWarn();\n }\n initialize(...args);\n request.setServerUrlByRegion('cn');\n }\n};\n\n// If we're running in node.js, allow using the master key.\nif (!process.env.CLIENT_PLATFORM) {\n AV.Cloud = AV.Cloud || {};\n /**\n * Switches the LeanCloud SDK to using the Master key. The Master key grants\n * priveleged access to the data in LeanCloud and can be used to bypass ACLs and\n * other restrictions that are applied to the client SDKs.\n *

Available in Cloud Code and Node.js only.\n *

\n */\n AV.Cloud.useMasterKey = function() {\n AV._useMasterKey = true;\n };\n}\n\n// 兼容老版本的初始化方法\nAV.initialize = AV.init;\n\n\n\n// WEBPACK FOOTER //\n// ./src/init.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * 包含了使用了 LeanCloud\n * 离线数据分析功能的函数。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @namespace\n */\n AV.Insight = AV.Insight || {};\n\n _.extend(AV.Insight, /** @lends AV.Insight */ {\n\n /**\n * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用\n * AV.Insight.JobQuery 查询任务状态和结果。\n * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
\n     *                   { \"sql\" : \"select count(*) as c,gender from _User group by gender\",\n     *                     \"saveAs\": {\n     *                         \"className\" : \"UserGender\",\n     *                         \"limit\": 1\n     *                      }\n     *                   }\n     *                  
\n * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n startJob: function(jobConfig, options) {\n if(!jobConfig || !jobConfig.sql) {\n throw new Error('Please provide the sql to run the job.');\n }\n var data = {\n jobConfig: jobConfig,\n appId: AV.applicationId\n };\n var request = AVRequest(\"bigquery\", 'jobs', null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).id;\n });\n },\n\n /**\n * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成\n * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息,\n * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。\n *\n */\n on: function(event, cb) {\n }\n });\n\n /**\n * 创建一个对象,用于查询 Insight 任务状态和结果。\n * @class\n * @param {String} id 任务 id\n * @since 0.5.5\n */\n AV.Insight.JobQuery = function(id, className) {\n if(!id) {\n throw new Error('Please provide the job id.');\n }\n this.id = id;\n this.className = className;\n this._skip = 0;\n this._limit = 100;\n };\n\n AV.Insight.JobQuery.prototype = {\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n this._limit = n;\n return this;\n },\n\n /**\n * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数,\n * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间\n * startTime、endTime 等信息。\n *\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n *\n */\n find: function(options) {\n var params = {\n skip: this._skip,\n limit: this._limit\n };\n\n var request = AVRequest(\"bigquery\", 'jobs', this.id, \"GET\",\n params, options);\n var self = this;\n return request.then(function(response) {\n if(response.error) {\n return AV.Promise.reject(new AVError(response.code, response.error));\n }\n return AV.Promise.resolve(response);\n });\n }\n\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/insight.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst utils = require('./utils');\n\nconst RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt'];\nconst checkReservedKey = key => {\n if (RESERVED_KEYS.indexOf(key) !== -1) {\n throw new Error(`key[${key}] is reserved`);\n }\n};\n\n// AV.Object is analogous to the Java AVObject.\n// It also implements the same interface as a Backbone model.\n\nmodule.exports = function(AV) {\n /**\n * Creates a new model with defined attributes. A client id (cid) is\n * automatically generated and assigned for you.\n *\n *

You won't normally call this method directly. It is recommended that\n * you use a subclass of AV.Object instead, created by calling\n * extend.

\n *\n *

However, if you don't want to use a subclass, or aren't sure which\n * subclass is appropriate, you can use this form:

\n   *     var object = new AV.Object(\"ClassName\");\n   * 
\n * That is basically equivalent to:
\n   *     var MyClass = AV.Object.extend(\"ClassName\");\n   *     var object = new MyClass();\n   * 

\n *\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @see AV.Object.extend\n *\n * @class\n *\n *

The fundamental unit of AV data, which implements the Backbone Model\n * interface.

\n */\n AV.Object = function(attributes, options) {\n // Allow new AV.Object(\"ClassName\") as a shortcut to _create.\n if (_.isString(attributes)) {\n return AV.Object._create.apply(this, arguments);\n }\n\n attributes = attributes || {};\n if (options && options.parse) {\n attributes = this.parse(attributes);\n attributes = this._mergeMagicFields(attributes);\n }\n var defaults = AV._getValue(this, 'defaults');\n if (defaults) {\n attributes = _.extend({}, defaults, attributes);\n }\n if (options && options.collection) {\n this.collection = options.collection;\n }\n\n this._serverData = {}; // The last known data for this object from cloud.\n this._opSetQueue = [{}]; // List of sets of changes to the data.\n this._flags = {};\n this.attributes = {}; // The best estimate of this's current data.\n\n this._hashedJSON = {}; // Hash of values of containers at last save.\n this._escapedAttributes = {};\n this.cid = _.uniqueId('c');\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this.set(attributes, { silent: true });\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this._hasData = true;\n this._previousAttributes = _.clone(this.attributes);\n this.initialize.apply(this, arguments);\n };\n\n /**\n * @lends AV.Object.prototype\n * @property {String} id The objectId of the AV Object.\n */\n\n /**\n * Saves the given list of AV.Object.\n * If any error is encountered, stops and calls the error handler.\n *\n *
\n   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {\n   *     // All the objects were saved.\n   *   }, function(error) {\n   *     // An error occurred while saving one of the objects.\n   *   });\n   *\n   * @param {Array} list A list of AV.Object.\n   */\n  AV.Object.saveAll = function(list, options) {\n    return AV.Object._deepSaveAsync(list, null, options);\n  };\n\n  /**\n   * Fetch the given list of AV.Object.\n   *\n   * @param {AV.Object[]} objects A list of AV.Object\n   * @param {AuthOptions} options\n   * @return {Promise.} The given list of AV.Object, updated\n   */\n\n  AV.Object.fetchAll = (objects, options) =>\n    AV.Promise.resolve().then(() =>\n      AVRequest('batch', null, null, 'POST', {\n        requests: _.map(objects, object => {\n          if (!object.className) throw new Error('object must have className to fetch');\n          if (!object.id) throw new Error('object must have id to fetch');\n          if (object.dirty()) throw new Error('object is modified but not saved');\n          return {\n            method: 'GET',\n            path: `/1.1/classes/${object.className}/${object.id}`,\n          };\n        }),\n      }, options)\n    ).then(function(response) {\n      _.forEach(objects, function(object, i) {\n        if (response[i].success) {\n          object._finishFetch(\n            object.parse(response[i].success));\n        } else {\n          const error = new Error(response[i].error.error);\n          error.code = response[i].error.code;\n          throw error;\n        }\n      });\n      return objects;\n    });\n\n  // Attach all inheritable methods to the AV.Object prototype.\n  _.extend(AV.Object.prototype, AV.Events,\n           /** @lends AV.Object.prototype */ {\n    _fetchWhenSave: false,\n\n    /**\n     * Initialize is an empty function by default. Override it with your own\n     * initialization logic.\n     */\n    initialize: function(){},\n\n   /**\n     * Set whether to enable fetchWhenSave option when updating object.\n     * When set true, SDK would fetch the latest object after saving.\n     * Default is false.\n     *\n     * @deprecated use AV.Object#save with options.fetchWhenSave instead\n     * @param {boolean} enable  true to enable fetchWhenSave option.\n     */\n    fetchWhenSave: function(enable){\n      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');\n      if (!_.isBoolean(enable)) {\n        throw new Error('Expect boolean value for fetchWhenSave');\n      }\n      this._fetchWhenSave = enable;\n    },\n\n   /**\n    * Returns the object's objectId.\n    * @return {String} the objectId.\n    */\n    getObjectId: function() {\n      return this.id;\n    },\n\n   /**\n    * Returns the object's createdAt attribute.\n    * @return {Date}\n    */\n    getCreatedAt: function() {\n      return this.createdAt || this.get('createdAt');\n    },\n\n   /**\n    * Returns the object's updatedAt attribute.\n    * @return {Date}\n    */\n    getUpdatedAt: function() {\n      return this.updatedAt || this.get('updatedAt');\n    },\n\n    /**\n     * Returns a JSON version of the object suitable for saving to AV.\n     * @return {Object}\n     */\n    toJSON: function() {\n      var json = this._toFullJSON();\n      AV._arrayEach([\"__type\", \"className\"],\n                       function(key) { delete json[key]; });\n      return json;\n    },\n\n    _toFullJSON: function(seenObjects) {\n      var json = _.clone(this.attributes);\n      AV._objectEach(json, function(val, key) {\n        json[key] = AV._encode(val, seenObjects);\n      });\n      AV._objectEach(this._operations, function(val, key) {\n        json[key] = val;\n      });\n\n      if (_.has(this, \"id\")) {\n        json.objectId = this.id;\n      }\n      _(['createdAt', 'updatedAt']).each((key) => {\n        if (_.has(this, key)) {\n          const val = this[key];\n          json[key] = _.isDate(val) ? val.toJSON() : val;\n        }\n      });\n      json.__type = \"Object\";\n      json.className = this.className;\n      return json;\n    },\n\n    /**\n     * Updates _hashedJSON to reflect the current state of this object.\n     * Adds any changed hash values to the set of pending changes.\n     * @private\n     */\n    _refreshCache: function() {\n      var self = this;\n      if (self._refreshingCache) {\n        return;\n      }\n      self._refreshingCache = true;\n      AV._objectEach(this.attributes, function(value, key) {\n        if (value instanceof AV.Object) {\n          value._refreshCache();\n        } else if (_.isObject(value)) {\n          if (self._resetCacheForKey(key)) {\n            self.set(key, new AV.Op.Set(value), { silent: true });\n          }\n        }\n      });\n      delete self._refreshingCache;\n    },\n\n    /**\n     * Returns true if this object has been modified since its last\n     * save/refresh.  If an attribute is specified, it returns true only if that\n     * particular attribute has been modified since the last save/refresh.\n     * @param {String} attr An attribute name (optional).\n     * @return {Boolean}\n     */\n    dirty: function(attr) {\n      this._refreshCache();\n\n      var currentChanges = _.last(this._opSetQueue);\n\n      if (attr) {\n        return (currentChanges[attr] ? true : false);\n      }\n      if (!this.id) {\n        return true;\n      }\n      if (_.keys(currentChanges).length > 0) {\n        return true;\n      }\n      return false;\n    },\n\n    /**\n     * Gets a Pointer referencing this Object.\n     * @private\n     */\n    _toPointer: function() {\n      // if (!this.id) {\n      //   throw new Error(\"Can't serialize an unsaved AV.Object\");\n      // }\n      return { __type: \"Pointer\",\n               className: this.className,\n               objectId: this.id };\n    },\n\n    /**\n     * Gets the value of an attribute.\n     * @param {String} attr The string name of an attribute.\n     */\n    get: function(attr) {\n      switch (attr) {\n        case 'objectId':\n          return this.id;\n        case 'createdAt':\n        case 'updatedAt':\n          return this[attr];\n        default:\n          return this.attributes[attr];\n      }\n    },\n\n    /**\n     * Gets a relation on the given class for the attribute.\n     * @param {String} attr The attribute to get the relation for.\n     * @return {AV.Relation}\n     */\n    relation: function(attr) {\n      var value = this.get(attr);\n      if (value) {\n        if (!(value instanceof AV.Relation)) {\n          throw new Error(\"Called relation() on non-relation field \" + attr);\n        }\n        value._ensureParentAndKey(this, attr);\n        return value;\n      } else {\n        return new AV.Relation(this, attr);\n      }\n    },\n\n    /**\n     * Gets the HTML-escaped value of an attribute.\n     */\n    escape: function(attr) {\n      var html = this._escapedAttributes[attr];\n      if (html) {\n        return html;\n      }\n      var val = this.attributes[attr];\n      var escaped;\n      if (utils.isNullOrUndefined(val)) {\n        escaped = '';\n      } else {\n        escaped = _.escape(val.toString());\n      }\n      this._escapedAttributes[attr] = escaped;\n      return escaped;\n    },\n\n    /**\n     * Returns true if the attribute contains a value that is not\n     * null or undefined.\n     * @param {String} attr The string name of the attribute.\n     * @return {Boolean}\n     */\n    has: function(attr) {\n      return !utils.isNullOrUndefined(this.attributes[attr]);\n    },\n\n    /**\n     * Pulls \"special\" fields like objectId, createdAt, etc. out of attrs\n     * and puts them on \"this\" directly.  Removes them from attrs.\n     * @param attrs - A dictionary with the data for this AV.Object.\n     * @private\n     */\n    _mergeMagicFields: function(attrs) {\n      // Check for changes of magic fields.\n      var model = this;\n      var specialFields = [\"objectId\", \"createdAt\", \"updatedAt\"];\n      AV._arrayEach(specialFields, function(attr) {\n        if (attrs[attr]) {\n          if (attr === \"objectId\") {\n            model.id = attrs[attr];\n          } else if ((attr === \"createdAt\" || attr === \"updatedAt\") &&\n                     !_.isDate(attrs[attr])) {\n            model[attr] = AV._parseDate(attrs[attr]);\n          } else { \n            model[attr] = attrs[attr]; \n          }\n          delete attrs[attr];\n        }\n      });\n      return attrs;\n    },\n\n    /**\n     * Returns the json to be sent to the server.\n     * @private\n     */\n    _startSave: function() {\n      this._opSetQueue.push({});\n    },\n\n    /**\n     * Called when a save fails because of an error. Any changes that were part\n     * of the save need to be merged with changes made after the save. This\n     * might throw an exception is you do conflicting operations. For example,\n     * if you do:\n     *   object.set(\"foo\", \"bar\");\n     *   object.set(\"invalid field name\", \"baz\");\n     *   object.save();\n     *   object.increment(\"foo\");\n     * then this will throw when the save fails and the client tries to merge\n     * \"bar\" with the +1.\n     * @private\n     */\n    _cancelSave: function() {\n      var self = this;\n      var failedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      var nextChanges = _.first(this._opSetQueue);\n      AV._objectEach(failedChanges, function(op, key) {\n        var op1 = failedChanges[key];\n        var op2 = nextChanges[key];\n        if (op1 && op2) {\n          nextChanges[key] = op2._mergeWithPrevious(op1);\n        } else if (op1) {\n          nextChanges[key] = op1;\n        }\n      });\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a save completes successfully. This merges the changes that\n     * were saved into the known server data, and overrides it with any data\n     * sent directly from the server.\n     * @private\n     */\n    _finishSave: function(serverData) {\n      // Grab a copy of any object referenced by this object. These instances\n      // may have already been fetched, and we don't want to lose their data.\n      // Note that doing it like this means we will unify separate copies of the\n      // same object, but that's a risk we have to take.\n      var fetchedObjects = {};\n      AV._traverse(this.attributes, function(object) {\n        if (object instanceof AV.Object && object.id && object._hasData) {\n          fetchedObjects[object.id] = object;\n        }\n      });\n\n      var savedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      this._applyOpSet(savedChanges, this._serverData);\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n\n        // Look for any objects that might have become unfetched and fix them\n        // by replacing their values with the previously observed values.\n        var fetched = AV._traverse(self._serverData[key], function(object) {\n          if (object instanceof AV.Object && fetchedObjects[object.id]) {\n            return fetchedObjects[object.id];\n          }\n        });\n        if (fetched) {\n          self._serverData[key] = fetched;\n        }\n      });\n      this._rebuildAllEstimatedData();\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a fetch or login is complete to set the known server data to\n     * the given object.\n     * @private\n     */\n    _finishFetch: function(serverData, hasData) {\n      // Clear out any changes the user might have made previously.\n      this._opSetQueue = [{}];\n\n      // Bring in all the new server data.\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n      });\n\n      // Refresh the attributes.\n      this._rebuildAllEstimatedData();\n\n      // Clear out the cache of mutable containers.\n      this._refreshCache();\n      this._opSetQueue = [{}];\n\n      this._hasData = hasData;\n    },\n\n    /**\n     * Applies the set of AV.Op in opSet to the object target.\n     * @private\n     */\n    _applyOpSet: function(opSet, target) {\n      var self = this;\n      AV._objectEach(opSet, function(change, key) {\n        target[key] = change._estimate(target[key], self, key);\n        if (target[key] === AV.Op._UNSET) {\n          delete target[key];\n        }\n      });\n    },\n\n    /**\n     * Replaces the cached value for key with the current value.\n     * Returns true if the new value is different than the old value.\n     * @private\n     */\n    _resetCacheForKey: function(key) {\n      var value = this.attributes[key];\n      if (_.isObject(value) &&\n          !(value instanceof AV.Object) &&\n          !(value instanceof AV.File)) {\n\n        value = value.toJSON ? value.toJSON() : value;\n        var json = JSON.stringify(value);\n        if (this._hashedJSON[key] !== json) {\n          var wasSet = !! this._hashedJSON[key];\n          this._hashedJSON[key] = json;\n          return wasSet;\n        }\n      }\n      return false;\n    },\n\n    /**\n     * Populates attributes[key] by starting with the last known data from the\n     * server, and applying all of the local changes that have been made to that\n     * key since then.\n     * @private\n     */\n    _rebuildEstimatedDataForKey: function(key) {\n      var self = this;\n      delete this.attributes[key];\n      if (this._serverData[key]) {\n        this.attributes[key] = this._serverData[key];\n      }\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        var op = opSet[key];\n        if (op) {\n          self.attributes[key] = op._estimate(self.attributes[key], self, key);\n          if (self.attributes[key] === AV.Op._UNSET) {\n            delete self.attributes[key];\n          } else {\n            self._resetCacheForKey(key);\n          }\n        }\n      });\n    },\n\n    /**\n     * Populates attributes by starting with the last known data from the\n     * server, and applying all of the local changes that have been made since\n     * then.\n     * @private\n     */\n    _rebuildAllEstimatedData: function() {\n      var self = this;\n\n      var previousAttributes = _.clone(this.attributes);\n\n      this.attributes = _.clone(this._serverData);\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        self._applyOpSet(opSet, self.attributes);\n        AV._objectEach(opSet, function(op, key) {\n          self._resetCacheForKey(key);\n        });\n      });\n\n      // Trigger change events for anything that changed because of the fetch.\n      AV._objectEach(previousAttributes, function(oldValue, key) {\n        if (self.attributes[key] !== oldValue) {\n          self.trigger('change:' + key, self, self.attributes[key], {});\n        }\n      });\n      AV._objectEach(this.attributes, function(newValue, key) {\n        if (!_.has(previousAttributes, key)) {\n          self.trigger('change:' + key, self, newValue, {});\n        }\n      });\n    },\n\n    /**\n     * Sets a hash of model attributes on the object, firing\n     * \"change\" unless you choose to silence it.\n     *\n     * 

You can call it with an object containing keys and values, or with one\n * key and value. For example:

\n     *   gameTurn.set({\n     *     player: player1,\n     *     diceRoll: 2\n     *   }, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"currentPlayer\", player2, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"finished\", true);

\n *\n * @param {String} key The key to set.\n * @param {Any} value The value to give it.\n * @param {Object} [options]\n * @param {Boolean} [options.silent]\n * @return {AV.Object} self if succeeded, throws if the value is not valid.\n * @see AV.Object#validate\n */\n set: function(key, value, options) {\n var attrs;\n if (_.isObject(key) || utils.isNullOrUndefined(key)) {\n attrs = _.mapObject(key, function(v, k) {\n checkReservedKey(k);\n return AV._decode(v, k);\n });\n options = value;\n } else {\n attrs = {};\n checkReservedKey(key);\n attrs[key] = AV._decode(value, key);\n }\n\n // Extract attributes and options.\n options = options || {};\n if (!attrs) {\n return this;\n }\n if (attrs instanceof AV.Object) {\n attrs = attrs.attributes;\n }\n\n // If the unset option is used, every attribute should be a Unset.\n if (options.unset) {\n AV._objectEach(attrs, function(unused_value, key) {\n attrs[key] = new AV.Op.Unset();\n });\n }\n\n // Apply all the attributes to get the estimated values.\n var dataToValidate = _.clone(attrs);\n var self = this;\n AV._objectEach(dataToValidate, function(value, key) {\n if (value instanceof AV.Op) {\n dataToValidate[key] = value._estimate(self.attributes[key],\n self, key);\n if (dataToValidate[key] === AV.Op._UNSET) {\n delete dataToValidate[key];\n }\n }\n });\n\n // Run validation.\n this._validate(attrs, options);\n\n options.changes = {};\n var escaped = this._escapedAttributes;\n var prev = this._previousAttributes || {};\n\n // Update attributes.\n AV._arrayEach(_.keys(attrs), function(attr) {\n var val = attrs[attr];\n\n // If this is a relation object we need to set the parent correctly,\n // since the location where it was parsed does not have access to\n // this object.\n if (val instanceof AV.Relation) {\n val.parent = self;\n }\n\n if (!(val instanceof AV.Op)) {\n val = new AV.Op.Set(val);\n }\n\n // See if this change will actually have any effect.\n var isRealChange = true;\n if (val instanceof AV.Op.Set &&\n _.isEqual(self.attributes[attr], val.value)) {\n isRealChange = false;\n }\n\n if (isRealChange) {\n delete escaped[attr];\n if (options.silent) {\n self._silent[attr] = true;\n } else {\n options.changes[attr] = true;\n }\n }\n\n var currentChanges = _.last(self._opSetQueue);\n currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]);\n self._rebuildEstimatedDataForKey(attr);\n\n if (isRealChange) {\n self.changed[attr] = self.attributes[attr];\n if (!options.silent) {\n self._pending[attr] = true;\n }\n } else {\n delete self.changed[attr];\n delete self._pending[attr];\n }\n });\n\n if (!options.silent) {\n this.change(options);\n }\n return this;\n },\n\n /**\n * Remove an attribute from the model, firing \"change\" unless\n * you choose to silence it. This is a noop if the attribute doesn't\n * exist.\n */\n unset: function(attr, options) {\n options = options || {};\n options.unset = true;\n return this.set(attr, null, options);\n },\n\n /**\n * Atomically increments the value of the given attribute the next time the\n * object is saved. If no amount is specified, 1 is used by default.\n *\n * @param attr {String} The key.\n * @param amount {Number} The amount to increment by.\n */\n increment: function(attr, amount) {\n if (_.isUndefined(amount) || _.isNull(amount)) {\n amount = 1;\n }\n return this.set(attr, new AV.Op.Increment(amount));\n },\n\n /**\n * Atomically add an object to the end of the array associated with a given\n * key.\n * @param attr {String} The key.\n * @param item {} The item to add.\n */\n add: function(attr, item) {\n return this.set(attr, new AV.Op.Add(utils.ensureArray(item)));\n },\n\n /**\n * Atomically add an object to the array associated with a given key, only\n * if it is not already present in the array. The position of the insert is\n * not guaranteed.\n *\n * @param attr {String} The key.\n * @param item {} The object to add.\n */\n addUnique: function(attr, item) {\n return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item)));\n },\n\n /**\n * Atomically remove all instances of an object from the array associated\n * with a given key.\n *\n * @param attr {String} The key.\n * @param item {} The object to remove.\n */\n remove: function(attr, item) {\n return this.set(attr, new AV.Op.Remove(utils.ensureArray(item)));\n },\n\n /**\n * Returns an instance of a subclass of AV.Op describing what kind of\n * modification has been performed on this field since the last time it was\n * saved. For example, after calling object.increment(\"x\"), calling\n * object.op(\"x\") would return an instance of AV.Op.Increment.\n *\n * @param attr {String} The key.\n * @returns {AV.Op} The operation, or undefined if none.\n */\n op: function(attr) {\n return _.last(this._opSetQueue)[attr];\n },\n\n /**\n * Clear all attributes on the model, firing \"change\" unless\n * you choose to silence it.\n */\n clear: function(options) {\n options = options || {};\n options.unset = true;\n var keysToClear = _.extend(this.attributes, this._operations);\n return this.set(keysToClear, options);\n },\n\n /**\n * Returns a JSON-encoded set of operations to be sent with the next save\n * request.\n * @private\n */\n _getSaveJSON: function() {\n var json = _.clone(_.first(this._opSetQueue));\n AV._objectEach(json, function(op, key) {\n json[key] = op.toJSON();\n });\n return json;\n },\n\n /**\n * Returns true if this object can be serialized for saving.\n * @private\n */\n _canBeSerialized: function() {\n return AV.Object._canBeSerializedAsValue(this.attributes);\n },\n\n /**\n * Fetch the model from the server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * triggering a \"change\" event.\n * @param {Object} fetchOptions Optional options to set 'keys' and\n * 'include' option.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(fetchOptions = {}, options) {\n if (_.isArray(fetchOptions.keys)) {\n fetchOptions.keys = fetchOptions.keys.join(',');\n }\n if (_.isArray(fetchOptions.include)) {\n fetchOptions.include = fetchOptions.include.join(',');\n }\n\n var self = this;\n var request = AVRequest('classes', this.className, this.id, 'GET',\n fetchOptions, options);\n return request.then(function(response) {\n self._finishFetch(self.parse(response), true);\n return self;\n });\n },\n\n /**\n * Set a hash of model attributes, and save the model to the server.\n * updatedAt will be updated when the request returns.\n * You can either call it as:
\n     *   object.save();
\n * or
\n     *   object.save(null, options);
\n * or
\n     *   object.save(attrs, options);
\n * or
\n     *   object.save(key, value, options);
\n *\n * For example,
\n     *   gameTurn.save({\n     *     player: \"Jake Cutter\",\n     *     diceRoll: 2\n     *   }).then(function(gameTurnAgain) {\n     *     // The save was successful.\n     *   }, function(error) {\n     *     // The save failed.  Error is an instance of AVError.\n     *   });
\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded\n * @param {AV.Query} options.query Save object only when it matches the query\n * @return {AV.Promise} A promise that is fulfilled when the save\n * completes.\n * @see AVError\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n\n options = _.clone(options) || {};\n if (options.wait) {\n current = _.clone(this.attributes);\n }\n\n var setOptions = _.clone(options) || {};\n if (setOptions.wait) {\n setOptions.silent = true;\n }\n if (attrs) {\n this.set(attrs, setOptions);\n }\n\n var model = this;\n\n // If there is any unsaved child, save it first.\n model._refreshCache();\n\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(model.attributes,\n unsavedChildren,\n unsavedFiles);\n if (unsavedChildren.length + unsavedFiles.length > 0) {\n return AV.Object._deepSaveAsync(this.attributes, model, options).then(function() {\n return model.save(null, options);\n });\n }\n\n this._startSave();\n this._saving = (this._saving || 0) + 1;\n\n this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve();\n this._allPreviousSaves = this._allPreviousSaves.catch(e => {}).then(function() {\n var method = model.id ? 'PUT' : 'POST';\n\n var json = model._getSaveJSON();\n\n if(model._fetchWhenSave){\n //Sepcial-case fetchWhenSave when updating object.\n json._fetchWhenSave = true;\n }\n\n if (options.fetchWhenSave) {\n json._fetchWhenSave = true;\n }\n if (options.query) {\n var queryJSON;\n if (typeof options.query.toJSON === 'function') {\n queryJSON = options.query.toJSON();\n if (queryJSON) {\n json._where = queryJSON.where;\n }\n }\n if (!json._where) {\n var error = new Error('options.query is not an AV.Query');\n throw error;\n }\n }\n\n _.extend(json, model._flags);\n\n var route = \"classes\";\n var className = model.className;\n if (model.className === \"_User\" && !model.id) {\n // Special-case user sign-up.\n route = \"users\";\n className = null;\n }\n //hook makeRequest in options.\n var makeRequest = options._makeRequest || AVRequest;\n var request = makeRequest(route, className, model.id, method, json, options);\n\n request = request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n if (options.wait) {\n serverAttrs = _.extend(attrs || {}, serverAttrs);\n }\n model._finishSave(serverAttrs);\n if (options.wait) {\n model.set(current, setOptions);\n }\n return model;\n\n }, function(error) {\n model._cancelSave();\n throw error;\n });\n\n return request;\n });\n return this._allPreviousSaves;\n },\n\n /**\n * Destroy this model on the server if it was already persisted.\n * Optimistically removes the model from its collection, if it has one.\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} [options.wait] wait for the server to respond\n * before removal.\n *\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n options = options || {};\n var model = this;\n\n var triggerDestroy = function() {\n model.trigger('destroy', model, model.collection, options);\n };\n\n if (!this.id) {\n return triggerDestroy();\n }\n\n if (!options.wait) {\n triggerDestroy();\n }\n\n var request =\n AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options);\n return request.then(function() {\n if (options.wait) {\n triggerDestroy();\n }\n return model;\n });\n },\n\n /**\n * Converts a response into the hash of attributes to be set on the model.\n * @ignore\n */\n parse: function(resp) {\n var output = _.clone(resp);\n _([\"createdAt\", \"updatedAt\"]).each(function(key) {\n if (output[key]) {\n output[key] = AV._parseDate(output[key]);\n }\n });\n if (!output.updatedAt) {\n output.updatedAt = output.createdAt;\n }\n return output;\n },\n\n /**\n * Creates a new model with identical attributes to this one.\n * @return {AV.Object}\n */\n clone: function() {\n return new this.constructor(this.attributes);\n },\n\n /**\n * Returns true if this object has never been saved to AV.\n * @return {Boolean}\n */\n isNew: function() {\n return !this.id;\n },\n\n /**\n * Call this method to manually fire a `\"change\"` event for this model and\n * a `\"change:attribute\"` event for each changed attribute.\n * Calling this will cause all objects observing the model to update.\n */\n change: function(options) {\n options = options || {};\n var changing = this._changing;\n this._changing = true;\n\n // Silent changes become pending changes.\n var self = this;\n AV._objectEach(this._silent, function(attr) {\n self._pending[attr] = true;\n });\n\n // Silent changes are triggered.\n var changes = _.extend({}, options.changes, this._silent);\n this._silent = {};\n AV._objectEach(changes, function(unused_value, attr) {\n self.trigger('change:' + attr, self, self.get(attr), options);\n });\n if (changing) {\n return this;\n }\n\n // This is to get around lint not letting us make a function in a loop.\n var deleteChanged = function(value, attr) {\n if (!self._pending[attr] && !self._silent[attr]) {\n delete self.changed[attr];\n }\n };\n\n // Continue firing `\"change\"` events while there are pending changes.\n while (!_.isEmpty(this._pending)) {\n this._pending = {};\n this.trigger('change', this, options);\n // Pending and silent changes still remain.\n AV._objectEach(this.changed, deleteChanged);\n self._previousAttributes = _.clone(this.attributes);\n }\n\n this._changing = false;\n return this;\n },\n\n /**\n * Determine if the model has changed since the last \"change\"\n * event. If you specify an attribute name, determine if that attribute\n * has changed.\n * @param {String} attr Optional attribute name\n * @return {Boolean}\n */\n hasChanged: function(attr) {\n if (!arguments.length) {\n return !_.isEmpty(this.changed);\n }\n return this.changed && _.has(this.changed, attr);\n },\n\n /**\n * Returns an object containing all the attributes that have changed, or\n * false if there are no changed attributes. Useful for determining what\n * parts of a view need to be updated and/or what attributes need to be\n * persisted to the server. Unset attributes will be set to undefined.\n * You can also pass an attributes object to diff against the model,\n * determining if there *would be* a change.\n */\n changedAttributes: function(diff) {\n if (!diff) {\n return this.hasChanged() ? _.clone(this.changed) : false;\n }\n var changed = {};\n var old = this._previousAttributes;\n AV._objectEach(diff, function(diffVal, attr) {\n if (!_.isEqual(old[attr], diffVal)) {\n changed[attr] = diffVal;\n }\n });\n return changed;\n },\n\n /**\n * Gets the previous value of an attribute, recorded at the time the last\n * \"change\" event was fired.\n * @param {String} attr Name of the attribute to get.\n */\n previous: function(attr) {\n if (!arguments.length || !this._previousAttributes) {\n return null;\n }\n return this._previousAttributes[attr];\n },\n\n /**\n * Gets all of the attributes of the model at the time of the previous\n * \"change\" event.\n * @return {Object}\n */\n previousAttributes: function() {\n return _.clone(this._previousAttributes);\n },\n\n /**\n * Checks if the model is currently in a valid state. It's only possible to\n * get into an *invalid* state if you're using silent changes.\n * @return {Boolean}\n */\n isValid: function() {\n try {\n this.validate(this.attributes);\n } catch (error) {\n return false;\n }\n return true;\n },\n\n /**\n * You should not call this function directly unless you subclass\n * AV.Object, in which case you can override this method\n * to provide additional validation on set and\n * save. Your implementation should throw an Error if\n * the attrs is invalid\n *\n * @param {Object} attrs The current data to validate.\n * @see AV.Object#set\n */\n validate: function(attrs) {\n if (_.has(attrs, \"ACL\") && !(attrs.ACL instanceof AV.ACL)) {\n throw new AVError(AVError.OTHER_CAUSE,\n \"ACL must be a AV.ACL.\");\n }\n },\n\n /**\n * Run validation against a set of incoming attributes, returning `true`\n * if all is well. If a specific `error` callback has been passed,\n * call that instead of firing the general `\"error\"` event.\n * @private\n */\n _validate: function(attrs, options) {\n if (options.silent || !this.validate) {\n return;\n }\n attrs = _.extend({}, this.attributes, attrs);\n this.validate(attrs);\n },\n\n /**\n * Returns the ACL for this object.\n * @returns {AV.ACL} An instance of AV.ACL.\n * @see AV.Object#get\n */\n getACL: function() {\n return this.get(\"ACL\");\n },\n\n /**\n * Sets the ACL to be used for this object.\n * @param {AV.ACL} acl An instance of AV.ACL.\n * @param {Object} options Optional Backbone-like options object to be\n * passed in to set.\n * @return {Boolean} Whether the set passed validation.\n * @see AV.Object#set\n */\n setACL: function(acl, options) {\n return this.set(\"ACL\", acl, options);\n },\n\n disableBeforeHook: function() {\n this.ignoreHook('beforeSave');\n this.ignoreHook('beforeUpdate');\n this.ignoreHook('beforeDelete');\n },\n\n disableAfterHook: function() {\n this.ignoreHook('afterSave');\n this.ignoreHook('afterUpdate');\n this.ignoreHook('afterDelete');\n },\n\n ignoreHook: function(hookName) {\n if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) {\n console.trace('Unsupported hookName: ' + hookName);\n }\n\n if (!AV.hookKey) {\n console.trace('ignoreHook required hookKey');\n }\n\n if (!this._flags.__ignore_hooks) {\n this._flags.__ignore_hooks = [];\n }\n\n this._flags.__ignore_hooks.push(hookName);\n }\n });\n\n /**\n * Creates an instance of a subclass of AV.Object for the give classname\n * and id.\n * @param {String} className The name of the AV class backing this model.\n * @param {String} id The object id of this model.\n * @return {AV.Object} A new subclass instance of AV.Object.\n */\n AV.Object.createWithoutData = function(className, id, hasData){\n var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n result.id = id;\n result._hasData = hasData;\n return result;\n };\n /**\n * Delete objects in batch.\n * @param {AV.Object[]} objects The AV.Object array to be deleted.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n AV.Object.destroyAll = function(objects, options = {}){\n if (!objects || objects.length === 0){\n\t\t return AV.Promise.resolve();\n }\n const objectsByClassNameAndFlags = _.groupBy(objects, object => JSON.stringify({\n className: object.className,\n flags: object._flags\n }));\n const body = {\n requests: _.map(objectsByClassNameAndFlags, objects => {\n const ids = _.map(objects, 'id').join(',');\n return {\n method: 'DELETE',\n path: `/1.1/classes/${objects[0].className}/${ids}`,\n body: objects[0]._flags\n }\n })\n };\n return AVRequest('batch', null, null, 'POST', body, options);\n };\n\n /**\n * Returns the appropriate subclass for making new instances of the given\n * className string.\n * @private\n */\n AV.Object._getSubclass = function(className) {\n if (!_.isString(className)) {\n throw new Error('AV.Object._getSubclass requires a string argument.');\n }\n var ObjectClass = AV.Object._classMap[className];\n if (!ObjectClass) {\n ObjectClass = AV.Object.extend(className);\n AV.Object._classMap[className] = ObjectClass;\n }\n return ObjectClass;\n };\n\n /**\n * Creates an instance of a subclass of AV.Object for the given classname.\n * @private\n */\n AV.Object._create = function(className, attributes, options, noDefaultACL) {\n var ObjectClass = AV.Object._getSubclass(className);\n return new ObjectClass(attributes, options, noDefaultACL);\n };\n\n // Set up a map of className to class so that we can create new instances of\n // AV Objects from JSON automatically.\n AV.Object._classMap = {};\n\n AV.Object._extend = AV._extend;\n\n /**\n * Creates a new model with defined attributes,\n * It's the same with\n *
\n   *   new AV.Object(attributes, options);\n   *  
\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @return {AV.Object}\n * @since v0.4.4\n * @see AV.Object\n * @see AV.Object.extend\n */\n AV.Object['new'] = function(attributes, options){\n return new AV.Object(attributes, options);\n };\n\n /**\n * Creates a new subclass of AV.Object for the given AV class name.\n *\n *

Every extension of a AV class will inherit from the most recent\n * previous extension of that class. When a AV.Object is automatically\n * created by parsing JSON, it will use the most recent extension of that\n * class.

\n *\n *

You should call either:

\n   *     var MyClass = AV.Object.extend(\"MyClass\", {\n   *         Instance properties\n   *     }, {\n   *         Class properties\n   *     });
\n * or, for Backbone compatibility:
\n   *     var MyClass = AV.Object.extend({\n   *         className: \"MyClass\",\n   *         Other instance properties\n   *     }, {\n   *         Class properties\n   *     });

\n *\n * @param {String} className The name of the AV class backing this model.\n * @param {Object} protoProps Instance properties to add to instances of the\n * class returned from this method.\n * @param {Object} classProps Class properties to add the class returned from\n * this method.\n * @return {Class} A new subclass of AV.Object.\n */\n AV.Object.extend = function(className, protoProps, classProps) {\n // Handle the case with only two args.\n if (!_.isString(className)) {\n if (className && _.has(className, \"className\")) {\n return AV.Object.extend(className.className, className, protoProps);\n } else {\n throw new Error(\n \"AV.Object.extend's first argument should be the className.\");\n }\n }\n\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n className = \"_User\";\n }\n\n var NewClassObject = null;\n if (_.has(AV.Object._classMap, className)) {\n var OldClassObject = AV.Object._classMap[className];\n // This new subclass has been told to extend both from \"this\" and from\n // OldClassObject. This is multiple inheritance, which isn't supported.\n // For now, let's just pick one.\n if (protoProps || classProps) {\n NewClassObject = OldClassObject._extend(protoProps, classProps);\n } else {\n return OldClassObject;\n }\n } else {\n protoProps = protoProps || {};\n protoProps._className = className;\n NewClassObject = this._extend(protoProps, classProps);\n }\n // Extending a subclass should reuse the classname automatically.\n NewClassObject.extend = function(arg0) {\n if (_.isString(arg0) || (arg0 && _.has(arg0, \"className\"))) {\n return AV.Object.extend.apply(NewClassObject, arguments);\n }\n var newArguments = [className].concat(_.toArray(arguments));\n return AV.Object.extend.apply(NewClassObject, newArguments);\n };\n NewClassObject['new'] = function(attributes, options){\n return new NewClassObject(attributes, options);\n };\n AV.Object._classMap[className] = NewClassObject;\n return NewClassObject;\n };\n\n // ES6 class syntax support\n Object.defineProperty(AV.Object.prototype, 'className', {\n get: function(){\n const className = this._className || this.constructor._LCClassName || this.constructor.name;\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n return \"_User\";\n }\n return className;\n },\n });\n\n /**\n * Register a class.\n * If a subclass of AV.Object is defined with your own implement\n * rather then AV.Object.extend, the subclass must be registered.\n * @param {Function} klass A subclass of AV.Object\n * @param {String} [name] Specify the name of the class. Useful when the class might be uglified.\n * @example\n * class Person extend AV.Object {}\n * AV.Object.register(Person);\n */\n AV.Object.register = (klass, name) => {\n if (!(klass.prototype instanceof AV.Object)) {\n throw new Error('registered class is not a subclass of AV.Object');\n }\n const className = name || klass.name;\n if (!className.length) {\n throw new Error('registered class must be named');\n }\n if (name) {\n klass._LCClassName = name;\n }\n AV.Object._classMap[className] = klass;\n };\n\n AV.Object._findUnsavedChildren = function(object, children, files) {\n AV._traverse(object, function(object) {\n if (object instanceof AV.Object) {\n object._refreshCache();\n if (object.dirty()) {\n children.push(object);\n }\n return;\n }\n\n if (object instanceof AV.File) {\n if (!object.url() && !object.id) {\n files.push(object);\n }\n return;\n }\n });\n };\n\n AV.Object._canBeSerializedAsValue = function(object) {\n var canBeSerializedAsValue = true;\n\n if (object instanceof AV.Object || object instanceof AV.File) {\n canBeSerializedAsValue = !!object.id;\n\n } else if (_.isArray(object)) {\n AV._arrayEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n\n } else if (_.isObject(object)) {\n AV._objectEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n }\n\n return canBeSerializedAsValue;\n };\n\n AV.Object._deepSaveAsync = function(object, model, options) {\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles);\n if(model) {\n unsavedChildren = _.filter(unsavedChildren, function(object) {\n return object != model;\n });\n }\n\n var promise = AV.Promise.resolve();\n _.each(unsavedFiles, function(file) {\n promise = promise.then(function() {\n return file.save();\n });\n });\n\n var objects = _.uniq(unsavedChildren);\n var remaining = _.uniq(objects);\n\n return promise.then(function() {\n return AV.Promise._continueWhile(function() {\n return remaining.length > 0;\n }, function() {\n\n // Gather up all the objects that can be saved in this batch.\n var batch = [];\n var newRemaining = [];\n AV._arrayEach(remaining, function(object) {\n // Limit batches to 20 objects.\n if (batch.length > 20) {\n newRemaining.push(object);\n return;\n }\n\n if (object._canBeSerialized()) {\n batch.push(object);\n } else {\n newRemaining.push(object);\n }\n });\n remaining = newRemaining;\n\n // If we can't save any objects, there must be a circular reference.\n if (batch.length === 0) {\n return AV.Promise.reject(\n new AVError(AVError.OTHER_CAUSE,\n \"Tried to save a batch with a cycle.\"));\n }\n\n // Reserve a spot in every object's save queue.\n var readyToStart = AV.Promise.resolve(_.map(batch, function(object) {\n return object._allPreviousSaves || AV.Promise.resolve();\n }));\n\n // Save a single batch, whether previous saves succeeded or failed.\n const bathSavePromise = readyToStart.then(() =>\n AVRequest(\"batch\", null, null, \"POST\", {\n requests: _.map(batch, function(object) {\n var json = object._getSaveJSON();\n _.extend(json, object._flags);\n var method = \"POST\";\n\n var path = \"/1.1/classes/\" + object.className;\n if (object.id) {\n path = path + \"/\" + object.id;\n method = \"PUT\";\n }\n\n object._startSave();\n\n return {\n method: method,\n path: path,\n body: json\n };\n })\n\n }, options).then(function(response) {\n var error;\n AV._arrayEach(batch, function(object, i) {\n if (response[i].success) {\n object._finishSave(\n object.parse(response[i].success));\n } else {\n error = error || response[i].error;\n object._cancelSave();\n }\n });\n if (error) {\n return AV.Promise.reject(\n new AVError(error.code, error.error));\n }\n\n })\n );\n AV._arrayEach(batch, function(object) {\n object._allPreviousSaves = bathSavePromise;\n });\n return bathSavePromise;\n });\n }).then(function() {\n return object;\n });\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/object.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n\n /**\n * @private\n * @class\n * A AV.Op is an atomic operation that can be applied to a field in a\n * AV.Object. For example, calling object.set(\"foo\", \"bar\")\n * is an example of a AV.Op.Set. Calling object.unset(\"foo\")\n * is a AV.Op.Unset. These operations are stored in a AV.Object and\n * sent to the server as part of object.save() operations.\n * Instances of AV.Op should be immutable.\n *\n * You should not create subclasses of AV.Op or instantiate AV.Op\n * directly.\n */\n AV.Op = function() {\n this._initialize.apply(this, arguments);\n };\n\n AV.Op.prototype = {\n _initialize: function() {}\n };\n\n _.extend(AV.Op, {\n /**\n * To create a new Op, call AV.Op._extend();\n * @private\n */\n _extend: AV._extend,\n\n // A map of __op string to decoder function.\n _opDecoderMap: {},\n\n /**\n * Registers a function to convert a json object with an __op field into an\n * instance of a subclass of AV.Op.\n * @private\n */\n _registerDecoder: function(opName, decoder) {\n AV.Op._opDecoderMap[opName] = decoder;\n },\n\n /**\n * Converts a json object into an instance of a subclass of AV.Op.\n * @private\n */\n _decode: function(json) {\n var decoder = AV.Op._opDecoderMap[json.__op];\n if (decoder) {\n return decoder(json);\n } else {\n return undefined;\n }\n }\n });\n\n /*\n * Add a handler for Batch ops.\n */\n AV.Op._registerDecoder(\"Batch\", function(json) {\n var op = null;\n AV._arrayEach(json.ops, function(nextOp) {\n nextOp = AV.Op._decode(nextOp);\n op = nextOp._mergeWithPrevious(op);\n });\n return op;\n });\n\n /**\n * @private\n * @class\n * A Set operation indicates that either the field was changed using\n * AV.Object.set, or it is a mutable container that was detected as being\n * changed.\n */\n AV.Op.Set = AV.Op._extend(/** @lends AV.Op.Set.prototype */ {\n _initialize: function(value) {\n this._value = value;\n },\n\n /**\n * Returns the new value of this field after the set.\n */\n value: function() {\n return this._value;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return AV._encode(this.value());\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return this.value();\n }\n });\n\n /**\n * A sentinel value that is returned by AV.Op.Unset._estimate to\n * indicate the field should be deleted. Basically, if you find _UNSET as a\n * value in your object, you should remove that key.\n */\n AV.Op._UNSET = {};\n\n /**\n * @private\n * @class\n * An Unset operation indicates that this field has been deleted from the\n * object.\n */\n AV.Op.Unset = AV.Op._extend(/** @lends AV.Op.Unset.prototype */ {\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Delete\" };\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return AV.Op._UNSET;\n }\n });\n\n AV.Op._registerDecoder(\"Delete\", function(json) {\n return new AV.Op.Unset();\n });\n\n /**\n * @private\n * @class\n * An Increment is an atomic operation where the numeric value for the field\n * will be increased by a given amount.\n */\n AV.Op.Increment = AV.Op._extend(\n /** @lends AV.Op.Increment.prototype */ {\n\n _initialize: function(amount) {\n this._amount = amount;\n },\n\n /**\n * Returns the amount to increment by.\n * @return {Number} the amount to increment by.\n */\n amount: function() {\n return this._amount;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Increment\", amount: this._amount };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.amount());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(previous.value() + this.amount());\n } else if (previous instanceof AV.Op.Increment) {\n return new AV.Op.Increment(this.amount() + previous.amount());\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return this.amount();\n }\n return oldValue + this.amount();\n }\n });\n\n AV.Op._registerDecoder(\"Increment\", function(json) {\n return new AV.Op.Increment(json.amount);\n });\n\n /**\n * @private\n * @class\n * Add is an atomic operation where the given objects will be appended to the\n * array that is stored in this field.\n */\n AV.Op.Add = AV.Op._extend(/** @lends AV.Op.Add.prototype */ {\n _initialize: function(objects) {\n this._objects = objects;\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Add\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Add) {\n return new AV.Op.Add(previous.objects().concat(this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n return oldValue.concat(this.objects());\n }\n }\n });\n\n AV.Op._registerDecoder(\"Add\", function(json) {\n return new AV.Op.Add(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * AddUnique is an atomic operation where the given items will be appended to\n * the array that is stored in this field only if they were not already\n * present in the array.\n */\n AV.Op.AddUnique = AV.Op._extend(\n /** @lends AV.Op.AddUnique.prototype */ {\n\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"AddUnique\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.AddUnique) {\n return new AV.Op.AddUnique(this._estimate(previous.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n // We can't just take the _.uniq(_.union(...)) of oldValue and\n // this.objects, because the uniqueness may not apply to oldValue\n // (especially if the oldValue was set via .set())\n var newValue = _.clone(oldValue);\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n var matchingObj = _.find(newValue, function(anObj) {\n return (anObj instanceof AV.Object) && (anObj.id === obj.id);\n });\n if (!matchingObj) {\n newValue.push(obj);\n } else {\n var index = _.indexOf(newValue, matchingObj);\n newValue[index] = obj;\n }\n } else if (!_.contains(newValue, obj)) {\n newValue.push(obj);\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddUnique\", function(json) {\n return new AV.Op.AddUnique(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * Remove is an atomic operation where the given objects will be removed from\n * the array that is stored in this field.\n */\n AV.Op.Remove = AV.Op._extend(/** @lends AV.Op.Remove.prototype */ {\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be removed from the array.\n * @return {Array} The objects to be removed from the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Remove\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return previous;\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Remove) {\n return new AV.Op.Remove(_.union(previous.objects(), this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return [];\n } else {\n var newValue = _.difference(oldValue, this.objects());\n // If there are saved AV Objects being removed, also remove them.\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n newValue = _.reject(newValue, function(other) {\n return (other instanceof AV.Object) && (other.id === obj.id);\n });\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"Remove\", function(json) {\n return new AV.Op.Remove(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * A Relation operation indicates that the field is an instance of\n * AV.Relation, and objects are being added to, or removed from, that\n * relation.\n */\n AV.Op.Relation = AV.Op._extend(\n /** @lends AV.Op.Relation.prototype */ {\n\n _initialize: function(adds, removes) {\n this._targetClassName = null;\n\n var self = this;\n\n var pointerToId = function(object) {\n if (object instanceof AV.Object) {\n if (!object.id) {\n throw new Error('You can\\'t add an unsaved AV.Object to a relation.');\n }\n if (!self._targetClassName) {\n self._targetClassName = object.className;\n }\n if (self._targetClassName !== object.className) {\n throw new Error(\"Tried to create a AV.Relation with 2 different types: \" +\n self._targetClassName + \" and \" + object.className + \".\");\n }\n return object.id;\n }\n return object;\n };\n\n this.relationsToAdd = _.uniq(_.map(adds, pointerToId));\n this.relationsToRemove = _.uniq(_.map(removes, pointerToId));\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being added to the\n * relation.\n * @return {Array}\n */\n added: function() {\n var self = this;\n return _.map(this.relationsToAdd, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being removed from\n * the relation.\n * @return {Array}\n */\n removed: function() {\n var self = this;\n return _.map(this.relationsToRemove, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n var adds = null;\n var removes = null;\n var self = this;\n var idToPointer = function(id) {\n return { __type: 'Pointer',\n className: self._targetClassName,\n objectId: id };\n };\n var pointers = null;\n if (this.relationsToAdd.length > 0) {\n pointers = _.map(this.relationsToAdd, idToPointer);\n adds = { \"__op\": \"AddRelation\", \"objects\": pointers };\n }\n\n if (this.relationsToRemove.length > 0) {\n pointers = _.map(this.relationsToRemove, idToPointer);\n removes = { \"__op\": \"RemoveRelation\", \"objects\": pointers };\n }\n\n if (adds && removes) {\n return { \"__op\": \"Batch\", \"ops\": [adds, removes]};\n }\n\n return adds || removes || {};\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n throw new Error('You can\\'t modify a relation after deleting it.');\n } else if (previous instanceof AV.Op.Relation) {\n if (previous._targetClassName &&\n previous._targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be of class \" + previous._targetClassName +\n \", but \" + this._targetClassName + \" was passed in.\");\n }\n var newAdd = _.union(_.difference(previous.relationsToAdd,\n this.relationsToRemove),\n this.relationsToAdd);\n var newRemove = _.union(_.difference(previous.relationsToRemove,\n this.relationsToAdd),\n this.relationsToRemove);\n\n var newRelation = new AV.Op.Relation(newAdd, newRemove);\n newRelation._targetClassName = this._targetClassName;\n return newRelation;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue, object, key) {\n if (!oldValue) {\n var relation = new AV.Relation(object, key);\n relation.targetClassName = this._targetClassName;\n } else if (oldValue instanceof AV.Relation) {\n if (this._targetClassName) {\n if (oldValue.targetClassName) {\n if (oldValue.targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be a \" + oldValue.targetClassName +\n \", but a \" + this._targetClassName + \" was passed in.\");\n }\n } else {\n oldValue.targetClassName = this._targetClassName;\n }\n }\n return oldValue;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddRelation\", function(json) {\n return new AV.Op.Relation(AV._decode(json.objects), []);\n });\n AV.Op._registerDecoder(\"RemoveRelation\", function(json) {\n return new AV.Op.Relation([], AV._decode(json.objects));\n });\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/op.js","const AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n AV.Installation = AV.Object.extend(\"_Installation\");\n\n /**\n * @namespace\n */\n AV.Push = AV.Push || {};\n\n /**\n * Sends a push notification.\n * @param {Object} data The data of the push notification.\n * @param {String[]} [data.channels] An Array of channels to push to.\n * @param {Date} [data.push_time] A Date object for when to send the push.\n * @param {Date} [data.expiration_time] A Date object for when to expire\n * the push.\n * @param {Number} [data.expiration_interval] The seconds from now to expire the push.\n * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {Date} data.data The data to send as part of the push\n * @param {AuthOptions} [options]\n * @return {Promise}\n */\n AV.Push.send = function(data, options) {\n if (data.where) {\n data.where = data.where.toJSON().where;\n }\n\n if(data.where && data.cql){\n throw new Error(\"Both where and cql can't be set\");\n }\n\n if (data.push_time) {\n data.push_time = data.push_time.toJSON();\n }\n\n if (data.expiration_time) {\n data.expiration_time = data.expiration_time.toJSON();\n }\n\n if (data.expiration_time && data.expiration_time_interval) {\n throw new Error(\"Both expiration_time and expiration_time_interval can't be set\");\n }\n\n var request = AVRequest('push', null, null, 'POST', data, options);\n return request;\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/push.js","const _ = require('underscore');\nconst debug = require('debug')('leancloud:query');\nconst Promise = require('./promise');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst { ensureArray } = require('./utils');\n\nconst requires = (value, message) => {\n if (value === undefined) {\n throw new Error(message);\n }\n};\n\n// AV.Query is a way to create a list of AV.Objects.\nmodule.exports = function(AV) {\n /**\n * Creates a new AV.Query for the given AV.Object subclass.\n * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string.\n * @class\n *\n *

AV.Query defines a query that is used to fetch AV.Objects. The\n * most common use case is finding all objects that match a query through the\n * find method. For example, this sample code fetches all objects\n * of class MyClass. It calls a different function depending on\n * whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.find().then(function(results) {\n   *   // results is an array of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to retrieve a single object whose id is\n * known, through the get method. For example, this sample code fetches an\n * object of class MyClass and id myId. It calls a\n * different function depending on whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.get(myId).then(function(object) {\n   *   // object is an instance of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to count the number of objects that match\n * the query without retrieving all of those objects. For example, this\n * sample code counts the number of objects of the class MyClass\n *

\n   * var query = new AV.Query(MyClass);\n   * query.count().then(function(number) {\n   *   // There are number instances of MyClass.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n */\n AV.Query = function(objectClass) {\n if (_.isString(objectClass)) {\n objectClass = AV.Object._getSubclass(objectClass);\n }\n\n this.objectClass = objectClass;\n\n this.className = objectClass.prototype.className;\n\n this._where = {};\n this._include = [];\n this._select = [];\n this._limit = -1; // negative limit means, do not send a limit\n this._skip = 0;\n this._extraOptions = {};\n };\n\n /**\n * Constructs a AV.Query that is the OR of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.or(query1, query2, query3);
\n *\n * will create a compoundQuery that is an or of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to OR.\n * @return {AV.Query} The query that is the OR of the passed in queries.\n */\n AV.Query.or = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._orQuery(queries);\n return query;\n };\n\n /**\n * Constructs a AV.Query that is the AND of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.and(query1, query2, query3);
\n *\n * will create a compoundQuery that is an 'and' of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to AND.\n * @return {AV.Query} The query that is the AND of the passed in queries.\n */\n AV.Query.and = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._andQuery(queries);\n return query;\n };\n\n /**\n * Retrieves a list of AVObjects that satisfy the CQL.\n * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n *\n * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n * @param {Array} pvalues An array contains placeholder values.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n AV.Query.doCloudQuery = function(cql, pvalues, options) {\n var params = { cql: cql };\n if(_.isArray(pvalues)){\n params.pvalues = pvalues;\n } else {\n options = pvalues;\n }\n\n var request = AVRequest('cloudQuery', null, null, 'GET', params, options);\n return request.then(function(response) {\n //query to process results.\n var query = new AV.Query(response.className);\n var results = _.map(response.results, function(json) {\n var obj = query._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(query._processResult(json), true);\n }\n return obj;\n });\n return {\n results: results,\n count: response.count,\n className: response.className\n };\n });\n };\n\n AV.Query._extend = AV._extend;\n\n AV.Query.prototype = {\n //hook to iterate result. Added by dennis.\n _processResult: function(obj){\n return obj;\n },\n\n /**\n * Constructs an AV.Object whose id is already known by fetching data from\n * the server.\n *\n * @param {String} objectId The id of the object to be fetched.\n * @param {AuthOptions} options\n * @return {Promise.}\n */\n get: function(objectId, options) {\n if(!objectId) {\n var errorObject = new AVError(AVError.OBJECT_NOT_FOUND,\n \"Object not found.\");\n throw errorObject;\n }\n\n var self = this;\n\n var obj = self._newObject();\n obj.id = objectId;\n\n var queryJSON = self.toJSON();\n var fetchOptions = {};\n\n if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;\n if (queryJSON.include) fetchOptions.include = queryJSON.include;\n\n return obj.fetch(fetchOptions, options);\n },\n\n /**\n * Returns a JSON representation of this query.\n * @return {Object}\n */\n toJSON: function() {\n var params = {\n where: this._where\n };\n\n if (this._include.length > 0) {\n params.include = this._include.join(\",\");\n }\n if (this._select.length > 0) {\n params.keys = this._select.join(\",\");\n }\n if (this._limit >= 0) {\n params.limit = this._limit;\n }\n if (this._skip > 0) {\n params.skip = this._skip;\n }\n if (this._order !== undefined) {\n params.order = this._order;\n }\n\n AV._objectEach(this._extraOptions, function(v, k) {\n params[k] = v;\n });\n\n return params;\n },\n\n _newObject: function(response){\n var obj;\n if (response && response.className) {\n obj = new AV.Object(response.className);\n } else {\n obj = new this.objectClass();\n }\n return obj;\n },\n _createRequest(params = this.toJSON(), options) {\n if (JSON.stringify(params).length > 2000) {\n const body = {\n requests: [{\n method: 'GET',\n path: `/1.1/classes/${this.className}`,\n params,\n }],\n };\n return AVRequest('batch', null, null, 'POST', body, options)\n .then(response => {\n const result = response[0];\n if (result.success) {\n return result.success;\n }\n const error = new Error(result.error.error || 'Unknown batch error');\n error.code = result.error.code;\n throw error;\n });\n }\n return AVRequest('classes', this.className, null, \"GET\", params, options);\n },\n\n _parseResponse(response) {\n return _.map(response.results, (json) => {\n var obj = this._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(this._processResult(json), true);\n }\n return obj;\n });\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find(options) {\n const request = this._createRequest(undefined, options);\n return request.then(this._parseResponse.bind(this));\n },\n\n /**\n * scan a Query. masterKey required.\n *\n * @since 2.1.0\n * @param {object} [options]\n * @param {string} [options.orderedBy] specify the key to sort\n * @param {number} [options.batchSize] specify the batch size for each request\n * @param {AuthOptions} [authOptions]\n * @return {AsyncIterator.}\n * @example const scan = new AV.Query(TestClass).scan({\n * orderedBy: 'objectId',\n * batchSize: 10,\n * }, {\n * useMasterKey: true,\n * });\n * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next()));\n * getTen().then(results => {\n * // results are fisrt 10 instances of TestClass\n * return getTen();\n * }).then(results => {\n * // 11 - 20\n * });\n */\n scan({\n orderedBy,\n batchSize,\n } = {}, authOptions) {\n const condition = this.toJSON();\n debug('scan %O', condition);\n if (condition.order) {\n console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.');\n delete condition.order;\n }\n if (condition.skip) {\n console.warn('The skip option of the query is ignored for Query#scan.');\n delete condition.skip;\n }\n if (condition.limit) {\n console.warn('The limit option of the query is ignored for Query#scan.');\n delete condition.limit;\n }\n if (orderedBy) condition.scan_key = orderedBy;\n if (batchSize) condition.limit = batchSize;\n let promise = Promise.resolve([]);\n let cursor;\n let done = false;\n return {\n next: () => {\n promise = promise.then((remainResults) => {\n if (done) return [];\n if (remainResults.length > 1) return remainResults;\n // no cursor means we have reached the end\n // except for the first time\n if (!cursor && remainResults.length !== 0) {\n done = true;\n return remainResults;\n }\n // when only 1 item left in queue\n // start the next request to see if it is the last one\n return AVRequest(\n 'scan/classes',\n this.className,\n null,\n 'GET',\n cursor ? _.extend({}, condition, { cursor }) : condition,\n authOptions\n ).then(response => {\n cursor = response.cursor;\n return this._parseResponse(response);\n }).then(results => {\n if (!results.length) done = true;\n return remainResults.concat(results);\n });\n });\n return promise\n .then(remainResults => remainResults.shift())\n .then(result => ({\n value: result,\n done,\n }));\n },\n };\n },\n\n /**\n * Delete objects retrieved by this query.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n destroyAll: function(options){\n var self = this;\n return self.find(options).then(function(objects){\n return AV.Object.destroyAll(objects, options);\n });\n },\n\n /**\n * Counts the number of objects that match this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the count when\n * the query completes.\n */\n count: function(options) {\n var params = this.toJSON();\n params.limit = 0;\n params.count = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return response.count;\n });\n },\n\n /**\n * Retrieves at most one AV.Object that satisfies this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the object when\n * the query completes.\n */\n first: function(options) {\n var self = this;\n\n var params = this.toJSON();\n params.limit = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return _.map(response.results, function(json) {\n var obj = self._newObject();\n if (obj._finishFetch) {\n obj._finishFetch(self._processResult(json), true);\n }\n return obj;\n })[0];\n });\n },\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n requires(n, 'undefined is not a valid skip value');\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n requires(n, 'undefined is not a valid limit value');\n this._limit = n;\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that the AV.Object must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n equalTo: function(key, value) {\n requires(key, 'undefined is not a valid key');\n requires(value, 'undefined is not a valid value');\n this._where[key] = AV._encode(value);\n return this;\n },\n\n /**\n * Helper for condition queries\n * @private\n */\n _addCondition: function(key, condition, value) {\n requires(key, 'undefined is not a valid condition key');\n requires(condition, 'undefined is not a valid condition');\n requires(value, 'undefined is not a valid condition value');\n\n // Check if we already have a condition\n if (!this._where[key]) {\n this._where[key] = {};\n }\n this._where[key][condition] = AV._encode(value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular\n * array key's length to be equal to the provided value.\n * @param {String} key The array key to check.\n * @param value The length value.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n sizeEqualTo: function(key, value) {\n this._addCondition(key, \"$size\", value);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be not equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that must not be equalled.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notEqualTo: function(key, value) {\n this._addCondition(key, \"$ne\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThan: function(key, value) {\n this._addCondition(key, \"$lt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThan: function(key, value) {\n this._addCondition(key, \"$gt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$lte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$gte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containedIn: function(key, values) {\n this._addCondition(key, \"$in\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * not be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notContainedIn: function(key, values) {\n this._addCondition(key, \"$nin\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * contain each one of the provided list of values.\n * @param {String} key The key to check. This key's value must be an array.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containsAll: function(key, values) {\n this._addCondition(key, \"$all\", values);\n return this;\n },\n\n\n /**\n * Add a constraint for finding objects that contain the given key.\n * @param {String} key The key that should exist.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n exists: function(key) {\n this._addCondition(key, \"$exists\", true);\n return this;\n },\n\n /**\n * Add a constraint for finding objects that do not contain a given key.\n * @param {String} key The key that should not exist\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotExist: function(key) {\n this._addCondition(key, \"$exists\", false);\n return this;\n },\n\n /**\n * Add a regular expression constraint for finding string values that match\n * the provided regular expression.\n * This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {RegExp} regex The regular expression pattern to match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matches: function(key, regex, modifiers) {\n this._addCondition(key, \"$regex\", regex);\n if (!modifiers) { modifiers = \"\"; }\n // Javascript regex options support mig as inline options but store them\n // as properties of the object. We support mi & should migrate them to\n // modifiers\n if (regex.ignoreCase) { modifiers += 'i'; }\n if (regex.multiline) { modifiers += 'm'; }\n\n if (modifiers && modifiers.length) {\n this._addCondition(key, \"$options\", modifiers);\n }\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value matches a AV.Query\n * constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$inQuery\", queryJSON);\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not matches a\n * AV.Query constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$notInQuery\", queryJSON);\n return this;\n },\n\n\n /**\n * Add a constraint that requires that a key's value matches a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * matched.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$select\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not match a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * excluded.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$dontSelect\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add constraint that at least one of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _orQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$or = queryJSON;\n return this;\n },\n\n /**\n * Add constraint that both of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _andQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$and = queryJSON;\n return this;\n },\n\n\n /**\n * Converts a string into a regex that matches it.\n * Surrounding with \\Q .. \\E does this, we just need to escape \\E's in\n * the text separately.\n * @private\n */\n _quote: function(s) {\n return \"\\\\Q\" + s.replace(\"\\\\E\", \"\\\\E\\\\\\\\E\\\\Q\") + \"\\\\E\";\n },\n\n /**\n * Add a constraint for finding string values that contain a provided\n * string. This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} substring The substring that the value must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n contains: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that start with a provided\n * string. This query will use the backend index, so it will be fast even\n * for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} prefix The substring that the value must start with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n startsWith: function(key, value) {\n this._addCondition(key, \"$regex\", \"^\" + this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that end with a provided\n * string. This will be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} suffix The substring that the value must end with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n endsWith: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value) + \"$\");\n return this;\n },\n\n /**\n * Sorts the results in ascending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n ascending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = key;\n return this;\n },\n\n /**\n * Also sorts the results in ascending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addAscending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',' + key;\n else\n this._order = key;\n return this;\n },\n\n /**\n * Sorts the results in descending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n descending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = \"-\" + key;\n return this;\n },\n\n /**\n * Also sorts the results in descending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addDescending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',-' + key;\n else\n this._order = '-' + key;\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n near: function(key, point) {\n if (!(point instanceof AV.GeoPoint)) {\n // Try to cast it to a GeoPoint, so that near(\"loc\", [20,30]) works.\n point = new AV.GeoPoint(point);\n }\n this._addCondition(key, \"$nearSphere\", point);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param maxDistance Maximum distance (in radians) of results to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinRadians: function(key, point, distance) {\n this.near(key, point);\n this._addCondition(key, \"$maxDistance\", distance);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 3958.8 miles.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in miles) of results to\n * return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinMiles: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 3958.8);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 6371.0 kilometers.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in kilometers) of results\n * to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinKilometers: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 6371.0);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's\n * coordinates be contained within a given rectangular geographic bounding\n * box.\n * @param {String} key The key to be constrained.\n * @param {AV.GeoPoint} southwest\n * The lower-left inclusive corner of the box.\n * @param {AV.GeoPoint} northeast\n * The upper-right inclusive corner of the box.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinGeoBox: function(key, southwest, northeast) {\n if (!(southwest instanceof AV.GeoPoint)) {\n southwest = new AV.GeoPoint(southwest);\n }\n if (!(northeast instanceof AV.GeoPoint)) {\n northeast = new AV.GeoPoint(northeast);\n }\n this._addCondition(key, '$within', { '$box': [southwest, northeast] });\n return this;\n },\n\n /**\n * Include nested AV.Objects for the provided key. You can use dot\n * notation to specify which fields in the included object are also fetch.\n * @param {String[]} keys The name of the key to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n include: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._include = this._include.concat(ensureArray(keys))\n });\n return this;\n },\n\n /**\n * Restrict the fields of the returned AV.Objects to include only the\n * provided keys. If this is called multiple times, then all of the keys\n * specified in each of the calls will be included.\n * @param {String[]} keys The names of the keys to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n select: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._select = this._select.concat(ensureArray(keys));\n });\n return this;\n },\n\n /**\n * Iterates over each result of a query, calling a callback for each one. If\n * the callback returns a promise, the iteration will not continue until\n * that promise has been fulfilled. If the callback returns a rejected\n * promise, then iteration will stop with that error. The items are\n * processed in an unspecified order. The query may not have any sort order,\n * and may not use limit or skip.\n * @param callback {Function} Callback that will be called with each result\n * of the query.\n * @return {Promise} A promise that will be fulfilled once the\n * iteration has completed.\n */\n each: function(callback, options = {}) {\n\n if (this._order || this._skip || (this._limit >= 0)) {\n var error =\n new Error(\"Cannot iterate on a query with sort, skip, or limit.\");\n return AV.Promise.reject(error);\n }\n\n var query = new AV.Query(this.objectClass);\n // We can override the batch size from the options.\n // This is undocumented, but useful for testing.\n query._limit = options.batchSize || 100;\n query._where = _.clone(this._where);\n query._include = _.clone(this._include);\n\n query.ascending('objectId');\n\n var finished = false;\n return AV.Promise._continueWhile(function() {\n return !finished;\n\n }, function() {\n return query.find(options).then(function(results) {\n var callbacksDone = AV.Promise.resolve();\n _.each(results, function(result) {\n callbacksDone = callbacksDone.then(function() {\n return callback(result);\n });\n });\n\n return callbacksDone.then(function() {\n if (results.length >= query._limit) {\n query.greaterThan(\"objectId\", results[results.length - 1].id);\n } else {\n finished = true;\n }\n });\n });\n });\n }\n };\n\n AV.FriendShipQuery = AV.Query._extend({\n _objectClass: AV.User,\n _newObject: function(){\n return new AV.User();\n },\n _processResult: function(json){\n if(json && json[this._friendshipTag]) {\n var user = json[this._friendshipTag];\n if(user.__type === 'Pointer' && user.className === '_User'){\n delete user.__type;\n delete user.className;\n }\n return user;\n } else {\n return null;\n }\n },\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/query.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n /**\n * Creates a new Relation for the given parent object and key. This\n * constructor should rarely be used directly, but rather created by\n * {@link AV.Object#relation}.\n * @param {AV.Object} parent The parent of this relation.\n * @param {String} key The key for this relation on the parent.\n * @see AV.Object#relation\n * @class\n *\n *

\n * A class that is used to access all of the children of a many-to-many\n * relationship. Each instance of AV.Relation is associated with a\n * particular parent object and key.\n *

\n */\n AV.Relation = function(parent, key) {\n if (! _.isString(key)) {\n throw new TypeError('key must be a string');\n }\n this.parent = parent;\n this.key = key;\n this.targetClassName = null;\n };\n\n /**\n * Creates a query that can be used to query the parent objects in this relation.\n * @param {String} parentClass The parent class or name.\n * @param {String} relationKey The relation field key in parent.\n * @param {AV.Object} child The child object.\n * @return {AV.Query}\n */\n AV.Relation.reverseQuery = function(parentClass, relationKey, child){\n var query = new AV.Query(parentClass);\n query.equalTo(relationKey, child._toPointer());\n return query;\n };\n\n AV.Relation.prototype = {\n /**\n * Makes sure that this relation has the right parent and key.\n * @private\n */\n _ensureParentAndKey: function(parent, key) {\n this.parent = this.parent || parent;\n this.key = this.key || key;\n if (this.parent !== parent) {\n throw new Error(\"Internal Error. Relation retrieved from two different Objects.\");\n }\n if (this.key !== key) {\n throw new Error(\"Internal Error. Relation retrieved from two different keys.\");\n }\n },\n\n /**\n * Adds a AV.Object or an array of AV.Objects to the relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to add.\n */\n add: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation(objects, []);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Removes a AV.Object or an array of AV.Objects from this relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to remove.\n */\n remove: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation([], objects);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Returns a JSON version of the object suitable for saving to disk.\n * @return {Object}\n */\n toJSON: function() {\n return { \"__type\": \"Relation\", \"className\": this.targetClassName };\n },\n\n /**\n * Returns a AV.Query that is limited to objects in this\n * relation.\n * @return {AV.Query}\n */\n query: function() {\n var targetClass;\n var query;\n if (!this.targetClassName) {\n targetClass = AV.Object._getSubclass(this.parent.className);\n query = new AV.Query(targetClass);\n query._extraOptions.redirectClassNameForKey = this.key;\n } else {\n targetClass = AV.Object._getSubclass(this.targetClassName);\n query = new AV.Query(targetClass);\n }\n query._addCondition(\"$relatedTo\", \"object\", this.parent._toPointer());\n query._addCondition(\"$relatedTo\", \"key\", this.key);\n\n return query;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/relation.js","const _ = require('underscore');\nconst AVError = require('./error');\n\nmodule.exports = function(AV) {\n AV.Role = AV.Object.extend(\"_Role\", /** @lends AV.Role.prototype */ {\n // Instance Methods\n\n /**\n * Represents a Role on the AV server. Roles represent groupings of\n * Users for the purposes of granting permissions (e.g. specifying an ACL\n * for an Object). Roles are specified by their sets of child users and\n * child roles, all of which are granted any permissions that the parent\n * role has.\n *\n *

Roles must have a name (which cannot be changed after creation of the\n * role), and must specify an ACL.

\n * An AV.Role is a local representation of a role persisted to the AV\n * cloud.\n * @class AV.Role\n * @param {String} name The name of the Role to create.\n * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL\n * `{'*': { read: true }}` will be used.\n */\n constructor: function(name, acl, noDefaultACL) {\n if (_.isString(name)) {\n AV.Object.prototype.constructor.call(this, null, null);\n this.setName(name);\n } else {\n AV.Object.prototype.constructor.call(this, name, acl);\n }\n if (acl === undefined) {\n if (!noDefaultACL) {\n if(!this.getACL()) {\n console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.');\n var defaultAcl = new AV.ACL();\n defaultAcl.setPublicReadAccess(true); \n this.setACL(defaultAcl);\n }\n }\n } else if (!(acl instanceof AV.ACL)) {\n throw new TypeError('acl must be an instance of AV.ACL');\n } else {\n this.setACL(acl);\n }\n },\n\n /**\n * Gets the name of the role. You can alternatively call role.get(\"name\")\n *\n * @return {String} the name of the role.\n */\n getName: function() {\n return this.get(\"name\");\n },\n\n /**\n * Sets the name for a role. This value must be set before the role has\n * been saved to the server, and cannot be set once the role has been\n * saved.\n *\n *

\n * A role's name can only contain alphanumeric characters, _, -, and\n * spaces.\n *

\n *\n *

This is equivalent to calling role.set(\"name\", name)

\n *\n * @param {String} name The name of the role.\n */\n setName: function(name, options) {\n return this.set(\"name\", name, options);\n },\n\n /**\n * Gets the AV.Relation for the AV.Users that are direct\n * children of this role. These users are granted any privileges that this\n * role has been granted (e.g. read or write access through ACLs). You can\n * add or remove users from the role through this relation.\n *\n *

This is equivalent to calling role.relation(\"users\")

\n *\n * @return {AV.Relation} the relation for the users belonging to this\n * role.\n */\n getUsers: function() {\n return this.relation(\"users\");\n },\n\n /**\n * Gets the AV.Relation for the AV.Roles that are direct\n * children of this role. These roles' users are granted any privileges that\n * this role has been granted (e.g. read or write access through ACLs). You\n * can add or remove child roles from this role through this relation.\n *\n *

This is equivalent to calling role.relation(\"roles\")

\n *\n * @return {AV.Relation} the relation for the roles belonging to this\n * role.\n */\n getRoles: function() {\n return this.relation(\"roles\");\n },\n\n /**\n * @ignore\n */\n validate: function(attrs, options) {\n if (\"name\" in attrs && attrs.name !== this.getName()) {\n var newName = attrs.name;\n if (this.id && this.id !== attrs.objectId) {\n // Check to see if the objectId being set matches this.id.\n // This happens during a fetch -- the id is set before calling fetch.\n // Let the name be set in this case.\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only be set before it has been saved.\");\n }\n if (!_.isString(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name must be a String.\");\n }\n if (!(/^[0-9a-zA-Z\\-_ ]+$/).test(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only contain alphanumeric characters, _,\" +\n \" -, and spaces.\");\n }\n }\n if (AV.Object.prototype.validate) {\n return AV.Object.prototype.validate.call(this, attrs, options);\n }\n return false;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/role.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * A builder to generate sort string for app searching.For example:\n * @class\n * @since 0.5.1\n * @example\n * var builder = new AV.SearchSortBuilder();\n * builder.ascending('key1').descending('key2','max');\n * var query = new AV.SearchQuery('Player');\n * query.sortBy(builder);\n * query.find().then();\n */\n AV.SearchSortBuilder = function() {\n this._sortFields = [];\n };\n\n AV.SearchSortBuilder.prototype = {\n _addField: function(key, order, mode, missing) {\n var field = {};\n field[key] = {\n order: order || 'asc',\n mode: mode ||'avg',\n missing: '_' + (missing || 'last')\n };\n this._sortFields.push(field);\n return this;\n },\n\n\n /**\n * Sorts the results in ascending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n ascending: function(key, mode, missing) {\n return this._addField(key, 'asc', mode, missing);\n },\n\n /**\n * Sorts the results in descending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n descending: function(key, mode, missing) {\n return this._addField(key, 'desc', mode, missing);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Object} options The other options such as mode,order, unit etc.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n whereNear: function(key, point, options) {\n options = options || {};\n var field = {};\n var geo = {\n lat: point.latitude,\n lon: point.longitude\n };\n var m = {\n order: options.order || 'asc',\n mode: options.mode || 'avg',\n unit: options.unit || 'km'\n };\n m[key] = geo;\n field['_geo_distance'] = m;\n\n this._sortFields.push(field);\n return this;\n },\n\n /**\n * Build a sort string by configuration.\n * @return {String} the sort string.\n */\n build: function() {\n return JSON.stringify(AV._encode(this._sortFields));\n }\n };\n\n /**\n * App searching query.Use just like AV.Query:\n *\n * Visit App Searching Guide\n * for more details.\n * @class\n * @since 0.5.1\n * @example\n * var query = new AV.SearchQuery('Player');\n * query.queryString('*');\n * query.find().then(function(results) {\n * console.log('Found %d objects', query.hits());\n * //Process results\n * });\n */\n AV.SearchQuery = AV.Query._extend(/** @lends AV.SearchQuery.prototype */{\n _sid: null,\n _hits: 0,\n _queryString: null,\n _highlights: null,\n _sortBuilder: null,\n _createRequest: function(params, options){\n return AVRequest('search/select', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n /**\n * Sets the sid of app searching query.Default is null.\n * @param {String} sid Scroll id for searching.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n sid: function(sid) {\n this._sid = sid;\n return this;\n },\n\n /**\n * Sets the query string of app searching.\n * @param {String} q The query string.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n queryString: function(q) {\n this._queryString = q;\n return this;\n },\n\n\n /**\n * Sets the highlight fields. Such as\n *
\n     *   query.highlights('title');\n     *   //or pass an array.\n     *   query.highlights(['title', 'content'])\n     * 
\n * @param {String[]} highlights a list of fields.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n highlights: function(highlights) {\n var objects;\n if (highlights && _.isString(highlights)) {\n objects = arguments;\n } else {\n objects = highlights;\n }\n this._highlights = objects;\n return this;\n },\n\n /**\n * Sets the sort builder for this query.\n * @see AV.SearchSortBuilder\n * @param { AV.SearchSortBuilder} builder The sort builder.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n *\n */\n sortBy: function(builder) {\n this._sortBuilder = builder;\n return this;\n },\n\n /**\n * Returns the number of objects that match this query.\n * @return {Number}\n */\n hits: function() {\n if (!this._hits) {\n this._hits = 0;\n }\n return this._hits;\n },\n\n _processResult: function(json){\n delete json['className'];\n delete json['_app_url'];\n delete json['_deeplink'];\n return json;\n },\n\n /**\n * Returns true when there are more documents can be retrieved by this\n * query instance, you can call find function to get more results.\n * @see AV.SearchQuery#find\n * @return {Boolean}\n */\n hasMore: function() {\n return !this._hitEnd;\n },\n\n /**\n * Reset current query instance state(such as sid, hits etc) except params\n * for a new searching. After resetting, hasMore() will return true.\n */\n reset: function() {\n this._hitEnd = false;\n this._sid = null;\n this._hits = 0;\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n * Either options.success or options.error is called when the find\n * completes.\n *\n * @see AV.Query#find\n * @return {AV.Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find: function() {\n var self = this;\n\n var request = this._createRequest();\n\n return request.then(function(response) {\n //update sid for next querying.\n if(response.sid) {\n self._oldSid = self._sid;\n self._sid = response.sid;\n } else {\n self._sid = null;\n self._hitEnd = true;\n }\n self._hits = response.hits || 0;\n\n return _.map(response.results, function(json) {\n if(json.className) {\n response.className = json.className;\n }\n var obj = self._newObject(response);\n obj.appURL = json['_app_url'];\n obj._finishFetch(self._processResult(json), true);\n return obj;\n });\n });\n },\n\n toJSON: function(){\n var params = AV.SearchQuery.__super__.toJSON.call(this);\n delete params.where;\n if(this.className) {\n params.clazz = this.className;\n }\n if(this._sid) {\n params.sid = this._sid;\n }\n if(!this._queryString) {\n throw new Error('Please set query string.');\n } else {\n params.q = this._queryString;\n }\n if(this._highlights) {\n params.highlights = this._highlights.join(',');\n }\n if(this._sortBuilder && params.order) {\n throw new Error('sort and order can not be set at same time.');\n }\n if(this._sortBuilder) {\n params.sort = this._sortBuilder.build();\n }\n\n return params;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/search.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n const getUser = (options = {}) => AV.User.currentAsync()\n .then(currUser => currUser || AV.User._fetchUserBySessionToken(options.sessionToken));\n\n const getUserPointer = options => getUser(options)\n .then(currUser => AV.Object.createWithoutData('_User', currUser.id)._toPointer());\n\n /**\n * Contains functions to deal with Status in LeanCloud.\n * @class\n */\n AV.Status = function(imageUrl, message) {\n this.data = {};\n this.inboxType = 'default';\n this.query = null;\n if(imageUrl && typeof imageUrl === 'object') {\n this.data = imageUrl;\n } else {\n if(imageUrl){\n this.data.image = imageUrl;\n }\n if(message){\n this.data.message = message;\n }\n }\n return this;\n };\n\n AV.Status.prototype = {\n /**\n * Gets the value of an attribute in status data.\n * @param {String} attr The string name of an attribute.\n */\n get: function(attr){\n return this.data[attr];\n },\n /**\n * Sets a hash of model attributes on the status data.\n * @param {String} key The key to set.\n * @param {} value The value to give it.\n */\n set: function(key, value){\n this.data[key] = value;\n return this;\n },\n /**\n * Destroy this status,then it will not be avaiable in other user's inboxes.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options){\n if(!this.id)\n return AV.Promise.reject(new Error('The status id is not exists.'));\n var request = AVRequest('statuses', null, this.id, 'DELETE', options);\n return request;\n },\n /**\n * Cast the AV.Status object to an AV.Object pointer.\n * @return {AV.Object} A AV.Object pointer.\n */\n toObject: function(){\n if(!this.id)\n return null;\n return AV.Object.createWithoutData('_Status', this.id);\n },\n _getDataJSON: function() {\n var json = _.clone(this.data);\n return AV._encode(json);\n },\n /**\n * Send a status by a AV.Query object.\n * @since 0.3.0\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a status to male users\n * var status = new AVStatus('image url', 'a message');\n * status.query = new AV.Query('_User');\n * status.query.equalTo('gender', 'male');\n * status.send().then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n send: function(options = {}){\n if(!options.sessionToken && !AV.User.current()) {\n throw new Error('Please signin an user.');\n }\n if(!this.query){\n return AV.Status.sendStatusToFollowers(this, options);\n }\n\n return getUserPointer(options).then(currUser => {\n var query = this.query.toJSON();\n query.className = this.query.className;\n var data = {};\n data.query = query;\n this.data = this.data || {};\n this.data.source = this.data.source || currUser;\n data.data = this._getDataJSON();\n data.inboxType = this.inboxType || 'default';\n\n return AVRequest('statuses', null, null, 'POST', data, options);\n })\n .then((response) => {\n this.id = response.objectId;\n this.createdAt = AV._parseDate(response.createdAt);\n return this;\n });\n },\n\n _finishFetch: function(serverData){\n this.id = serverData.objectId;\n this.createdAt = AV._parseDate(serverData.createdAt);\n this.updatedAt = AV._parseDate(serverData.updatedAt);\n this.messageId = serverData.messageId;\n delete serverData.messageId;\n delete serverData.objectId;\n delete serverData.createdAt;\n delete serverData.updatedAt;\n this.data = AV._decode(serverData);\n }\n };\n\n /**\n * Send a status to current signined user's followers.\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendStatusToFollowers(status).then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendStatusToFollowers = function(status, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_Follower';\n query.keys = 'follower';\n query.where = {user: currUser};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = status.inboxType || 'default';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n *

Send a status from current signined user to other user's private status inbox.

\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {String} target The target user or user's objectId.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a private status to user '52e84e47e4b0f8de283b079b'\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendPrivateStatus = function(status, target, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n if(!target){\n throw new Error(\"Invalid target user.\");\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error(\"Invalid target user.\");\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_User';\n query.where = {objectId: userObjectId};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = 'private';\n status.inboxType = 'private';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n * Count unread statuses in someone's inbox.\n * @since 0.3.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the count\n * completes.\n * @example\n * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.countUnreadStatuses = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options);\n });\n };\n\n /**\n * reset unread statuses count in someone's inbox.\n * @since 2.1.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the reset\n * completes.\n * @example\n * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.resetUnreadCount = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options);\n });\n };\n\n /**\n * Create a status query to find someone's published statuses.\n * @since 0.3.0\n * @param {Object} source The status source.\n * @return {AV.Query} The query object for status.\n * @example\n * //Find current user's published statuses.\n * var query = AV.Status.statusQuery(AV.User.current());\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.statusQuery = function(source){\n var query = new AV.Query('_Status');\n if(source){\n query.equalTo('source', source);\n }\n return query;\n };\n\n /**\n *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

\n * @class\n */\n AV.InboxQuery = AV.Query._extend(/** @lends AV.InboxQuery.prototype */{\n _objectClass: AV.Status,\n _sinceId: 0,\n _maxId: 0,\n _inboxType: 'default',\n _owner: null,\n _newObject: function(){\n return new AV.Status();\n },\n _createRequest: function(params, options){\n return AVRequest('subscribe/statuses', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n\n /**\n * Sets the messageId of results to skip before returning any results.\n * This is useful for pagination.\n * Default is zero.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n sinceId: function(id){\n this._sinceId = id;\n return this;\n },\n /**\n * Sets the maximal messageId of results。\n * This is useful for pagination.\n * Default is zero that is no limition.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n maxId: function(id){\n this._maxId = id;\n return this;\n },\n /**\n * Sets the owner of the querying inbox.\n * @param {Object} owner The inbox owner.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n owner: function(owner){\n this._owner = owner;\n return this;\n },\n /**\n * Sets the querying inbox type.default is 'default'.\n * @param {Object} owner The inbox type.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n inboxType: function(type){\n this._inboxType = type;\n return this;\n },\n toJSON: function(){\n var params = AV.InboxQuery.__super__.toJSON.call(this);\n params.owner = AV._encode(this._owner);\n params.inboxType = AV._encode(this._inboxType);\n params.sinceId = AV._encode(this._sinceId);\n params.maxId = AV._encode(this._maxId);\n return params;\n }\n });\n\n /**\n * Create a inbox status query to find someone's inbox statuses.\n * @since 0.3.0\n * @param {Object} owner The inbox's owner\n * @param {String} inboxType The inbox type,'default' by default.\n * @return {AV.InboxQuery} The inbox query object.\n * @see AV.InboxQuery\n * @example\n * //Find current user's default inbox statuses.\n * var query = AV.Status.inboxQuery(AV.User.current());\n * //find the statuses after the last message id\n * query.sinceId(lastMessageId);\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.inboxQuery = function(owner, inboxType){\n var query = new AV.InboxQuery(AV.Status);\n if(owner){\n query._owner = owner;\n }\n if(inboxType){\n query._inboxType = inboxType;\n }\n return query;\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/status.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\n\nconst getWeappLoginCode = () => {\n if (typeof wx === 'undefined' || typeof wx.login !== 'function') {\n throw new Error('Weapp Login is only available in Weapp');\n }\n return new Promise((resolve, reject) => {\n wx.login({\n success: ({ code, errMsg }) => {\n if (code) {\n resolve(code);\n } else {\n reject(new Error(errMsg));\n }\n },\n });\n });\n};\n\nmodule.exports = function(AV) {\n /**\n * @class\n *\n *

An AV.User object is a local representation of a user persisted to the\n * LeanCloud server. This class is a subclass of an AV.Object, and retains the\n * same functionality of an AV.Object, but also extends it with various\n * user specific methods, like authentication, signing up, and validation of\n * uniqueness.

\n */\n AV.User = AV.Object.extend(\"_User\", /** @lends AV.User.prototype */ {\n // Instance Variables\n _isCurrentUser: false,\n\n\n // Instance Methods\n\n /**\n * Internal method to handle special fields in a _User response.\n * @private\n */\n _mergeMagicFields: function(attrs) {\n if (attrs.sessionToken) {\n this._sessionToken = attrs.sessionToken;\n delete attrs.sessionToken;\n }\n AV.User.__super__._mergeMagicFields.call(this, attrs);\n },\n\n /**\n * Removes null values from authData (which exist temporarily for\n * unlinking)\n * @private\n */\n _cleanupAuthData: function() {\n if (!this.isCurrent()) {\n return;\n }\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n AV._objectEach(this.get('authData'), function(value, key) {\n if (!authData[key]) {\n delete authData[key];\n }\n });\n },\n\n /**\n * Synchronizes authData for all providers.\n * @private\n */\n _synchronizeAllAuthData: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._synchronizeAuthData(key);\n });\n },\n\n /**\n * Synchronizes auth data for a provider (e.g. puts the access token in the\n * right place to be used by the Facebook SDK).\n * @private\n */\n _synchronizeAuthData: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[authType];\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData');\n if (!authData || !provider) {\n return;\n }\n var success = provider.restoreAuthentication(authData[authType]);\n if (!success) {\n this._unlinkFrom(provider);\n }\n },\n\n _handleSaveResult: function(makeCurrent) {\n // Clean up and synchronize the authData object, removing any unset values\n if (makeCurrent && !AV._config.disableCurrentUser) {\n this._isCurrentUser = true;\n }\n this._cleanupAuthData();\n this._synchronizeAllAuthData();\n // Don't keep the password around.\n delete this._serverData.password;\n this._rebuildEstimatedDataForKey(\"password\");\n this._refreshCache();\n if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) {\n // Some old version of leanengine-node-sdk will overwrite\n // AV.User._saveCurrentUser which returns no Promise.\n // So we need a Promise wrapper.\n return Promise.resolve(AV.User._saveCurrentUser(this));\n } else {\n return Promise.resolve();\n }\n },\n\n /**\n * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can\n * call linkWith on the user (even if it doesn't exist yet on the server).\n * @private\n */\n _linkWith: function(provider, data) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[provider];\n } else {\n authType = provider.getAuthType();\n }\n if (data) {\n var authData = this.get('authData') || {};\n authData[authType] = data;\n return this.save({ authData })\n .then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n } else {\n return provider.authenticate().then(result => this._linkWith(provider, result));\n }\n },\n\n /**\n * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。\n * 仅在小程序中可用。\n *\n * @return {AV.User}\n */\n linkWithWeapp() {\n return getWeappLoginCode().then(code => this._linkWith('lc_weapp', { code }));\n },\n\n /**\n * Unlinks a user from a service.\n * @private\n */\n _unlinkFrom: function(provider) {\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n return this._linkWith(provider, null).then(model => {\n this._synchronizeAuthData(provider);\n return model;\n });\n },\n\n /**\n * Checks whether a user is linked to a service.\n * @private\n */\n _isLinked: function(provider) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData') || {};\n return !!authData[authType];\n },\n\n logOut: function() {\n this._logOutWithAll();\n this._isCurrentUser = false;\n },\n\n /**\n * Deauthenticates all providers.\n * @private\n */\n _logOutWithAll: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._logOutWith(key);\n });\n },\n\n /**\n * Deauthenticates a single provider (e.g. removing access tokens from the\n * Facebook SDK).\n * @private\n */\n _logOutWith: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n if (provider && provider.deauthenticate) {\n provider.deauthenticate();\n }\n },\n\n /**\n * Signs up a new user. You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUp\n */\n signUp: function(attrs, options) {\n var error;\n\n var username = (attrs && attrs.username) || this.get(\"username\");\n if (!username || (username === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty name.\");\n throw error;\n }\n\n var password = (attrs && attrs.password) || this.get(\"password\");\n if (!password || (password === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty password.\");\n throw error;\n }\n\n return this.save(attrs, options).then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Signs up a new user with mobile phone and sms code.\n * You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(attrs, options = {}) {\n var error;\n\n var mobilePhoneNumber = (attrs && attrs.mobilePhoneNumber) ||\n this.get(\"mobilePhoneNumber\");\n if (!mobilePhoneNumber || (mobilePhoneNumber === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty mobilePhoneNumber.\");\n throw error;\n }\n\n var smsCode = (attrs && attrs.smsCode) || this.get(\"smsCode\");\n if (!smsCode || (smsCode === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty smsCode.\");\n throw error;\n }\n\n options._makeRequest = function(route, className, id, method, json) {\n return AVRequest('usersByMobilePhone', null, null, \"POST\", json);\n };\n return this.save(attrs, options).then(function(model) {\n delete model.attributes.smsCode;\n delete model._serverData.smsCode;\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Logs in a AV.User. On success, this saves the session to localStorage,\n * so you can retrieve the currently logged in user using\n * current.\n *\n *

A username and password must be set before calling logIn.

\n *\n * @see AV.User.logIn\n * @return {Promise} A promise that is fulfilled with the user when\n * the login is complete.\n */\n logIn: function() {\n var model = this;\n var request = AVRequest('login', null, null, 'POST', this.toJSON());\n return request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n model._finishFetch(serverAttrs);\n return model._handleSaveResult(true).then(function() {\n if(!serverAttrs.smsCode)\n delete model.attributes['smsCode'];\n return model;\n });\n });\n },\n /**\n * @see AV.Object#save\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n options = options || {};\n\n return AV.Object.prototype.save\n .call(this, attrs, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Follow a user\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to follow.\n * @param {AuthOptions} options\n */\n follow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'POST', null, options);\n return request;\n },\n\n /**\n * Unfollow a user.\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to unfollow.\n * @param {AuthOptions} options\n */\n unfollow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'DELETE', null, options);\n return request;\n },\n\n /**\n *Create a follower query to query the user's followers.\n * @since 0.3.0\n * @see AV.User#followerQuery\n */\n followerQuery: function() {\n return AV.User.followerQuery(this.id);\n },\n\n /**\n *Create a followee query to query the user's followees.\n * @since 0.3.0\n * @see AV.User#followeeQuery\n */\n followeeQuery: function() {\n return AV.User.followeeQuery(this.id);\n },\n\n /**\n * @see AV.Object#fetch\n */\n fetch: function(fetchOptions, options) {\n return AV.Object.prototype.fetch.call(this, fetchOptions, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Update user's new password safely based on old password.\n * @param {String} oldPassword the old password.\n * @param {String} newPassword the new password.\n * @param {AuthOptions} options\n */\n updatePassword: function(oldPassword, newPassword, options) {\n var route = 'users/' + this.id + '/updatePassword';\n var params = {\n old_password: oldPassword,\n new_password: newPassword\n };\n var request = AVRequest(route, null, null, 'PUT', params, options);\n return request;\n },\n\n /**\n * Returns true if current would return this user.\n * @see AV.User#current\n */\n isCurrent: function() {\n return this._isCurrentUser;\n },\n\n /**\n * Returns get(\"username\").\n * @return {String}\n * @see AV.Object#get\n */\n getUsername: function() {\n return this.get(\"username\");\n },\n\n /**\n * Returns get(\"mobilePhoneNumber\").\n * @return {String}\n * @see AV.Object#get\n */\n getMobilePhoneNumber: function(){\n return this.get(\"mobilePhoneNumber\");\n },\n\n /**\n * Calls set(\"mobilePhoneNumber\", phoneNumber, options) and returns the result.\n * @param {String} mobilePhoneNumber\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setMobilePhoneNumber: function(phone, options) {\n return this.set(\"mobilePhoneNumber\", phone, options);\n },\n\n /**\n * Calls set(\"username\", username, options) and returns the result.\n * @param {String} username\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setUsername: function(username, options) {\n return this.set(\"username\", username, options);\n },\n\n /**\n * Calls set(\"password\", password, options) and returns the result.\n * @param {String} password\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setPassword: function(password, options) {\n return this.set(\"password\", password, options);\n },\n\n /**\n * Returns get(\"email\").\n * @return {String}\n * @see AV.Object#get\n */\n getEmail: function() {\n return this.get(\"email\");\n },\n\n /**\n * Calls set(\"email\", email, options) and returns the result.\n * @param {String} email\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setEmail: function(email, options) {\n return this.set(\"email\", email, options);\n },\n\n /**\n * Checks whether this user is the current user and has been authenticated.\n * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),\n * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id\n * @return (Boolean) whether this user is the current user and is logged in.\n */\n authenticated: function() {\n console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。')\n return !!this._sessionToken &&\n (!AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id);\n },\n\n /**\n * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。\n *\n * @since 2.0.0\n * @return Promise.\n */\n isAuthenticated() {\n return Promise.resolve().then(() =>\n !!this._sessionToken &&\n AV.User._fetchUserBySessionToken(this._sessionToken).then(\n () => true,\n (error) => {\n if (error.code === 211) {\n return false;\n }\n throw error;\n }\n )\n );\n },\n\n /**\n * Get sessionToken of current user.\n * @return {String} sessionToken\n */\n getSessionToken() {\n return this._sessionToken;\n },\n\n /**\n * Refresh sessionToken of current user.\n * @since 2.1.0\n * @param {AuthOptions} [options]\n * @return {Promise.} user with refreshed sessionToken\n */\n refreshSessionToken(options) {\n return AVRequest(`users/${this.id}/refreshSessionToken`, null, null, 'PUT', null, options)\n .then(response => {\n this._finishFetch(response);\n return this._handleSaveResult(true).then(() => this);\n });\n },\n\n /**\n * Get this user's Roles.\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that is fulfilled with the roles when\n * the query is complete.\n */\n getRoles(options) {\n return AV.Relation.reverseQuery(\"_Role\", \"users\", this).find(options);\n },\n\n }, /** @lends AV.User */ {\n // Class Variables\n\n // The currently logged-in user.\n _currentUser: null,\n\n // Whether currentUser is known to match the serialized version on disk.\n // This is useful for saving a localstorage check if you try to load\n // _currentUser frequently while there is none stored.\n _currentUserMatchesDisk: false,\n\n // The localStorage key suffix that the current user is stored under.\n _CURRENT_USER_KEY: \"currentUser\",\n\n // The mapping of auth provider names to actual providers\n _authProviders: {},\n\n // Class Methods\n\n /**\n * Signs up a new user with a username (or email) and password.\n * This will create a new AV.User on the server, and also persist the\n * session in localStorage so that you can access the user using\n * {@link #current}.\n *\n * @param {String} username The username (or email) to sign up with.\n * @param {String} password The password to sign up with.\n * @param {Object} attrs Extra fields to set on the new user.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the signup completes.\n * @see AV.User#signUp\n */\n signUp: function(username, password, attrs, options) {\n attrs = attrs || {};\n attrs.username = username;\n attrs.password = password;\n var user = AV.Object._create(\"_User\");\n return user.signUp(attrs, options);\n },\n\n /**\n * Logs in a user with a username (or email) and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} username The username (or email) to log in with.\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logIn: function(username, password, options) {\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ username: username, password: password });\n return user.logIn(options);\n },\n\n /**\n * Logs in a user with a session token. On success, this saves the session\n * to disk, so you can retrieve the currently logged in user using\n * current.\n *\n * @param {String} sessionToken The sessionToken to log in with.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n */\n become: function(sessionToken) {\n return this._fetchUserBySessionToken(sessionToken).then(user =>\n user._handleSaveResult(true).then(() => user)\n );\n },\n\n _fetchUserBySessionToken: function(sessionToken) {\n var user = AV.Object._create(\"_User\");\n return AVRequest(\n \"users\",\n \"me\",\n null,\n \"GET\", {\n session_token: sessionToken\n }\n ).then(function(resp) {\n var serverAttrs = user.parse(resp);\n user._finishFetch(serverAttrs);\n return user;\n });\n },\n\n /**\n * Logs in a user with a mobile phone number and sms code sent by\n * AV.User.requestLoginSmsCode.On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhoneSmsCode: function(mobilePhone, smsCode, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a mobilePhoneNumber and smsCode.\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {String} mobilePhoneNumber The user's mobilePhoneNumber.\n * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode\n * @param {Object} attributes The user's other attributes such as username etc.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(mobilePhoneNumber, smsCode, attrs, options) {\n attrs = attrs || {};\n attrs.mobilePhoneNumber = mobilePhoneNumber;\n attrs.smsCode = smsCode;\n var user = AV.Object._create(\"_User\");\n return user.signUpOrlogInWithMobilePhone(attrs, options);\n },\n\n\n /**\n * Logs in a user with a mobile phone number and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhone: function(mobilePhone, password, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a third party auth data(AccessToken).\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @param {string} platform Available platform for sign up.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户}\n */\n signUpOrlogInWithAuthData(authData, platform) {\n return AV.User._logInWith(platform, authData);\n },\n\n /**\n * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。\n * 仅在小程序中可用。\n *\n * @since 2.0.0\n * @return {AV.User}\n */\n loginWithWeapp() {\n return getWeappLoginCode().then(code => this.signUpOrlogInWithAuthData({ code }, 'lc_weapp'));\n },\n\n /**\n * Associate a user with a third party auth data(AccessToken).\n *\n * @param {AV.User} userObj A user which you want to associate.\n * @param {string} platform Available platform for sign up.\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @return {Promise} A promise that is fulfilled with the user when completed.\n * @example AV.User.associateWithAuthData(loginUser, 'weixin', {\n * openid: 'abc123',\n * access_token: '123abc',\n * expires_in: 1382686496\n * }).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n */\n associateWithAuthData(userObj, platform, authData) {\n return userObj._linkWith(platform, authData);\n },\n /**\n * Logs out the currently logged in user session. This will remove the\n * session from disk, log out of linked services, and future calls to\n * current will return null.\n * @return {Promise}\n */\n logOut: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser !== null) {\n AV.User._currentUser._logOutWithAll();\n AV.User._currentUser._isCurrentUser = false;\n }\n AV.User._currentUserMatchesDisk = true;\n AV.User._currentUser = null;\n return AV.localStorage.removeItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY));\n },\n\n /**\n *Create a follower query for special user to query the user's followers.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followerQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Follower');\n query._friendshipTag ='follower';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n *Create a followee query for special user to query the user's followees.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followeeQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Followee');\n query._friendshipTag ='followee';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n * Requests a password reset email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * reset their password on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * forgot their password.\n * @return {Promise}\n */\n requestPasswordReset: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestPasswordReset\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * verify their email address on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * doesn't verify their email address.\n * @return {Promise}\n */\n requestEmailVerify: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestEmailVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * verify their mobile phone number by calling AV.User.verifyMobilePhone\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestMobilePhoneVerify: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestMobilePhoneVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n\n /**\n * Requests a reset password sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * reset their account's password by calling AV.User.resetPasswordBySmsCode\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestPasswordResetBySmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestPasswordResetBySmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Makes a call to reset user's account password by sms code and new password.\n * The sms code is sent by AV.User.requestPasswordResetBySmsCode.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @param {String} password The new password.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n resetPasswordBySmsCode: function(code, password){\n var json = { password: password};\n var request = AVRequest(\"resetPasswordBySmsCode\", null, code, \"PUT\",\n json);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode\n * If verify successfully,the user mobilePhoneVerified attribute will be true.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifyMobilePhone: function(code){\n var request = AVRequest(\"verifyMobilePhone\", null, code, \"POST\",\n null);\n return request;\n },\n\n /**\n * Requests a logIn sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * login by AV.User.logInWithMobilePhoneSmsCode function.\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that want to login by AV.User.logInWithMobilePhoneSmsCode\n * @return {Promise}\n */\n requestLoginSmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestLoginSmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {Promise.} resolved with the currently logged in AV.User.\n */\n currentAsync: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser) {\n return Promise.resolve(AV.User._currentUser);\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return Promise.resolve(AV.User._currentUser);\n }\n\n\n return AV.localStorage.getItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY)\n ).then(function(userData) {\n if (!userData) {\n return null;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n });\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {AV.User} The currently logged in AV.User.\n */\n current: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return null;\n }\n\n if (AV.User._currentUser) {\n return AV.User._currentUser;\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return AV.User._currentUser;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n var userData = AV.localStorage.getItem(AV._getAVPath(\n AV.User._CURRENT_USER_KEY));\n if (!userData) {\n\n return null;\n }\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n },\n\n /**\n * Persists a user as currentUser to localStorage, and into the singleton.\n * @private\n */\n _saveCurrentUser: function(user) {\n var promise;\n if (AV.User._currentUser !== user) {\n promise = AV.User.logOut();\n }\n else {\n promise = Promise.resolve();\n }\n return promise.then(function() {\n user._isCurrentUser = true;\n AV.User._currentUser = user;\n\n var json = user.toJSON();\n json._id = user.id;\n json._sessionToken = user._sessionToken;\n return AV.localStorage.setItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY),\n JSON.stringify(json)\n ).then(function() {\n AV.User._currentUserMatchesDisk = true;\n });\n });\n },\n\n _registerAuthenticationProvider: function(provider) {\n AV.User._authProviders[provider.getAuthType()] = provider;\n // Synchronize the current user with the auth provider.\n if (!AV._config.disableCurrentUser && AV.User.current()) {\n AV.User.current()._synchronizeAuthData(provider.getAuthType());\n }\n },\n\n _logInWith: function(provider, options) {\n var user = AV.Object._create(\"_User\");\n return user._linkWith(provider, options);\n }\n\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/user.js","/*!\n * LeanCloud JavaScript SDK\n * https://leancloud.cn\n *\n * Copyright 2016 LeanCloud.cn, Inc.\n * The LeanCloud JavaScript SDK is freely distributable under the MIT license.\n */\n\nconst AV = require('./av');\n\nAV._ = require('underscore');\nAV.version = require('./version');\nAV.Promise = require('./promise');\nAV.localStorage = require('./localstorage');\nAV.Cache = require('./cache');\nAV.Error = require('./error');\n\nrequire('./init');\nrequire('./event')(AV);\nrequire('./geopoint')(AV);\nrequire('./acl')(AV);\nrequire('./op')(AV);\nrequire('./relation')(AV);\nrequire('./file')(AV);\nrequire('./object')(AV);\nrequire('./role')(AV);\nrequire('./user')(AV);\nrequire('./query')(AV);\nrequire('./cloudfunction')(AV);\nrequire('./push')(AV);\nrequire('./status')(AV);\nrequire('./search')(AV);\nrequire('./insight')(AV);\n\nmodule.exports = AV;\n\n/**\n * Options to controll the authentication for an operation\n * @typedef {Object} AuthOptions\n * @property {String} [sessionToken] Specify a user to excute the operation as.\n * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided.\n * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set.\n */\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","module.exports = [];\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/comments-browser.js","const version = require('../version');\nconst comments = [process.env.CLIENT_PLATFORM || 'Node.js'].concat(require('./comments'));\n\nmodule.exports = `LeanCloud-JS-SDK/${version} (${comments.join('; ')})`;\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/index.js","const request = require('superagent');\nconst debug = require('debug')('cos');\nconst Promise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n const uploadUrl = uploadInfo.upload_url + \"?sign=\" + encodeURIComponent(uploadInfo.token);\n\n return new Promise((resolve, reject) => {\n const req = request('POST', uploadUrl)\n .field('fileContent', data)\n .field('op', 'upload');\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/cos.js","const request = require('superagent');\nconst Promise = require('../promise');\nconst debug = require('debug')('qiniu');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n // Get the uptoken to upload files to qiniu.\n const uptoken = uploadInfo.token;\n return new Promise((resolve, reject) => {\n const req = request('POST', 'https://up.qbox.me')\n .field('file', data)\n .field('name', file.attributes.name)\n .field('key', file._qiniu_key)\n .field('token', uptoken);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/qiniu-browser.js","const request = require('superagent');\nconst AVPromise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n return new Promise((resolve, reject) => {\n // 海外节点,针对 S3 才会返回 upload_url\n const req = request('PUT', uploadInfo.upload_url)\n .set('Content-Type', file.get('mime_type'))\n .send(data);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/s3.js","var _ = require('underscore');\nvar Promise = require('../promise');\n\n// interface Storage {\n// readonly attribute boolean async;\n// string getItem(string key);\n// void setItem(string key, string value);\n// void removeItem(string key);\n// void clear();\n// Promise getItemAsync(string key);\n// Promise setItemAsync(string key, string value);\n// Promise removeItemAsync(string key);\n// Promise clearAsync();\n// }\nvar Storage = {};\nvar apiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nvar localStorage = global.localStorage;\n\ntry {\n var testKey = '__storejs__';\n localStorage.setItem(testKey, testKey);\n if (localStorage.getItem(testKey) != testKey) {\n throw new Error();\n }\n localStorage.removeItem(testKey);\n} catch (e) {\n localStorage = require('localstorage-memory');\n}\n\n// in browser, `localStorage.async = false` will excute `localStorage.setItem('async', false)`\n_(apiNames).each(function(apiName) {\n Storage[apiName] = function() {\n return global.localStorage[apiName].apply(global.localStorage, arguments);\n };\n});\nStorage.async = false;\n\nmodule.exports = Storage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/localstorage-browser.js","var dataURItoBlob = function(dataURI, type) {\n var byteString;\n\n // 传入的 base64,不是 dataURL\n if (dataURI.indexOf('base64') < 0) {\n byteString = atob(dataURI);\n } else if (dataURI.split(',')[0].indexOf('base64') >= 0) {\n type = type || dataURI.split(',')[0].split(':')[1].split(';')[0];\n byteString = atob(dataURI.split(',')[1]);\n } else {\n byteString = unescape(dataURI.split(',')[1]);\n }\n var ia = new Uint8Array(byteString.length);\n for (var i = 0; i < byteString.length; i ++) {\n ia[i] = byteString.charCodeAt(i);\n }\n return new Blob([ia], {type});\n};\n\nmodule.exports = dataURItoBlob;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/parse-base64-browser.js","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/component-emitter/index.js\n// module id = 38\n// module chunks = 0","(function() {\n var base64map\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n crypt = {\n // Bit-wise rotation left\n rotl: function(n, b) {\n return (n << b) | (n >>> (32 - b));\n },\n\n // Bit-wise rotation right\n rotr: function(n, b) {\n return (n << (32 - b)) | (n >>> b);\n },\n\n // Swap big-endian to little-endian and vice versa\n endian: function(n) {\n // If number given, swap endian\n if (n.constructor == Number) {\n return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n }\n\n // Else, assume array and swap all items\n for (var i = 0; i < n.length; i++)\n n[i] = crypt.endian(n[i]);\n return n;\n },\n\n // Generate an array of any length of random bytes\n randomBytes: function(n) {\n for (var bytes = []; n > 0; n--)\n bytes.push(Math.floor(Math.random() * 256));\n return bytes;\n },\n\n // Convert a byte array to big-endian 32-bit words\n bytesToWords: function(bytes) {\n for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n words[b >>> 5] |= bytes[i] << (24 - b % 32);\n return words;\n },\n\n // Convert big-endian 32-bit words to a byte array\n wordsToBytes: function(words) {\n for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a hex string\n bytesToHex: function(bytes) {\n for (var hex = [], i = 0; i < bytes.length; i++) {\n hex.push((bytes[i] >>> 4).toString(16));\n hex.push((bytes[i] & 0xF).toString(16));\n }\n return hex.join('');\n },\n\n // Convert a hex string to a byte array\n hexToBytes: function(hex) {\n for (var bytes = [], c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return bytes;\n },\n\n // Convert a byte array to a base-64 string\n bytesToBase64: function(bytes) {\n for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n for (var j = 0; j < 4; j++)\n if (i * 8 + j * 6 <= bytes.length * 8)\n base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n else\n base64.push('=');\n }\n return base64.join('');\n },\n\n // Convert a base-64 string to a byte array\n base64ToBytes: function(base64) {\n // Remove non-base-64 characters\n base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n imod4 = ++i % 4) {\n if (imod4 == 0) continue;\n bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n }\n return bytes;\n }\n };\n\n module.exports = crypt;\n})();\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/crypt/crypt.js\n// module id = 39\n// module chunks = 0","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (namespaces || '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/debug.js\n// module id = 40\n// module chunks = 0","/*!\n * @overview es6-promise - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE\n * @version 4.1.0\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.ES6Promise = factory());\n}(this, (function () { 'use strict';\n\nfunction objectOrFunction(x) {\n return typeof x === 'function' || typeof x === 'object' && x !== null;\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\nvar _isArray = undefined;\nif (!Array.isArray) {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n} else {\n _isArray = Array.isArray;\n}\n\nvar isArray = _isArray;\n\nvar len = 0;\nvar vertxNext = undefined;\nvar customSchedulerFn = undefined;\n\nvar asap = function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 2, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n if (customSchedulerFn) {\n customSchedulerFn(flush);\n } else {\n scheduleFlush();\n }\n }\n};\n\nfunction setScheduler(scheduleFn) {\n customSchedulerFn = scheduleFn;\n}\n\nfunction setAsap(asapFn) {\n asap = asapFn;\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // see https://github.com/cujojs/when/issues/410 for details\n return function () {\n return process.nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n if (typeof vertxNext !== 'undefined') {\n return function () {\n vertxNext(flush);\n };\n }\n\n return useSetTimeout();\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n // Store setTimeout reference so es6-promise will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var globalSetTimeout = setTimeout;\n return function () {\n return globalSetTimeout(flush, 1);\n };\n}\n\nvar queue = new Array(1000);\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n\n callback(arg);\n\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertx() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush = undefined;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush = attemptVertx();\n} else {\n scheduleFlush = useSetTimeout();\n}\n\nfunction then(onFulfillment, onRejection) {\n var _arguments = arguments;\n\n var parent = this;\n\n var child = new this.constructor(noop);\n\n if (child[PROMISE_ID] === undefined) {\n makePromise(child);\n }\n\n var _state = parent._state;\n\n if (_state) {\n (function () {\n var callback = _arguments[_state - 1];\n asap(function () {\n return invokeCallback(_state, child, callback, parent._result);\n });\n })();\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\n/**\n `Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {Any} value value that the returned promise will be resolved with\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve(object) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop);\n _resolve(promise, object);\n return promise;\n}\n\nvar PROMISE_ID = Math.random().toString(36).substring(16);\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nfunction selfFulfillment() {\n return new TypeError(\"You cannot resolve a promise with itself\");\n}\n\nfunction cannotReturnOwn() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then) {\n asap(function (promise) {\n var sealed = false;\n var error = tryThen(then, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n _resolve(promise, value);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n _reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n _reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n _reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n return _resolve(promise, value);\n }, function (reason) {\n return _reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$) {\n if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$ === GET_THEN_ERROR) {\n _reject(promise, GET_THEN_ERROR.error);\n GET_THEN_ERROR.error = null;\n } else if (then$$ === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$)) {\n handleForeignThenable(promise, maybeThenable, then$$);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction _resolve(promise, value) {\n if (promise === value) {\n _reject(promise, selfFulfillment());\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onerror) {\n promise._onerror(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length !== 0) {\n asap(publish, promise);\n }\n}\n\nfunction _reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n\n asap(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var _subscribers = parent._subscribers;\n var length = _subscribers.length;\n\n parent._onerror = null;\n\n _subscribers[length] = child;\n _subscribers[length + FULFILLED] = onFulfillment;\n _subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n asap(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = undefined,\n callback = undefined,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = undefined,\n error = undefined,\n succeeded = undefined,\n failed = undefined;\n\n if (hasCallback) {\n value = tryCatch(callback, detail);\n\n if (value === TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value.error = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n _reject(promise, cannotReturnOwn());\n return;\n }\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n _resolve(promise, value);\n } else if (failed) {\n _reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n _reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n try {\n resolver(function resolvePromise(value) {\n _resolve(promise, value);\n }, function rejectPromise(reason) {\n _reject(promise, reason);\n });\n } catch (e) {\n _reject(promise, e);\n }\n}\n\nvar id = 0;\nfunction nextId() {\n return id++;\n}\n\nfunction makePromise(promise) {\n promise[PROMISE_ID] = id++;\n promise._state = undefined;\n promise._result = undefined;\n promise._subscribers = [];\n}\n\nfunction Enumerator(Constructor, input) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop);\n\n if (!this.promise[PROMISE_ID]) {\n makePromise(this.promise);\n }\n\n if (isArray(input)) {\n this._input = input;\n this.length = input.length;\n this._remaining = input.length;\n\n this._result = new Array(this.length);\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate();\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n _reject(this.promise, validationError());\n }\n}\n\nfunction validationError() {\n return new Error('Array Methods must be provided an Array');\n};\n\nEnumerator.prototype._enumerate = function () {\n var length = this.length;\n var _input = this._input;\n\n for (var i = 0; this._state === PENDING && i < length; i++) {\n this._eachEntry(_input[i], i);\n }\n};\n\nEnumerator.prototype._eachEntry = function (entry, i) {\n var c = this._instanceConstructor;\n var resolve$$ = c.resolve;\n\n if (resolve$$ === resolve) {\n var _then = getThen(entry);\n\n if (_then === then && entry._state !== PENDING) {\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof _then !== 'function') {\n this._remaining--;\n this._result[i] = entry;\n } else if (c === Promise) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, _then);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve$$) {\n return resolve$$(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve$$(entry), i);\n }\n};\n\nEnumerator.prototype._settledAt = function (state, i, value) {\n var promise = this.promise;\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (state === REJECTED) {\n _reject(promise, value);\n } else {\n this._result[i] = value;\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n};\n\nEnumerator.prototype._willSettleAt = function (promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n};\n\n/**\n `Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = resolve(2);\n let promise3 = resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = reject(new Error(\"2\"));\n let promise3 = reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries) {\n return new Enumerator(this, entries).promise;\n}\n\n/**\n `Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} promises array of promises to observe\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (!isArray(entries)) {\n return new Constructor(function (_, reject) {\n return reject(new TypeError('You must pass an array to race.'));\n });\n } else {\n return new Constructor(function (resolve, reject) {\n var length = entries.length;\n for (var i = 0; i < length; i++) {\n Constructor.resolve(entries[i]).then(resolve, reject);\n }\n });\n }\n}\n\n/**\n `Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {Any} reason value that the returned promise will be rejected with.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject(reason) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop);\n _reject(promise, reason);\n return promise;\n}\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise's eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {function} resolver\n Useful for tooling.\n @constructor\n*/\nfunction Promise(resolver) {\n this[PROMISE_ID] = nextId();\n this._result = this._state = undefined;\n this._subscribers = [];\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n}\n\nPromise.all = all;\nPromise.race = race;\nPromise.resolve = resolve;\nPromise.reject = reject;\nPromise._setScheduler = setScheduler;\nPromise._setAsap = setAsap;\nPromise._asap = asap;\n\nPromise.prototype = {\n constructor: Promise,\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n \n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n \n Chaining\n --------\n \n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n \n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n \n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n \n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n \n Assimilation\n ------------\n \n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n \n If the assimliated promise rejects, then the downstream promise will also reject.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n \n Simple Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let result;\n \n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n \n Advanced Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let author, books;\n \n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n \n function foundBooks(books) {\n \n }\n \n function failure(reason) {\n \n }\n \n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n \n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n then: then,\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function _catch(onRejection) {\n return this.then(null, onRejection);\n }\n};\n\nfunction polyfill() {\n var local = undefined;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P) {\n var promiseToString = null;\n try {\n promiseToString = Object.prototype.toString.call(P.resolve());\n } catch (e) {\n // silently ignored\n }\n\n if (promiseToString === '[object Promise]' && !P.cast) {\n return;\n }\n }\n\n local.Promise = Promise;\n}\n\n// Strange compat..\nPromise.polyfill = polyfill;\nPromise.Promise = Promise;\n\nreturn Promise;\n\n})));\n//# sourceMappingURL=es6-promise.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/es6-promise/dist/es6-promise.js\n// module id = 41\n// module chunks = 0","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/is-buffer/index.js\n// module id = 42\n// module chunks = 0","(function(root) {\n var localStorageMemory = {};\n var cache = {};\n\n /**\n * number of stored items.\n */\n localStorageMemory.length = 0;\n\n /**\n * returns item for passed key, or null\n *\n * @para {String} key\n * name of item to be returned\n * @returns {String|null}\n */\n localStorageMemory.getItem = function(key) {\n return cache[key] || null;\n };\n\n /**\n * sets item for key to passed value, as String\n *\n * @para {String} key\n * name of item to be set\n * @para {String} value\n * value, will always be turned into a String\n * @returns {undefined}\n */\n localStorageMemory.setItem = function(key, value) {\n if (typeof value === 'undefined') {\n localStorageMemory.removeItem(key);\n } else {\n if (!(cache.hasOwnProperty(key))) {\n localStorageMemory.length++;\n }\n\n cache[key] = '' + value;\n }\n };\n\n /**\n * removes item for passed key\n *\n * @para {String} key\n * name of item to be removed\n * @returns {undefined}\n */\n localStorageMemory.removeItem = function(key) {\n if (cache.hasOwnProperty(key)) {\n delete cache[key];\n localStorageMemory.length--;\n }\n };\n\n /**\n * returns name of key at passed index\n *\n * @para {Number} index\n * Position for key to be returned (starts at 0)\n * @returns {String|null}\n */\n localStorageMemory.key = function(index) {\n return Object.keys(cache)[index] || null;\n };\n\n /**\n * removes all stored items and sets length to 0\n *\n * @returns {undefined}\n */\n localStorageMemory.clear = function() {\n cache = {};\n localStorageMemory.length = 0;\n };\n\n if (typeof exports === 'object') {\n module.exports = localStorageMemory;\n } else {\n root.localStorageMemory = localStorageMemory;\n }\n})(this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/localstorage-memory/lib/localstorage-memory.js\n// module id = 43\n// module chunks = 0","(function(){\r\n var crypt = require('crypt'),\r\n utf8 = require('charenc').utf8,\r\n isBuffer = require('is-buffer'),\r\n bin = require('charenc').bin,\r\n\r\n // The core\r\n md5 = function (message, options) {\r\n // Convert to byte array\r\n if (message.constructor == String)\r\n if (options && options.encoding === 'binary')\r\n message = bin.stringToBytes(message);\r\n else\r\n message = utf8.stringToBytes(message);\r\n else if (isBuffer(message))\r\n message = Array.prototype.slice.call(message, 0);\r\n else if (!Array.isArray(message))\r\n message = message.toString();\r\n // else, assume byte array already\r\n\r\n var m = crypt.bytesToWords(message),\r\n l = message.length * 8,\r\n a = 1732584193,\r\n b = -271733879,\r\n c = -1732584194,\r\n d = 271733878;\r\n\r\n // Swap endian\r\n for (var i = 0; i < m.length; i++) {\r\n m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;\r\n }\r\n\r\n // Padding\r\n m[l >>> 5] |= 0x80 << (l % 32);\r\n m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n // Method shortcuts\r\n var FF = md5._ff,\r\n GG = md5._gg,\r\n HH = md5._hh,\r\n II = md5._ii;\r\n\r\n for (var i = 0; i < m.length; i += 16) {\r\n\r\n var aa = a,\r\n bb = b,\r\n cc = c,\r\n dd = d;\r\n\r\n a = FF(a, b, c, d, m[i+ 0], 7, -680876936);\r\n d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n c = FF(c, d, a, b, m[i+ 2], 17, 606105819);\r\n b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n a = FF(a, b, c, d, m[i+ 4], 7, -176418897);\r\n d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);\r\n c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);\r\n d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n a = FF(a, b, c, d, m[i+12], 7, 1804603682);\r\n d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n b = FF(b, c, d, a, m[i+15], 22, 1236535329);\r\n\r\n a = GG(a, b, c, d, m[i+ 1], 5, -165796510);\r\n d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);\r\n c = GG(c, d, a, b, m[i+11], 14, 643717713);\r\n b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n a = GG(a, b, c, d, m[i+ 5], 5, -701558691);\r\n d = GG(d, a, b, c, m[i+10], 9, 38016083);\r\n c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n a = GG(a, b, c, d, m[i+ 9], 5, 568446438);\r\n d = GG(d, a, b, c, m[i+14], 9, -1019803690);\r\n c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);\r\n a = GG(a, b, c, d, m[i+13], 5, -1444681467);\r\n d = GG(d, a, b, c, m[i+ 2], 9, -51403784);\r\n c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);\r\n b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n a = HH(a, b, c, d, m[i+ 5], 4, -378558);\r\n d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n c = HH(c, d, a, b, m[i+11], 16, 1839030562);\r\n b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);\r\n d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);\r\n c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n a = HH(a, b, c, d, m[i+13], 4, 681279174);\r\n d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n b = HH(b, c, d, a, m[i+ 6], 23, 76029189);\r\n a = HH(a, b, c, d, m[i+ 9], 4, -640364487);\r\n d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n c = HH(c, d, a, b, m[i+15], 16, 530742520);\r\n b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n a = II(a, b, c, d, m[i+ 0], 6, -198630844);\r\n d = II(d, a, b, c, m[i+ 7], 10, 1126891415);\r\n c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n a = II(a, b, c, d, m[i+12], 6, 1700485571);\r\n d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n a = II(a, b, c, d, m[i+ 8], 6, 1873313359);\r\n d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n b = II(b, c, d, a, m[i+13], 21, 1309151649);\r\n a = II(a, b, c, d, m[i+ 4], 6, -145523070);\r\n d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n c = II(c, d, a, b, m[i+ 2], 15, 718787259);\r\n b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n a = (a + aa) >>> 0;\r\n b = (b + bb) >>> 0;\r\n c = (c + cc) >>> 0;\r\n d = (d + dd) >>> 0;\r\n }\r\n\r\n return crypt.endian([a, b, c, d]);\r\n };\r\n\r\n // Auxiliary functions\r\n md5._ff = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._gg = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._hh = function (a, b, c, d, x, s, t) {\r\n var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._ii = function (a, b, c, d, x, s, t) {\r\n var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n\r\n // Package private blocksize\r\n md5._blocksize = 16;\r\n md5._digestsize = 16;\r\n\r\n module.exports = function (message, options) {\r\n if (message === undefined || message === null)\r\n throw new Error('Illegal argument ' + message);\r\n\r\n var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n return options && options.asBytes ? digestbytes :\r\n options && options.asString ? bin.bytesToString(digestbytes) :\r\n crypt.bytesToHex(digestbytes);\r\n };\r\n\r\n})();\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/md5/md5.js\n// module id = 44\n// module chunks = 0","/**\n * Helpers.\n */\n\nvar s = 1000\nvar m = s * 60\nvar h = m * 60\nvar d = h * 24\nvar y = d * 365.25\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} options\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {}\n var type = typeof val\n if (type === 'string' && val.length > 0) {\n return parse(val)\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ?\n\t\t\tfmtLong(val) :\n\t\t\tfmtShort(val)\n }\n throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))\n}\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str)\n if (str.length > 10000) {\n return\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)\n if (!match) {\n return\n }\n var n = parseFloat(match[1])\n var type = (match[2] || 'ms').toLowerCase()\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y\n case 'days':\n case 'day':\n case 'd':\n return n * d\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n\n default:\n return undefined\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd'\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h'\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm'\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's'\n }\n return ms + 'ms'\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms'\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name\n }\n return Math.ceil(ms / n) + ' ' + name + 's'\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ms/index.js\n// module id = 45\n// module chunks = 0","/**\n * Check if `fn` is a function.\n *\n * @param {Function} fn\n * @return {Boolean}\n * @api private\n */\nvar isObject = require('./is-object');\n\nfunction isFunction(fn) {\n var tag = isObject(fn) ? Object.prototype.toString.call(fn) : '';\n return tag === '[object Function]';\n}\n\nmodule.exports = isFunction;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-function.js\n// module id = 46\n// module chunks = 0","/**\n * Module of mixed-in functions shared between node and client code\n */\nvar isObject = require('./is-object');\n\n/**\n * Expose `RequestBase`.\n */\n\nmodule.exports = RequestBase;\n\n/**\n * Initialize a new `RequestBase`.\n *\n * @api public\n */\n\nfunction RequestBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in RequestBase.prototype) {\n obj[key] = RequestBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Clear previous timeout.\n *\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.clearTimeout = function _clearTimeout(){\n clearTimeout(this._timer);\n clearTimeout(this._responseTimeoutTimer);\n delete this._timer;\n delete this._responseTimeoutTimer;\n return this;\n};\n\n/**\n * Override default response body parser\n *\n * This function will be called to convert incoming data into request.body\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.parse = function parse(fn){\n this._parser = fn;\n return this;\n};\n\n/**\n * Set format of binary response body.\n * In browser valid formats are 'blob' and 'arraybuffer',\n * which return Blob and ArrayBuffer, respectively.\n *\n * In Node all values result in Buffer.\n *\n * Examples:\n *\n * req.get('/')\n * .responseType('blob')\n * .end(callback);\n *\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.responseType = function(val){\n this._responseType = val;\n return this;\n};\n\n/**\n * Override default request body serializer\n *\n * This function will be called to convert data set via .send or .attach into payload to send\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.serialize = function serialize(fn){\n this._serializer = fn;\n return this;\n};\n\n/**\n * Set timeouts.\n *\n * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.\n * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.\n *\n * Value of 0 or false means no timeout.\n *\n * @param {Number|Object} ms or {response, read, deadline}\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.timeout = function timeout(options){\n if (!options || 'object' !== typeof options) {\n this._timeout = options;\n this._responseTimeout = 0;\n return this;\n }\n\n for(var option in options) {\n switch(option) {\n case 'deadline':\n this._timeout = options.deadline;\n break;\n case 'response':\n this._responseTimeout = options.response;\n break;\n default:\n console.warn(\"Unknown timeout option\", option);\n }\n }\n return this;\n};\n\n/**\n * Set number of retry attempts on error.\n *\n * Failed requests will be retried 'count' times if timeout or err.code >= 500.\n *\n * @param {Number} count\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.retry = function retry(count){\n // Default to 1 if no count passed or true\n if (arguments.length === 0 || count === true) count = 1;\n if (count <= 0) count = 0;\n this._maxRetries = count;\n this._retries = 0;\n return this;\n};\n\n/**\n * Retry request\n *\n * @return {Request} for chaining\n * @api private\n */\n\nRequestBase.prototype._retry = function() {\n this.clearTimeout();\n\n // node\n if (this.req) {\n this.req = null;\n this.req = this.request();\n }\n\n this._aborted = false;\n this.timedout = false;\n\n return this._end();\n};\n\n/**\n * Promise support\n *\n * @param {Function} resolve\n * @param {Function} [reject]\n * @return {Request}\n */\n\nRequestBase.prototype.then = function then(resolve, reject) {\n if (!this._fullfilledPromise) {\n var self = this;\n if (this._endCalled) {\n console.warn(\"Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises\");\n }\n this._fullfilledPromise = new Promise(function(innerResolve, innerReject){\n self.end(function(err, res){\n if (err) innerReject(err); else innerResolve(res);\n });\n });\n }\n return this._fullfilledPromise.then(resolve, reject);\n}\n\nRequestBase.prototype.catch = function(cb) {\n return this.then(undefined, cb);\n};\n\n/**\n * Allow for extension\n */\n\nRequestBase.prototype.use = function use(fn) {\n fn(this);\n return this;\n}\n\nRequestBase.prototype.ok = function(cb) {\n if ('function' !== typeof cb) throw Error(\"Callback required\");\n this._okCallback = cb;\n return this;\n};\n\nRequestBase.prototype._isResponseOK = function(res) {\n if (!res) {\n return false;\n }\n\n if (this._okCallback) {\n return this._okCallback(res);\n }\n\n return res.status >= 200 && res.status < 300;\n};\n\n\n/**\n * Get request header `field`.\n * Case-insensitive.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nRequestBase.prototype.get = function(field){\n return this._header[field.toLowerCase()];\n};\n\n/**\n * Get case-insensitive header `field` value.\n * This is a deprecated internal API. Use `.get(field)` instead.\n *\n * (getHeader is no longer used internally by the superagent code base)\n *\n * @param {String} field\n * @return {String}\n * @api private\n * @deprecated\n */\n\nRequestBase.prototype.getHeader = RequestBase.prototype.get;\n\n/**\n * Set header `field` to `val`, or multiple fields with one object.\n * Case-insensitive.\n *\n * Examples:\n *\n * req.get('/')\n * .set('Accept', 'application/json')\n * .set('X-API-Key', 'foobar')\n * .end(callback);\n *\n * req.get('/')\n * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })\n * .end(callback);\n *\n * @param {String|Object} field\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.set = function(field, val){\n if (isObject(field)) {\n for (var key in field) {\n this.set(key, field[key]);\n }\n return this;\n }\n this._header[field.toLowerCase()] = val;\n this.header[field] = val;\n return this;\n};\n\n/**\n * Remove header `field`.\n * Case-insensitive.\n *\n * Example:\n *\n * req.get('/')\n * .unset('User-Agent')\n * .end(callback);\n *\n * @param {String} field\n */\nRequestBase.prototype.unset = function(field){\n delete this._header[field.toLowerCase()];\n delete this.header[field];\n return this;\n};\n\n/**\n * Write the field `name` and `val`, or multiple fields with one object\n * for \"multipart/form-data\" request bodies.\n *\n * ``` js\n * request.post('/upload')\n * .field('foo', 'bar')\n * .end(callback);\n *\n * request.post('/upload')\n * .field({ foo: 'bar', baz: 'qux' })\n * .end(callback);\n * ```\n *\n * @param {String|Object} name\n * @param {String|Blob|File|Buffer|fs.ReadStream} val\n * @return {Request} for chaining\n * @api public\n */\nRequestBase.prototype.field = function(name, val) {\n\n // name should be either a string or an object.\n if (null === name || undefined === name) {\n throw new Error('.field(name, val) name can not be empty');\n }\n\n if (this._data) {\n console.error(\".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObject(name)) {\n for (var key in name) {\n this.field(key, name[key]);\n }\n return this;\n }\n\n if (Array.isArray(val)) {\n for (var i in val) {\n this.field(name, val[i]);\n }\n return this;\n }\n\n // val should be defined now\n if (null === val || undefined === val) {\n throw new Error('.field(name, val) val can not be empty');\n }\n if ('boolean' === typeof val) {\n val = '' + val;\n }\n this._getFormData().append(name, val);\n return this;\n};\n\n/**\n * Abort the request, and clear potential timeout.\n *\n * @return {Request}\n * @api public\n */\nRequestBase.prototype.abort = function(){\n if (this._aborted) {\n return this;\n }\n this._aborted = true;\n this.xhr && this.xhr.abort(); // browser\n this.req && this.req.abort(); // node\n this.clearTimeout();\n this.emit('abort');\n return this;\n};\n\n/**\n * Enable transmission of cookies with x-domain requests.\n *\n * Note that for this to work the origin must not be\n * using \"Access-Control-Allow-Origin\" with a wildcard,\n * and also must set \"Access-Control-Allow-Credentials\"\n * to \"true\".\n *\n * @api public\n */\n\nRequestBase.prototype.withCredentials = function(on){\n // This is browser-only functionality. Node side is no-op.\n if(on==undefined) on = true;\n this._withCredentials = on;\n return this;\n};\n\n/**\n * Set the max redirects to `n`. Does noting in browser XHR implementation.\n *\n * @param {Number} n\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.redirects = function(n){\n this._maxRedirects = n;\n return this;\n};\n\n/**\n * Convert to a plain javascript object (not JSON string) of scalar properties.\n * Note as this method is designed to return a useful non-this value,\n * it cannot be chained.\n *\n * @return {Object} describing method, url, and data of this request\n * @api public\n */\n\nRequestBase.prototype.toJSON = function(){\n return {\n method: this.method,\n url: this.url,\n data: this._data,\n headers: this._header\n };\n};\n\n\n/**\n * Send `data` as the request body, defaulting the `.type()` to \"json\" when\n * an object is given.\n *\n * Examples:\n *\n * // manual json\n * request.post('/user')\n * .type('json')\n * .send('{\"name\":\"tj\"}')\n * .end(callback)\n *\n * // auto json\n * request.post('/user')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // manual x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send('name=tj')\n * .end(callback)\n *\n * // auto x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // defaults to x-www-form-urlencoded\n * request.post('/user')\n * .send('name=tobi')\n * .send('species=ferret')\n * .end(callback)\n *\n * @param {String|Object} data\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.send = function(data){\n var isObj = isObject(data);\n var type = this._header['content-type'];\n\n if (this._formData) {\n console.error(\".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObj && !this._data) {\n if (Array.isArray(data)) {\n this._data = [];\n } else if (!this._isHost(data)) {\n this._data = {};\n }\n } else if (data && this._data && this._isHost(this._data)) {\n throw Error(\"Can't merge these send calls\");\n }\n\n // merge\n if (isObj && isObject(this._data)) {\n for (var key in data) {\n this._data[key] = data[key];\n }\n } else if ('string' == typeof data) {\n // default to x-www-form-urlencoded\n if (!type) this.type('form');\n type = this._header['content-type'];\n if ('application/x-www-form-urlencoded' == type) {\n this._data = this._data\n ? this._data + '&' + data\n : data;\n } else {\n this._data = (this._data || '') + data;\n }\n } else {\n this._data = data;\n }\n\n if (!isObj || this._isHost(data)) {\n return this;\n }\n\n // default to json\n if (!type) this.type('json');\n return this;\n};\n\n\n/**\n * Sort `querystring` by the sort function\n *\n *\n * Examples:\n *\n * // default order\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery()\n * .end(callback)\n *\n * // customized sort function\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery(function(a, b){\n * return a.length - b.length;\n * })\n * .end(callback)\n *\n *\n * @param {Function} sort\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.sortQuery = function(sort) {\n // _sort default to true but otherwise can be a function or boolean\n this._sort = typeof sort === 'undefined' ? true : sort;\n return this;\n};\n\n/**\n * Invoke callback with timeout error.\n *\n * @api private\n */\n\nRequestBase.prototype._timeoutError = function(reason, timeout, errno){\n if (this._aborted) {\n return;\n }\n var err = new Error(reason + timeout + 'ms exceeded');\n err.timeout = timeout;\n err.code = 'ECONNABORTED';\n err.errno = errno;\n this.timedout = true;\n this.abort();\n this.callback(err);\n};\n\nRequestBase.prototype._setTimeouts = function() {\n var self = this;\n\n // deadline\n if (this._timeout && !this._timer) {\n this._timer = setTimeout(function(){\n self._timeoutError('Timeout of ', self._timeout, 'ETIME');\n }, this._timeout);\n }\n // response timeout\n if (this._responseTimeout && !this._responseTimeoutTimer) {\n this._responseTimeoutTimer = setTimeout(function(){\n self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');\n }, this._responseTimeout);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/request-base.js\n// module id = 47\n// module chunks = 0","\n/**\n * Module dependencies.\n */\n\nvar utils = require('./utils');\n\n/**\n * Expose `ResponseBase`.\n */\n\nmodule.exports = ResponseBase;\n\n/**\n * Initialize a new `ResponseBase`.\n *\n * @api public\n */\n\nfunction ResponseBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in ResponseBase.prototype) {\n obj[key] = ResponseBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Get case-insensitive `field` value.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nResponseBase.prototype.get = function(field){\n return this.header[field.toLowerCase()];\n};\n\n/**\n * Set header related properties:\n *\n * - `.type` the content type without params\n *\n * A response of \"Content-Type: text/plain; charset=utf-8\"\n * will provide you with a `.type` of \"text/plain\".\n *\n * @param {Object} header\n * @api private\n */\n\nResponseBase.prototype._setHeaderProperties = function(header){\n // TODO: moar!\n // TODO: make this a util\n\n // content-type\n var ct = header['content-type'] || '';\n this.type = utils.type(ct);\n\n // params\n var params = utils.params(ct);\n for (var key in params) this[key] = params[key];\n\n this.links = {};\n\n // links\n try {\n if (header.link) {\n this.links = utils.parseLinks(header.link);\n }\n } catch (err) {\n // ignore\n }\n};\n\n/**\n * Set flags such as `.ok` based on `status`.\n *\n * For example a 2xx response will give you a `.ok` of __true__\n * whereas 5xx will be __false__ and `.error` will be __true__. The\n * `.clientError` and `.serverError` are also available to be more\n * specific, and `.statusType` is the class of error ranging from 1..5\n * sometimes useful for mapping respond colors etc.\n *\n * \"sugar\" properties are also defined for common cases. Currently providing:\n *\n * - .noContent\n * - .badRequest\n * - .unauthorized\n * - .notAcceptable\n * - .notFound\n *\n * @param {Number} status\n * @api private\n */\n\nResponseBase.prototype._setStatusProperties = function(status){\n var type = status / 100 | 0;\n\n // status / class\n this.status = this.statusCode = status;\n this.statusType = type;\n\n // basics\n this.info = 1 == type;\n this.ok = 2 == type;\n this.redirect = 3 == type;\n this.clientError = 4 == type;\n this.serverError = 5 == type;\n this.error = (4 == type || 5 == type)\n ? this.toError()\n : false;\n\n // sugar\n this.accepted = 202 == status;\n this.noContent = 204 == status;\n this.badRequest = 400 == status;\n this.unauthorized = 401 == status;\n this.notAcceptable = 406 == status;\n this.forbidden = 403 == status;\n this.notFound = 404 == status;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/response-base.js\n// module id = 48\n// module chunks = 0","var ERROR_CODES = [\n 'ECONNRESET',\n 'ETIMEDOUT',\n 'EADDRINFO',\n 'ESOCKETTIMEDOUT'\n];\n\n/**\n * Determine if a request should be retried.\n * (Borrowed from segmentio/superagent-retry)\n *\n * @param {Error} err\n * @param {Response} [res]\n * @returns {Boolean}\n */\nmodule.exports = function shouldRetry(err, res) {\n if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true;\n if (res && res.status && res.status >= 500) return true;\n // Superagent timeout\n if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true;\n if (err && 'crossDomain' in err) return true;\n return false;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/should-retry.js\n// module id = 49\n// module chunks = 0","\n/**\n * Return the mime type for the given `str`.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nexports.type = function(str){\n return str.split(/ *; */).shift();\n};\n\n/**\n * Return header field parameters.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.params = function(str){\n return str.split(/ *; */).reduce(function(obj, str){\n var parts = str.split(/ *= */);\n var key = parts.shift();\n var val = parts.shift();\n\n if (key && val) obj[key] = val;\n return obj;\n }, {});\n};\n\n/**\n * Parse Link header fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.parseLinks = function(str){\n return str.split(/ *, */).reduce(function(obj, str){\n var parts = str.split(/ *; */);\n var url = parts[0].slice(1, -1);\n var rel = parts[1].split(/ *= */)[1].slice(1, -1);\n obj[rel] = url;\n return obj;\n }, {});\n};\n\n/**\n * Strip content related fields from `header`.\n *\n * @param {Object} header\n * @return {Object} header\n * @api private\n */\n\nexports.cleanHeader = function(header, shouldStripCookie){\n delete header['content-type'];\n delete header['content-length'];\n delete header['transfer-encoding'];\n delete header['host'];\n if (shouldStripCookie) {\n delete header['cookie'];\n }\n return header;\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/utils.js\n// module id = 50\n// module chunks = 0"]} \ No newline at end of file diff --git a/dist/av-rn.js b/dist/av-rn.js new file mode 100644 index 000000000..7b5a45b32 --- /dev/null +++ b/dist/av-rn.js @@ -0,0 +1,13997 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require("react-native")); + else if(typeof define === 'function' && define.amd) + define(["react-native"], factory); + else if(typeof exports === 'object') + exports["AV"] = factory(require("react-native")); + else + root["AV"] = factory(root["react-native"]); +})(this, function(__WEBPACK_EXTERNAL_MODULE_50__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 30); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Underscore.js 1.8.3 +// http://underscorejs.org +// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `exports` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var + push = ArrayProto.push, + slice = ArrayProto.slice, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind, + nativeCreate = Object.create; + + // Naked function reference for surrogate-prototype-swapping. + var Ctor = function(){}; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object. + if (true) { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.8.3'; + + // Internal function that returns an efficient (for current engines) version + // of the passed-in callback, to be repeatedly applied in other Underscore + // functions. + var optimizeCb = function(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 2: return function(value, other) { + return func.call(context, value, other); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; + } + return function() { + return func.apply(context, arguments); + }; + }; + + // A mostly-internal function to generate callbacks that can be applied + // to each element in a collection, returning the desired result — either + // identity, an arbitrary callback, a property matcher, or a property accessor. + var cb = function(value, context, argCount) { + if (value == null) return _.identity; + if (_.isFunction(value)) return optimizeCb(value, context, argCount); + if (_.isObject(value)) return _.matcher(value); + return _.property(value); + }; + _.iteratee = function(value, context) { + return cb(value, context, Infinity); + }; + + // An internal function for creating assigner functions. + var createAssigner = function(keysFunc, undefinedOnly) { + return function(obj) { + var length = arguments.length; + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + } + } + return obj; + }; + }; + + // An internal function for creating a new object that inherits from another. + var baseCreate = function(prototype) { + if (!_.isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + Ctor.prototype = prototype; + var result = new Ctor; + Ctor.prototype = null; + return result; + }; + + var property = function(key) { + return function(obj) { + return obj == null ? void 0 : obj[key]; + }; + }; + + // Helper for collection methods to determine whether a collection + // should be iterated as an array or as an object + // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength + // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; + var getLength = property('length'); + var isArrayLike = function(collection) { + var length = getLength(collection); + return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; + }; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles raw objects in addition to array-likes. Treats all + // sparse array-likes as if they were dense. + _.each = _.forEach = function(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var keys = _.keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + iteratee(obj[keys[i]], keys[i], obj); + } + } + return obj; + }; + + // Return the results of applying the iteratee to each element. + _.map = _.collect = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + results = Array(length); + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Create a reducing function iterating left or right. + function createReduce(dir) { + // Optimized iterator function as using arguments.length + // in the main function will deoptimize the, see #1991. + function iterator(obj, iteratee, memo, keys, index, length) { + for (; index >= 0 && index < length; index += dir) { + var currentKey = keys ? keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + } + + return function(obj, iteratee, memo, context) { + iteratee = optimizeCb(iteratee, context, 4); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + index = dir > 0 ? 0 : length - 1; + // Determine the initial value if none is provided. + if (arguments.length < 3) { + memo = obj[keys ? keys[index] : index]; + index += dir; + } + return iterator(obj, iteratee, memo, keys, index, length); + }; + } + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. + _.reduce = _.foldl = _.inject = createReduce(1); + + // The right-associative version of reduce, also known as `foldr`. + _.reduceRight = _.foldr = createReduce(-1); + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, predicate, context) { + var key; + if (isArrayLike(obj)) { + key = _.findIndex(obj, predicate, context); + } else { + key = _.findKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) return obj[key]; + }; + + // Return all the elements that pass a truth test. + // Aliased as `select`. + _.filter = _.select = function(obj, predicate, context) { + var results = []; + predicate = cb(predicate, context); + _.each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, predicate, context) { + return _.filter(obj, _.negate(cb(predicate)), context); + }; + + // Determine whether all of the elements match a truth test. + // Aliased as `all`. + _.every = _.all = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; + } + return true; + }; + + // Determine if at least one element in the object matches a truth test. + // Aliased as `any`. + _.some = _.any = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; + } + return false; + }; + + // Determine if the array or object contains a given item (using `===`). + // Aliased as `includes` and `include`. + _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + if (typeof fromIndex != 'number' || guard) fromIndex = 0; + return _.indexOf(obj, item, fromIndex) >= 0; + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + var func = isFunc ? method : value[method]; + return func == null ? func : func.apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, _.property(key)); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // containing specific `key:value` pairs. + _.where = function(obj, attrs) { + return _.filter(obj, _.matcher(attrs)); + }; + + // Convenience version of a common use case of `find`: getting the first object + // containing specific `key:value` pairs. + _.findWhere = function(obj, attrs) { + return _.find(obj, _.matcher(attrs)); + }; + + // Return the maximum element (or element-based computation). + _.max = function(obj, iteratee, context) { + var result = -Infinity, lastComputed = -Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value > result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed > lastComputed || computed === -Infinity && result === -Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed < lastComputed || computed === Infinity && result === Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Shuffle a collection, using the modern version of the + // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). + _.shuffle = function(obj) { + var set = isArrayLike(obj) ? obj : _.values(obj); + var length = set.length; + var shuffled = Array(length); + for (var index = 0, rand; index < length; index++) { + rand = _.random(0, index); + if (rand !== index) shuffled[index] = shuffled[rand]; + shuffled[rand] = set[index]; + } + return shuffled; + }; + + // Sample **n** random values from a collection. + // If **n** is not specified, returns a single random element. + // The internal `guard` argument allows it to work with `map`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + return _.shuffle(obj).slice(0, Math.max(0, n)); + }; + + // Sort the object's values by a criterion produced by an iteratee. + _.sortBy = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iteratee(value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iteratee, context) { + var result = {}; + iteratee = cb(iteratee, context); + _.each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + return result; + }; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = group(function(result, value, key) { + if (_.has(result, key)) result[key].push(value); else result[key] = [value]; + }); + + // Indexes the object's values by a criterion, similar to `groupBy`, but for + // when you know that your index values will be unique. + _.indexBy = group(function(result, value, key) { + result[key] = value; + }); + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = group(function(result, value, key) { + if (_.has(result, key)) result[key]++; else result[key] = 1; + }); + + // Safely create a real, live array from anything iterable. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); + if (isArrayLike(obj)) return _.map(obj, _.identity); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return isArrayLike(obj) ? obj.length : _.keys(obj).length; + }; + + // Split a collection into two arrays: one whose elements all satisfy the given + // predicate, and one whose elements all do not satisfy the predicate. + _.partition = function(obj, predicate, context) { + predicate = cb(predicate, context); + var pass = [], fail = []; + _.each(obj, function(value, key, obj) { + (predicate(value, key, obj) ? pass : fail).push(value); + }); + return [pass, fail]; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head` and `take`. The **guard** check + // allows it to work with `_.map`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[0]; + return _.initial(array, array.length - n); + }; + + // Returns everything but the last entry of the array. Especially useful on + // the arguments object. Passing **n** will return all the values in + // the array, excluding the last N. + _.initial = function(array, n, guard) { + return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); + }; + + // Get the last element of an array. Passing **n** will return the last N + // values in the array. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[array.length - 1]; + return _.rest(array, Math.max(0, array.length - n)); + }; + + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. + // Especially useful on the arguments object. Passing an **n** will return + // the rest N values in the array. + _.rest = _.tail = _.drop = function(array, n, guard) { + return slice.call(array, n == null || guard ? 1 : n); + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, _.identity); + }; + + // Internal implementation of a recursive `flatten` function. + var flatten = function(input, shallow, strict, startIndex) { + var output = [], idx = 0; + for (var i = startIndex || 0, length = getLength(input); i < length; i++) { + var value = input[i]; + if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { + //flatten current level of array or arguments object + if (!shallow) value = flatten(value, shallow, strict); + var j = 0, len = value.length; + output.length += len; + while (j < len) { + output[idx++] = value[j++]; + } + } else if (!strict) { + output[idx++] = value; + } + } + return output; + }; + + // Flatten out an array, either recursively (by default), or just one level. + _.flatten = function(array, shallow) { + return flatten(array, shallow, false); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted, iteratee, context) { + if (!_.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + if (iteratee != null) iteratee = cb(iteratee, context); + var result = []; + var seen = []; + for (var i = 0, length = getLength(array); i < length; i++) { + var value = array[i], + computed = iteratee ? iteratee(value, i, array) : value; + if (isSorted) { + if (!i || seen !== computed) result.push(value); + seen = computed; + } else if (iteratee) { + if (!_.contains(seen, computed)) { + seen.push(computed); + result.push(value); + } + } else if (!_.contains(result, value)) { + result.push(value); + } + } + return result; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(flatten(arguments, true, true)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var result = []; + var argsLength = arguments.length; + for (var i = 0, length = getLength(array); i < length; i++) { + var item = array[i]; + if (_.contains(result, item)) continue; + for (var j = 1; j < argsLength; j++) { + if (!_.contains(arguments[j], item)) break; + } + if (j === argsLength) result.push(item); + } + return result; + }; + + // Take the difference between one array and a number of other arrays. + // Only the elements present in just the first array will remain. + _.difference = function(array) { + var rest = flatten(arguments, true, true, 1); + return _.filter(array, function(value){ + return !_.contains(rest, value); + }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + return _.unzip(arguments); + }; + + // Complement of _.zip. Unzip accepts an array of arrays and groups + // each array's elements on shared indices + _.unzip = function(array) { + var length = array && _.max(array, getLength).length || 0; + var result = Array(length); + + for (var index = 0; index < length; index++) { + result[index] = _.pluck(array, index); + } + return result; + }; + + // Converts lists into objects. Pass either a single array of `[key, value]` + // pairs, or two parallel arrays of the same length -- one of keys, and one of + // the corresponding values. + _.object = function(list, values) { + var result = {}; + for (var i = 0, length = getLength(list); i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // Generator function to create the findIndex and findLastIndex functions + function createPredicateIndexFinder(dir) { + return function(array, predicate, context) { + predicate = cb(predicate, context); + var length = getLength(array); + var index = dir > 0 ? 0 : length - 1; + for (; index >= 0 && index < length; index += dir) { + if (predicate(array[index], index, array)) return index; + } + return -1; + }; + } + + // Returns the first index on an array-like that passes a predicate test + _.findIndex = createPredicateIndexFinder(1); + _.findLastIndex = createPredicateIndexFinder(-1); + + // Use a comparator function to figure out the smallest index at which + // an object should be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iteratee, context) { + iteratee = cb(iteratee, context, 1); + var value = iteratee(obj); + var low = 0, high = getLength(array); + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; + } + return low; + }; + + // Generator function to create the indexOf and lastIndexOf functions + function createIndexFinder(dir, predicateFind, sortedIndex) { + return function(array, item, idx) { + var i = 0, length = getLength(array); + if (typeof idx == 'number') { + if (dir > 0) { + i = idx >= 0 ? idx : Math.max(idx + length, i); + } else { + length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; + } + } else if (sortedIndex && idx && length) { + idx = sortedIndex(array, item); + return array[idx] === item ? idx : -1; + } + if (item !== item) { + idx = predicateFind(slice.call(array, i, length), _.isNaN); + return idx >= 0 ? idx + i : -1; + } + for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { + if (array[idx] === item) return idx; + } + return -1; + }; + } + + // Return the position of the first occurrence of an item in an array, + // or -1 if the item is not included in the array. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); + _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (stop == null) { + stop = start || 0; + start = 0; + } + step = step || 1; + + var length = Math.max(Math.ceil((stop - start) / step), 0); + var range = Array(length); + + for (var idx = 0; idx < length; idx++, start += step) { + range[idx] = start; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Determines whether to execute a function as a constructor + // or a normal function with the provided arguments + var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { + if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); + var self = baseCreate(sourceFunc.prototype); + var result = sourceFunc.apply(self, args); + if (_.isObject(result)) return result; + return self; + }; + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if + // available. + _.bind = function(func, context) { + if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); + var args = slice.call(arguments, 2); + var bound = function() { + return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); + }; + return bound; + }; + + // Partially apply a function by creating a version that has had some of its + // arguments pre-filled, without changing its dynamic `this` context. _ acts + // as a placeholder, allowing any combination of arguments to be pre-filled. + _.partial = function(func) { + var boundArgs = slice.call(arguments, 1); + var bound = function() { + var position = 0, length = boundArgs.length; + var args = Array(length); + for (var i = 0; i < length; i++) { + args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; + } + while (position < arguments.length) args.push(arguments[position++]); + return executeBound(func, bound, this, this, args); + }; + return bound; + }; + + // Bind a number of an object's methods to that object. Remaining arguments + // are the method names to be bound. Useful for ensuring that all callbacks + // defined on an object belong to it. + _.bindAll = function(obj) { + var i, length = arguments.length, key; + if (length <= 1) throw new Error('bindAll must be passed function names'); + for (i = 1; i < length; i++) { + key = arguments[i]; + obj[key] = _.bind(obj[key], obj); + } + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memoize = function(key) { + var cache = memoize.cache; + var address = '' + (hasher ? hasher.apply(this, arguments) : key); + if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); + return cache[address]; + }; + memoize.cache = {}; + return memoize; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ + return func.apply(null, args); + }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = _.partial(_.delay, _, 1); + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. Normally, the throttled function will run + // as much as it can, without ever going more than once per `wait` duration; + // but if you'd like to disable the execution on the leading edge, pass + // `{leading: false}`. To disable execution on the trailing edge, ditto. + _.throttle = function(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + if (!options) options = {}; + var later = function() { + previous = options.leading === false ? 0 : _.now(); + timeout = null; + result = func.apply(context, args); + if (!timeout) context = args = null; + }; + return function() { + var now = _.now(); + if (!previous && options.leading === false) previous = now; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0 || remaining > wait) { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + previous = now; + result = func.apply(context, args); + if (!timeout) context = args = null; + } else if (!timeout && options.trailing !== false) { + timeout = setTimeout(later, remaining); + } + return result; + }; + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. If `immediate` is passed, trigger the function on the + // leading edge, instead of the trailing. + _.debounce = function(func, wait, immediate) { + var timeout, args, context, timestamp, result; + + var later = function() { + var last = _.now() - timestamp; + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function() { + context = this; + args = arguments; + timestamp = _.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return _.partial(wrapper, func); + }; + + // Returns a negated version of the passed-in predicate. + _.negate = function(predicate) { + return function() { + return !predicate.apply(this, arguments); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var args = arguments; + var start = args.length - 1; + return function() { + var i = start; + var result = args[start].apply(this, arguments); + while (i--) result = args[i].call(this, result); + return result; + }; + }; + + // Returns a function that will only be executed on and after the Nth call. + _.after = function(times, func) { + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Returns a function that will only be executed up to (but not including) the Nth call. + _.before = function(times, func) { + var memo; + return function() { + if (--times > 0) { + memo = func.apply(this, arguments); + } + if (times <= 1) func = null; + return memo; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = _.partial(_.before, 2); + + // Object Functions + // ---------------- + + // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. + var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); + var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', + 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; + + function collectNonEnumProps(obj, keys) { + var nonEnumIdx = nonEnumerableProps.length; + var constructor = obj.constructor; + var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; + + // Constructor is a special case. + var prop = 'constructor'; + if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); + + while (nonEnumIdx--) { + prop = nonEnumerableProps[nonEnumIdx]; + if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { + keys.push(prop); + } + } + } + + // Retrieve the names of an object's own properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = function(obj) { + if (!_.isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve all the property names of an object. + _.allKeys = function(obj) { + if (!_.isObject(obj)) return []; + var keys = []; + for (var key in obj) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var values = Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[keys[i]]; + } + return values; + }; + + // Returns the results of applying the iteratee to each element of the object + // In contrast to _.map it returns an object + _.mapObject = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = _.keys(obj), + length = keys.length, + results = {}, + currentKey; + for (var index = 0; index < length; index++) { + currentKey = keys[index]; + results[currentKey] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var pairs = Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [keys[i], obj[keys[i]]]; + } + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.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; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = createAssigner(_.allKeys); + + // Assigns a given object with all the own properties in the passed-in object(s) + // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + _.extendOwn = _.assign = createAssigner(_.keys); + + // Returns the first key on an object that passes a predicate test + _.findKey = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = _.keys(obj), key; + for (var i = 0, length = keys.length; i < length; i++) { + key = keys[i]; + if (predicate(obj[key], key, obj)) return key; + } + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(object, oiteratee, context) { + var result = {}, obj = object, iteratee, keys; + if (obj == null) return result; + if (_.isFunction(oiteratee)) { + keys = _.allKeys(obj); + iteratee = optimizeCb(oiteratee, context); + } else { + keys = flatten(arguments, false, false, 1); + iteratee = function(value, key, obj) { return key in obj; }; + obj = Object(obj); + } + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; + var value = obj[key]; + if (iteratee(value, key, obj)) result[key] = value; + } + return result; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj, iteratee, context) { + if (_.isFunction(iteratee)) { + iteratee = _.negate(iteratee); + } else { + var keys = _.map(flatten(arguments, false, false, 1), String); + iteratee = function(value, key) { + return !_.contains(keys, key); + }; + } + return _.pick(obj, iteratee, context); + }; + + // Fill in a given object with default properties. + _.defaults = createAssigner(_.allKeys, true); + + // Creates an object that inherits from the given prototype object. + // If additional properties are provided then they will be added to the + // created object. + _.create = function(prototype, props) { + var result = baseCreate(prototype); + if (props) _.extendOwn(result, props); + return result; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + if (!_.isObject(obj)) return obj; + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Returns whether an object has a given set of `key:value` pairs. + _.isMatch = function(object, attrs) { + var keys = _.keys(attrs), length = keys.length; + if (object == null) return !length; + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (attrs[key] !== obj[key] || !(key in obj)) return false; + } + return true; + }; + + + // Internal recursive comparison function for `isEqual`. + var eq = function(a, b, aStack, bStack) { + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) return a !== 0 || 1 / a === 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className !== toString.call(b)) return false; + switch (className) { + // Strings, numbers, regular expressions, dates, and booleans are compared by value. + case '[object RegExp]': + // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return '' + a === '' + b; + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. + // Object(NaN) is equivalent to NaN + if (+a !== +a) return +b !== +b; + // An `egal` comparison is performed for other numeric values. + return +a === 0 ? 1 / +a === 1 / b : +a === +b; + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a === +b; + } + + var areArrays = className === '[object Array]'; + if (!areArrays) { + if (typeof a != 'object' || typeof b != 'object') return false; + + // Objects with different constructors are not equivalent, but `Object`s or `Array`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && + _.isFunction(bCtor) && bCtor instanceof bCtor) + && ('constructor' in a && 'constructor' in b)) { + return false; + } + } + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + + // Initializing stack of traversed objects. + // It's done here since we only need them for objects and arrays comparison. + aStack = aStack || []; + bStack = bStack || []; + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] === a) return bStack[length] === b; + } + + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + + // Recursively compare objects and arrays. + if (areArrays) { + // Compare array lengths to determine if a deep comparison is necessary. + length = a.length; + if (length !== b.length) return false; + // Deep compare the contents, ignoring non-numeric properties. + while (length--) { + if (!eq(a[length], b[length], aStack, bStack)) return false; + } + } else { + // Deep compare objects. + var keys = _.keys(a), key; + length = keys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (_.keys(b).length !== length) return false; + while (length--) { + // Deep compare each member + key = keys[length]; + if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return true; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + return eq(a, b); + }; + + // Is a given array, string, or object empty? + // An "empty" object has no enumerable own-properties. + _.isEmpty = function(obj) { + if (obj == null) return true; + if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; + return _.keys(obj).length === 0; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) === '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. + _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) === '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE < 9), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return _.has(obj, 'callee'); + }; + } + + // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, + // IE 11 (#1621), and in Safari 8 (#1929). + if (typeof /./ != 'function' && typeof Int8Array != 'object') { + _.isFunction = function(obj) { + return typeof obj == 'function' || false; + }; + } + + // Is a given object a finite number? + _.isFinite = function(obj) { + return isFinite(obj) && !isNaN(parseFloat(obj)); + }; + + // Is the given value `NaN`? (NaN is the only number which does not equal itself). + _.isNaN = function(obj) { + return _.isNumber(obj) && obj !== +obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Shortcut function for checking if an object has a given property directly + // on itself (in other words, not on a prototype). + _.has = function(obj, key) { + return obj != null && hasOwnProperty.call(obj, key); + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iteratees. + _.identity = function(value) { + return value; + }; + + // Predicate-generating functions. Often useful outside of Underscore. + _.constant = function(value) { + return function() { + return value; + }; + }; + + _.noop = function(){}; + + _.property = property; + + // Generates a function for a given object that returns a given property. + _.propertyOf = function(obj) { + return obj == null ? function(){} : function(key) { + return obj[key]; + }; + }; + + // Returns a predicate for checking whether an object has a given set of + // `key:value` pairs. + _.matcher = _.matches = function(attrs) { + attrs = _.extendOwn({}, attrs); + return function(obj) { + return _.isMatch(obj, attrs); + }; + }; + + // Run a function **n** times. + _.times = function(n, iteratee, context) { + var accum = Array(Math.max(0, n)); + iteratee = optimizeCb(iteratee, context, 1); + for (var i = 0; i < n; i++) accum[i] = iteratee(i); + return accum; + }; + + // Return a random integer between min and max (inclusive). + _.random = function(min, max) { + if (max == null) { + max = min; + min = 0; + } + return min + Math.floor(Math.random() * (max - min + 1)); + }; + + // A (possibly faster) way to get the current timestamp as an integer. + _.now = Date.now || function() { + return new Date().getTime(); + }; + + // List of HTML entities for escaping. + var escapeMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + var unescapeMap = _.invert(escapeMap); + + // Functions for escaping and unescaping strings to/from HTML interpolation. + var createEscaper = function(map) { + var escaper = function(match) { + return map[match]; + }; + // Regexes for identifying a key that needs to be escaped + var source = '(?:' + _.keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function(string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + }; + _.escape = createEscaper(escapeMap); + _.unescape = createEscaper(unescapeMap); + + // If the value of the named `property` is a function then invoke it with the + // `object` as context; otherwise, return it. + _.result = function(object, property, fallback) { + var value = object == null ? void 0 : object[property]; + if (value === void 0) { + value = fallback; + } + return _.isFunction(value) ? value.call(object) : value; + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = ++idCounter + ''; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\u2028|\u2029/g; + + var escapeChar = function(match) { + return '\\' + escapes[match]; + }; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + // NB: `oldSettings` only exists for backwards compatibility. + _.template = function(text, settings, oldSettings) { + if (!settings && oldSettings) settings = oldSettings; + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset).replace(escaper, escapeChar); + index = offset + match.length; + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } else if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } else if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + + // Adobe VMs need the match returned to produce the correct offest. + return match; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + 'return __p;\n'; + + try { + var render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled source as a convenience for precompilation. + var argument = settings.variable || 'obj'; + template.source = 'function(' + argument + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function. Start chaining a wrapped Underscore object. + _.chain = function(obj) { + var instance = _(obj); + instance._chain = true; + return instance; + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(instance, obj) { + return instance._chain ? _(obj).chain() : obj; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + _.each(_.functions(obj), function(name) { + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result(this, func.apply(_, args)); + }; + }); + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; + return result(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + _.each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result(this, method.apply(this._wrapped, arguments)); + }; + }); + + // Extracts the result from a wrapped and chained object. + _.prototype.value = function() { + return this._wrapped; + }; + + // Provide unwrapping proxy for some methods used in engine operations + // such as arithmetic and JSON stringification. + _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; + + _.prototype.toString = function() { + return '' + this._wrapped; + }; + + // AMD registration happens at the end for compatibility with AMD loaders + // that may not enforce next-turn semantics on modules. Even though general + // practice for AMD registration is to be anonymous, underscore registers + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { + return _; + }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } +}.call(this)); + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(41).Promise; + +Promise._continueWhile = function (predicate, asyncFunction) { + if (predicate()) { + return asyncFunction().then(function () { + return Promise._continueWhile(predicate, asyncFunction); + }); + } + return Promise.resolve(); +}; + +module.exports = Promise; + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var request = __webpack_require__(7); +var debug = __webpack_require__(5)('leancloud:request'); +var md5 = __webpack_require__(43); +var Promise = __webpack_require__(1); +var Cache = __webpack_require__(9); +var AVError = __webpack_require__(3); +var AV = __webpack_require__(6); +var _ = __webpack_require__(0); + +var _require = __webpack_require__(4), + getSessionToken = _require.getSessionToken; + +var getServerURLPromise = void 0; + +// 服务器请求的节点 host +var API_HOST = { + cn: 'https://api.leancloud.cn', + us: 'https://us-api.leancloud.cn' +}; + +// 计算 X-LC-Sign 的签名方法 +var sign = function sign(key, isMasterKey) { + var now = new Date().getTime(); + var signature = md5(now + key); + if (isMasterKey) { + return signature + ',' + now + ',master'; + } + return signature + ',' + now; +}; + +var requestsCount = 0; + +var ajax = function ajax(method, resourceUrl, data) { + var headers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var onprogress = arguments[4]; + + var count = requestsCount++; + + debug('request(' + count + ')', method, resourceUrl, data, headers); + + return new Promise(function (resolve, reject) { + var req = request(method, resourceUrl).set(headers).send(data); + if (onprogress) { + req.on('progress', onprogress); + } + req.end(function (err, res) { + if (res) { + debug('response(' + count + ')', res.status, res.body || res.text, res.header); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + return resolve(res.body); + }); + }); +}; + +var setAppKey = function setAppKey(headers, signKey) { + if (signKey) { + headers['X-LC-Sign'] = sign(AV.applicationKey); + } else { + headers['X-LC-Key'] = AV.applicationKey; + } +}; + +var setHeaders = function setHeaders() { + var authOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var signKey = arguments[1]; + + var headers = { + 'X-LC-Id': AV.applicationId, + 'Content-Type': 'application/json;charset=UTF-8' + }; + var useMasterKey = false; + if (typeof authOptions.useMasterKey === 'boolean') { + useMasterKey = authOptions.useMasterKey; + } else if (typeof AV._useMasterKey === 'boolean') { + useMasterKey = AV._useMasterKey; + } + if (useMasterKey) { + if (AV.masterKey) { + if (signKey) { + headers['X-LC-Sign'] = sign(AV.masterKey, true); + } else { + headers['X-LC-Key'] = AV.masterKey + ',master'; + } + } else { + console.warn('masterKey is not set, fall back to use appKey'); + setAppKey(headers, signKey); + } + } else { + setAppKey(headers, signKey); + } + if (AV.hookKey) { + headers['X-LC-Hook-Key'] = AV.hookKey; + } + if (AV._config.applicationProduction !== null) { + headers['X-LC-Prod'] = String(AV._config.applicationProduction); + } + headers[ false ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent; + + return Promise.resolve().then(function () { + // Pass the session token + var sessionToken = getSessionToken(authOptions); + if (sessionToken) { + headers['X-LC-Session'] = sessionToken; + } else if (!AV._config.disableCurrentUser) { + return AV.User.currentAsync().then(function (currentUser) { + if (currentUser && currentUser._sessionToken) { + headers['X-LC-Session'] = currentUser._sessionToken; + } + return headers; + }); + } + return headers; + }); +}; + +var createApiUrl = function createApiUrl(route, className, objectId, method, dataObject) { + // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉 + if (AV.serverURL) { + AV._config.APIServerURL = AV.serverURL; + console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.'); + } + + var apiURL = AV._config.APIServerURL || API_HOST.cn; + + if (apiURL.charAt(apiURL.length - 1) !== '/') { + apiURL += '/'; + } + apiURL += '1.1/' + route; + if (className) { + apiURL += '/' + className; + } + if (objectId) { + apiURL += '/' + objectId; + } + if ((route === 'users' || route === 'classes') && dataObject) { + apiURL += '?'; + if (dataObject._fetchWhenSave) { + delete dataObject._fetchWhenSave; + apiURL += '&new=true'; + } + if (dataObject._where) { + apiURL += '&where=' + encodeURIComponent(JSON.stringify(dataObject._where)); + delete dataObject._where; + } + } + + if (method.toLowerCase() === 'get') { + if (apiURL.indexOf('?') === -1) { + apiURL += '?'; + } + for (var k in dataObject) { + if (_typeof(dataObject[k]) === 'object') { + dataObject[k] = JSON.stringify(dataObject[k]); + } + apiURL += '&' + k + '=' + encodeURIComponent(dataObject[k]); + } + } + + return apiURL; +}; + +var cacheServerURL = function cacheServerURL(serverURL, ttl) { + if (typeof ttl !== 'number') { + ttl = 3600; + } + return Cache.setAsync('APIServerURL', serverURL, ttl * 1000); +}; + +// handle AV._request Error +var handleError = function handleError(error) { + return new Promise(function (resolve, reject) { + /** + When API request need to redirect to the right location, + can't use browser redirect by http status 307, as the reason of CORS, + so API server response http status 410 and the param "location" for this case. + */ + if (error.statusCode === 410) { + cacheServerURL(error.response.api_server, error.response.ttl).then(function () { + resolve(error.response.location); + }).catch(reject); + } else { + var errorJSON = { + code: error.code || -1, + error: error.message || error.responseText + }; + if (error.response && error.response.code) { + errorJSON = error.response; + } else if (error.responseText) { + try { + errorJSON = JSON.parse(error.responseText); + } catch (e) { + // If we fail to parse the error text, that's okay. + } + } + + // Transform the error into an instance of AVError by trying to parse + // the error string as JSON. + reject(new AVError(errorJSON.code, errorJSON.error)); + } + }); +}; + +var setServerUrl = function setServerUrl(serverURL) { + AV._config.APIServerURL = 'https://' + serverURL; + + // 根据新 URL 重新设置区域 + var newRegion = _.findKey(API_HOST, function (item) { + return item === AV._config.APIServerURL; + }); + if (newRegion) { + AV._config.region = newRegion; + } +}; + +var refreshServerUrlByRouter = function refreshServerUrlByRouter() { + var url = 'https://app-router.leancloud.cn/1/route?appId=' + AV.applicationId; + return ajax('get', url).then(function (servers) { + if (servers.api_server) { + setServerUrl(servers.api_server); + return cacheServerURL(servers.api_server, servers.ttl); + } + }, function (error) { + // bypass all non-4XX errors + if (error.statusCode >= 400 && error.statusCode < 500) { + throw error; + } + }); +}; + +var setServerUrlByRegion = function setServerUrlByRegion() { + var region = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'cn'; + + getServerURLPromise = new Promise(function (resolve, reject) { + // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router + if (AV._config.APIServerURL) { + resolve(); + return; + } + // if not china server region, do not use router + if (region === 'cn') { + return Cache.getAsync('APIServerURL').then(function (serverURL) { + if (serverURL) { + setServerUrl(serverURL); + } else { + return refreshServerUrlByRouter(); + } + }).then(function () { + resolve(); + }).catch(function (error) { + reject(error); + }); + } else { + AV._config.region = region; + AV._config.APIServerURL = API_HOST[region]; + resolve(); + } + }); +}; + +/** + * route is classes, users, login, etc. + * objectId is null if there is no associated objectId. + * method is the http method for the REST API. + * dataObject is the payload as an object, or null if there is none. + * @ignore + */ +var AVRequest = function AVRequest(route, className, objectId, method) { + var dataObject = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + var authOptions = arguments[5]; + + if (!AV.applicationId) { + throw new Error('You must specify your applicationId using AV.init()'); + } + + if (!AV.applicationKey && !AV.masterKey) { + throw new Error('You must specify a AppKey using AV.init()'); + } + + if (!getServerURLPromise) { + return Promise.reject(new Error('Not initialized')); + } + return getServerURLPromise.then(function () { + var apiURL = createApiUrl(route, className, objectId, method, dataObject); + return setHeaders(authOptions, route !== 'bigquery').then(function (headers) { + return ajax(method, apiURL, dataObject, headers).then(null, function (res) { + return handleError(res).then(function (location) { + return ajax(method, location, dataObject, headers); + }); + }); + }); + }); +}; + +module.exports = { + ajax: ajax, + request: AVRequest, + setServerUrlByRegion: setServerUrlByRegion +}; + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +/** + * @class AV.Error + */ + +function AVError(code, message) { + var error = new Error(message); + error.code = code; + return error; +} + +_.extend(AVError, /** @lends AV.Error */{ + /** + * Error code indicating some error other than those enumerated here. + * @constant + */ + OTHER_CAUSE: -1, + + /** + * Error code indicating that something has gone wrong with the server. + * If you get this error code, it is AV's fault. Contact us at + * https://avoscloud.com/help + * @constant + */ + INTERNAL_SERVER_ERROR: 1, + + /** + * Error code indicating the connection to the AV servers failed. + * @constant + */ + CONNECTION_FAILED: 100, + + /** + * Error code indicating the specified object doesn't exist. + * @constant + */ + OBJECT_NOT_FOUND: 101, + + /** + * Error code indicating you tried to query with a datatype that doesn't + * support it, like exact matching an array or object. + * @constant + */ + INVALID_QUERY: 102, + + /** + * Error code indicating a missing or invalid classname. Classnames are + * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the + * only valid characters. + * @constant + */ + INVALID_CLASS_NAME: 103, + + /** + * Error code indicating an unspecified object id. + * @constant + */ + MISSING_OBJECT_ID: 104, + + /** + * Error code indicating an invalid key name. Keys are case-sensitive. They + * must start with a letter, and a-zA-Z0-9_ are the only valid characters. + * @constant + */ + INVALID_KEY_NAME: 105, + + /** + * Error code indicating a malformed pointer. You should not see this unless + * you have been mucking about changing internal AV code. + * @constant + */ + INVALID_POINTER: 106, + + /** + * Error code indicating that badly formed JSON was received upstream. This + * either indicates you have done something unusual with modifying how + * things encode to JSON, or the network is failing badly. + * @constant + */ + INVALID_JSON: 107, + + /** + * Error code indicating that the feature you tried to access is only + * available internally for testing purposes. + * @constant + */ + COMMAND_UNAVAILABLE: 108, + + /** + * You must call AV.initialize before using the AV library. + * @constant + */ + NOT_INITIALIZED: 109, + + /** + * Error code indicating that a field was set to an inconsistent type. + * @constant + */ + INCORRECT_TYPE: 111, + + /** + * Error code indicating an invalid channel name. A channel name is either + * an empty string (the broadcast channel) or contains only a-zA-Z0-9_ + * characters. + * @constant + */ + INVALID_CHANNEL_NAME: 112, + + /** + * Error code indicating that push is misconfigured. + * @constant + */ + PUSH_MISCONFIGURED: 115, + + /** + * Error code indicating that the object is too large. + * @constant + */ + OBJECT_TOO_LARGE: 116, + + /** + * Error code indicating that the operation isn't allowed for clients. + * @constant + */ + OPERATION_FORBIDDEN: 119, + + /** + * Error code indicating the result was not found in the cache. + * @constant + */ + CACHE_MISS: 120, + + /** + * Error code indicating that an invalid key was used in a nested + * JSONObject. + * @constant + */ + INVALID_NESTED_KEY: 121, + + /** + * Error code indicating that an invalid filename was used for AVFile. + * A valid file name contains only a-zA-Z0-9_. characters and is between 1 + * and 128 characters. + * @constant + */ + INVALID_FILE_NAME: 122, + + /** + * Error code indicating an invalid ACL was provided. + * @constant + */ + INVALID_ACL: 123, + + /** + * Error code indicating that the request timed out on the server. Typically + * this indicates that the request is too expensive to run. + * @constant + */ + TIMEOUT: 124, + + /** + * Error code indicating that the email address was invalid. + * @constant + */ + INVALID_EMAIL_ADDRESS: 125, + + /** + * Error code indicating a missing content type. + * @constant + */ + MISSING_CONTENT_TYPE: 126, + + /** + * Error code indicating a missing content length. + * @constant + */ + MISSING_CONTENT_LENGTH: 127, + + /** + * Error code indicating an invalid content length. + * @constant + */ + INVALID_CONTENT_LENGTH: 128, + + /** + * Error code indicating a file that was too large. + * @constant + */ + FILE_TOO_LARGE: 129, + + /** + * Error code indicating an error saving a file. + * @constant + */ + FILE_SAVE_ERROR: 130, + + /** + * Error code indicating an error deleting a file. + * @constant + */ + FILE_DELETE_ERROR: 153, + + /** + * Error code indicating that a unique field was given a value that is + * already taken. + * @constant + */ + DUPLICATE_VALUE: 137, + + /** + * Error code indicating that a role's name is invalid. + * @constant + */ + INVALID_ROLE_NAME: 139, + + /** + * Error code indicating that an application quota was exceeded. Upgrade to + * resolve. + * @constant + */ + EXCEEDED_QUOTA: 140, + + /** + * Error code indicating that a Cloud Code script failed. + * @constant + */ + SCRIPT_FAILED: 141, + + /** + * Error code indicating that a Cloud Code validation failed. + * @constant + */ + VALIDATION_ERROR: 142, + + /** + * Error code indicating that invalid image data was provided. + * @constant + */ + INVALID_IMAGE_DATA: 150, + + /** + * Error code indicating an unsaved file. + * @constant + */ + UNSAVED_FILE_ERROR: 151, + + /** + * Error code indicating an invalid push time. + */ + INVALID_PUSH_TIME_ERROR: 152, + + /** + * Error code indicating that the username is missing or empty. + * @constant + */ + USERNAME_MISSING: 200, + + /** + * Error code indicating that the password is missing or empty. + * @constant + */ + PASSWORD_MISSING: 201, + + /** + * Error code indicating that the username has already been taken. + * @constant + */ + USERNAME_TAKEN: 202, + + /** + * Error code indicating that the email has already been taken. + * @constant + */ + EMAIL_TAKEN: 203, + + /** + * Error code indicating that the email is missing, but must be specified. + * @constant + */ + EMAIL_MISSING: 204, + + /** + * Error code indicating that a user with the specified email was not found. + * @constant + */ + EMAIL_NOT_FOUND: 205, + + /** + * Error code indicating that a user object without a valid session could + * not be altered. + * @constant + */ + SESSION_MISSING: 206, + + /** + * Error code indicating that a user can only be created through signup. + * @constant + */ + MUST_CREATE_USER_THROUGH_SIGNUP: 207, + + /** + * Error code indicating that an an account being linked is already linked + * to another user. + * @constant + */ + ACCOUNT_ALREADY_LINKED: 208, + + /** + * Error code indicating that a user cannot be linked to an account because + * that account's id could not be found. + * @constant + */ + LINKED_ID_MISSING: 250, + + /** + * Error code indicating that a user with a linked (e.g. Facebook) account + * has an invalid session. + * @constant + */ + INVALID_LINKED_SESSION: 251, + + /** + * Error code indicating that a service being linked (e.g. Facebook or + * Twitter) is unsupported. + * @constant + */ + UNSUPPORTED_SERVICE: 252, + /** + * Error code indicating a real error code is unavailable because + * we had to use an XDomainRequest object to allow CORS requests in + * Internet Explorer, which strips the body from HTTP responses that have + * a non-2XX status code. + * @constant + */ + X_DOMAIN_REQUEST: 602 +}); + +module.exports = AVError; + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +// Helper function to check null or undefined. +var isNullOrUndefined = function isNullOrUndefined(x) { + return _.isNull(x) || _.isUndefined(x); +}; + +var ensureArray = function ensureArray(target) { + if (_.isArray(target)) { + return target; + } + if (target === undefined || target === null) { + return []; + } + return [target]; +}; + +var getSessionToken = function getSessionToken(authOptions) { + if (authOptions.sessionToken) { + return authOptions.sessionToken; + } + if (authOptions.user && typeof authOptions.user.getSessionToken === 'function') { + return authOptions.user.getSessionToken(); + } +}; + +var tap = function tap(interceptor) { + return function (value) { + return interceptor(value), value; + }; +}; + +module.exports = { + isNullOrUndefined: isNullOrUndefined, + ensureArray: ensureArray, + getSessionToken: getSessionToken, + tap: tap +}; + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = __webpack_require__(40); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var _ = __webpack_require__(0); +var userAgent = __webpack_require__(32); + +var _require = __webpack_require__(4), + isNullOrUndefined = _require.isNullOrUndefined; + +var AV = global.AV || {}; + +// All internal configuration items +AV._config = AV._config || {}; +var AVConfig = AV._config; + +_.extend(AVConfig, { + + // 服务器节点地区,默认中国大陆 + region: 'cn', + + // 服务器的 URL,默认初始化时被设置为大陆节点地址 + APIServerURL: AVConfig.APIServerURL || '', + + // 禁用 currentUser,通常用于多用户环境 + disableCurrentUser: false, + + // Internal config can modifie the UserAgent + userAgent: userAgent, + + // set production environment or test environment + // 1: production environment, 0: test environment, null: default environment + applicationProduction: null +}); + +/** + * Contains all AV API classes and functions. + * @namespace AV + */ + +// Helpers +// ------- + +// Shared empty constructor function to aid in prototype-chain creation. +var EmptyConstructor = function EmptyConstructor() {}; + +// Helper function to correctly set up the prototype chain, for subclasses. +// Similar to `goog.inherits`, but uses a hash of prototype properties and +// class properties to be extended. +var inherits = function inherits(parent, protoProps, staticProps) { + var child; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent's constructor. + if (protoProps && protoProps.hasOwnProperty('constructor')) { + child = protoProps.constructor; + } else { + /** @ignore */ + child = function child() { + parent.apply(this, arguments); + }; + } + + // Inherit class (static) properties from parent. + _.extend(child, parent); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + EmptyConstructor.prototype = parent.prototype; + child.prototype = new EmptyConstructor(); + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) { + _.extend(child.prototype, protoProps); + } + + // Add static properties to the constructor function, if supplied. + if (staticProps) { + _.extend(child, staticProps); + } + + // Correctly set child's `prototype.constructor`. + child.prototype.constructor = child; + + // Set a convenience property in case the parent's prototype is + // needed later. + child.__super__ = parent.prototype; + + return child; +}; + +/** + * Call this method to set production environment variable. + * @function AV.setProduction + * @param {Boolean} production True is production environment,and + * it's true by default. + */ +AV.setProduction = function (production) { + if (!isNullOrUndefined(production)) { + AVConfig.applicationProduction = production ? 1 : 0; + } else { + // change to default value + AVConfig.applicationProduction = null; + } +}; + +/** + * Returns prefix for localStorage keys used by this instance of AV. + * @param {String} path The relative suffix to append to it. + * null or undefined is treated as the empty string. + * @return {String} The full key name. + * @private + */ +AV._getAVPath = function (path) { + if (!AV.applicationId) { + throw new Error("You need to call AV.initialize before using AV."); + } + if (!path) { + path = ""; + } + if (!_.isString(path)) { + throw new Error("Tried to get a localStorage path that wasn't a String."); + } + if (path[0] === "/") { + path = path.substring(1); + } + return "AV/" + AV.applicationId + "/" + path; +}; + +/** + * Returns the unique string for this app on this machine. + * Gets reset when localStorage is cleared. + * @private + */ +AV._installationId = null; +AV._getInstallationId = function () { + // See if it's cached in RAM. + if (AV._installationId) { + return AV.Promise.resolve(AV._installationId); + } + + // Try to get it from localStorage. + var path = AV._getAVPath("installationId"); + return AV.localStorage.getItemAsync(path).then(function (_installationId) { + AV._installationId = _installationId; + if (!AV._installationId) { + // It wasn't in localStorage, so create a new one. + var hexOctet = function hexOctet() { + return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + }; + AV._installationId = hexOctet() + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + hexOctet() + hexOctet(); + return AV.localStorage.setItemAsync(path, AV._installationId); + } else { + return _installationId; + } + }); +}; + +AV._parseDate = function (iso8601) { + var regexp = new RegExp("^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})" + "T" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})" + "(.([0-9]+))?" + "Z$"); + var match = regexp.exec(iso8601); + if (!match) { + return null; + } + + var year = match[1] || 0; + var month = (match[2] || 1) - 1; + var day = match[3] || 0; + var hour = match[4] || 0; + var minute = match[5] || 0; + var second = match[6] || 0; + var milli = match[8] || 0; + + return new Date(Date.UTC(year, month, day, hour, minute, second, milli)); +}; + +// A self-propagating extend function. +AV._extend = function (protoProps, classProps) { + var child = inherits(this, protoProps, classProps); + child.extend = this.extend; + return child; +}; + +// Helper function to get a value from a Backbone object as a property +// or as a function. +AV._getValue = function (object, prop) { + if (!(object && object[prop])) { + return null; + } + return _.isFunction(object[prop]) ? object[prop]() : object[prop]; +}; + +/** + * Converts a value in a AV Object into the appropriate representation. + * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object) + * if seenObjects is falsey. Otherwise any AV.Objects not in + * seenObjects will be fully embedded rather than encoded + * as a pointer. This array will be used to prevent going into an infinite + * loop because we have circular references. If + * is set, then none of the AV Objects that are serialized can be dirty. + * @private + */ +AV._encode = function (value, seenObjects, disallowObjects) { + if (value instanceof AV.Object) { + if (disallowObjects) { + throw new Error("AV.Objects not allowed here"); + } + if (!seenObjects || _.include(seenObjects, value) || !value._hasData) { + return value._toPointer(); + } + if (!value.dirty()) { + seenObjects = seenObjects.concat(value); + return AV._encode(value._toFullJSON(seenObjects), seenObjects, disallowObjects); + } + throw new Error("Tried to save an object with a pointer to a new, unsaved object."); + } + if (value instanceof AV.ACL) { + return value.toJSON(); + } + if (_.isDate(value)) { + return { "__type": "Date", "iso": value.toJSON() }; + } + if (value instanceof AV.GeoPoint) { + return value.toJSON(); + } + if (_.isArray(value)) { + return _.map(value, function (x) { + return AV._encode(x, seenObjects, disallowObjects); + }); + } + if (_.isRegExp(value)) { + return value.source; + } + if (value instanceof AV.Relation) { + return value.toJSON(); + } + if (value instanceof AV.Op) { + return value.toJSON(); + } + if (value instanceof AV.File) { + if (!value.url() && !value.id) { + throw new Error("Tried to save an object containing an unsaved file."); + } + return value._toFullJSON(); + } + if (_.isObject(value)) { + return _.mapObject(value, function (v, k) { + return AV._encode(v, seenObjects, disallowObjects); + }); + } + return value; +}; + +/** + * The inverse function of AV._encode. + * @private + */ +AV._decode = function (value, key) { + if (!_.isObject(value) || _.isDate(value)) { + return value; + } + if (_.isArray(value)) { + return _.map(value, function (v) { + return AV._decode(v); + }); + } + if (value instanceof AV.Object) { + return value; + } + if (value instanceof AV.File) { + return value; + } + if (value instanceof AV.Op) { + return value; + } + if (value instanceof AV.GeoPoint) { + return value; + } + if (value instanceof AV.ACL) { + return value; + } + if (key === 'ACL') { + return new AV.ACL(value); + } + if (value.__op) { + return AV.Op._decode(value); + } + var className; + if (value.__type === "Pointer") { + className = value.className; + var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + if (Object.keys(value).length > 3) { + var v = _.clone(value); + delete v.__type; + delete v.className; + pointer._finishFetch(v, true); + } else { + pointer._finishFetch({ objectId: value.objectId }, false); + } + return pointer; + } + if (value.__type === "Object") { + // It's an Object included in a query result. + className = value.className; + var _v = _.clone(value); + delete _v.__type; + delete _v.className; + var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + object._finishFetch(_v, true); + return object; + } + if (value.__type === "Date") { + return AV._parseDate(value.iso); + } + if (value.__type === "GeoPoint") { + return new AV.GeoPoint({ + latitude: value.latitude, + longitude: value.longitude + }); + } + if (value.__type === "Relation") { + if (!key) throw new Error('key missing decoding a Relation'); + var relation = new AV.Relation(null, key); + relation.targetClassName = value.className; + return relation; + } + if (value.__type === 'File') { + var file = new AV.File(value.name); + var _v2 = _.clone(value); + delete _v2.__type; + file._finishFetch(_v2); + return file; + } + return _.mapObject(value, AV._decode); +}; + +AV._encodeObjectOrArray = function (value) { + var encodeAVObject = function encodeAVObject(object) { + if (object && object._toFullJSON) { + object = object._toFullJSON([]); + } + + return _.mapObject(object, function (value) { + return AV._encode(value, []); + }); + }; + + if (_.isArray(value)) { + return value.map(function (object) { + return encodeAVObject(object); + }); + } else { + return encodeAVObject(value); + } +}; + +AV._arrayEach = _.each; + +/** + * Does a deep traversal of every item in object, calling func on every one. + * @param {Object} object The object or array to traverse deeply. + * @param {Function} func The function to call for every item. It will + * be passed the item as an argument. If it returns a truthy value, that + * value will replace the item in its parent container. + * @returns {} the result of calling func on the top-level object itself. + * @private + */ +AV._traverse = function (object, func, seen) { + if (object instanceof AV.Object) { + seen = seen || []; + if (_.indexOf(seen, object) >= 0) { + // We've already visited this object in this call. + return; + } + seen.push(object); + AV._traverse(object.attributes, func, seen); + return func(object); + } + if (object instanceof AV.Relation || object instanceof AV.File) { + // Nothing needs to be done, but we don't want to recurse into the + // object's parent infinitely, so we catch this case. + return func(object); + } + if (_.isArray(object)) { + _.each(object, function (child, index) { + var newChild = AV._traverse(child, func, seen); + if (newChild) { + object[index] = newChild; + } + }); + return func(object); + } + if (_.isObject(object)) { + AV._each(object, function (child, key) { + var newChild = AV._traverse(child, func, seen); + if (newChild) { + object[key] = newChild; + } + }); + return func(object); + } + return func(object); +}; + +/** + * This is like _.each, except: + * * it doesn't work for so-called array-like objects, + * * it does work for dictionaries with a "length" attribute. + * @private + */ +AV._objectEach = AV._each = function (obj, callback) { + if (_.isObject(obj)) { + _.each(_.keys(obj), function (key) { + callback(obj[key], key); + }); + } else { + _.each(obj, callback); + } +}; + +module.exports = AV; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(13))) + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Root reference for iframes. + */ + +var root; +if (typeof window !== 'undefined') { // Browser window + root = window; +} else if (typeof self !== 'undefined') { // Web Worker + root = self; +} else { // Other environments + console.warn("Using browser-only version of superagent in non-browser environment"); + root = this; +} + +var Emitter = __webpack_require__(38); +var RequestBase = __webpack_require__(46); +var isObject = __webpack_require__(8); +var isFunction = __webpack_require__(45); +var ResponseBase = __webpack_require__(47); +var shouldRetry = __webpack_require__(48); + +/** + * Noop. + */ + +function noop(){}; + +/** + * Expose `request`. + */ + +var request = exports = module.exports = function(method, url) { + // callback + if ('function' == typeof url) { + return new exports.Request('GET', method).end(url); + } + + // url first + if (1 == arguments.length) { + return new exports.Request('GET', method); + } + + return new exports.Request(method, url); +} + +exports.Request = Request; + +/** + * Determine XHR. + */ + +request.getXHR = function () { + if (root.XMLHttpRequest + && (!root.location || 'file:' != root.location.protocol + || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} + } + throw Error("Browser-only verison of superagent could not find XHR"); +}; + +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + +var trim = ''.trim + ? function(s) { return s.trim(); } + : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; + +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + for (var key in obj) { + pushEncodedKeyValuePair(pairs, key, obj[key]); + } + return pairs.join('&'); +} + +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + +function pushEncodedKeyValuePair(pairs, key, val) { + if (val != null) { + if (Array.isArray(val)) { + val.forEach(function(v) { + pushEncodedKeyValuePair(pairs, key, v); + }); + } else if (isObject(val)) { + for(var subkey in val) { + pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); + } + } else { + pairs.push(encodeURIComponent(key) + + '=' + encodeURIComponent(val)); + } + } else if (val === null) { + pairs.push(encodeURIComponent(key)); + } +} + +/** + * Expose serialization method. + */ + + request.serializeObject = serialize; + + /** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var pair; + var pos; + + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos == -1) { + obj[decodeURIComponent(pair)] = ''; + } else { + obj[decodeURIComponent(pair.slice(0, pos))] = + decodeURIComponent(pair.slice(pos + 1)); + } + } + + return obj; +} + +/** + * Expose parser. + */ + +request.parseString = parseString; + +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'application/xml', + urlencoded: 'application/x-www-form-urlencoded', + 'form': 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + + request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': JSON.stringify + }; + + /** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; + +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + + lines.pop(); // trailing CRLF + + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + + return fields; +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + return /[\/+]json\b/.test(mime); +} + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + +function Response(req) { + this.req = req; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') + ? this.xhr.responseText + : null; + this.statusText = this.req.xhr.statusText; + var status = this.xhr.status; + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + this._setStatusProperties(status); + this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + + if (null === this.text && req._responseType) { + this.body = this.xhr.response; + } else { + this.body = this.req.method != 'HEAD' + ? this._parseBody(this.text ? this.text : this.xhr.response) + : null; + } +} + +ResponseBase(Response.prototype); + +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function(str){ + var parse = request.parse[this.type]; + if(this.req._parser) { + return this.req._parser(this, str); + } + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && str && (str.length || str instanceof Object) + ? parse(str) + : null; +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function(){ + var req = this.req; + var method = req.method; + var url = req.url; + + var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + + return err; +}; + +/** + * Expose `Response`. + */ + +request.Response = Response; + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + var self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', function(){ + var err = null; + var res = null; + + try { + res = new Response(self); + } catch(e) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = e; + // issue #675: return the raw response if the response parsing fails + if (self.xhr) { + // ie9 doesn't have 'response' property + err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + err.status = self.xhr.status ? self.xhr.status : null; + err.statusCode = err.status; // backwards-compat only + } else { + err.rawResponse = null; + err.status = null; + } + + return self.callback(err); + } + + self.emit('response', res); + + var new_err; + try { + if (!self._isResponseOK(res)) { + new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + } + } catch(e) { + new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android + } + + // #1000 don't catch errors from the callback to avoid double calling it + if (new_err) { + self.callback(new_err, res); + } else { + self.callback(null, res); + } + }); +} + +/** + * Mixin `Emitter` and `RequestBase`. + */ + +Emitter(Request.prototype); +RequestBase(Request.prototype); + +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function(type){ + this.set('Content-Type', request.types[type] || type); + return this; +}; + +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function(type){ + this.set('Accept', request.types[type] || type); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} [pass] optional in case of using 'bearer' as type + * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function(user, pass, options){ + if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options + options = pass; + } + if (!options) { + options = { + type: 'function' === typeof btoa ? 'basic' : 'auto', + } + } + + switch (options.type) { + case 'basic': + this.set('Authorization', 'Basic ' + btoa(user + ':' + pass)); + break; + + case 'auto': + this.username = user; + this.password = pass; + break; + + case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' }) + this.set('Authorization', 'Bearer ' + user); + break; + } + return this; +}; + +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.query = function(val){ + if ('string' != typeof val) val = serialize(val); + if (val) this._query.push(val); + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function(field, file, options){ + if (file) { + if (this._data) { + throw Error("superagent can't mix .send() and .attach()"); + } + + this._getFormData().append(field, file, options || file.name); + } + return this; +}; + +Request.prototype._getFormData = function(){ + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function(err, res){ + // console.log(this._retries, this._maxRetries) + if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) { + return this._retry(); + } + + var fn = this._callback; + this.clearTimeout(); + + if (err) { + if (this._maxRetries) err.retries = this._retries - 1; + this.emit('error', err); + } + + fn(err, res); +}; + +/** + * Invoke callback with x-domain error. + * + * @api private + */ + +Request.prototype.crossDomainError = function(){ + var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + err.crossDomain = true; + + err.status = this.status; + err.method = this.method; + err.url = this.url; + + this.callback(err); +}; + +// This only warns, because the request is still likely to work +Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){ + console.warn("This is not supported in browser version of superagent"); + return this; +}; + +// This throws, because it can't send/receive data as expected +Request.prototype.pipe = Request.prototype.write = function(){ + throw Error("Streaming is not supported in browser version of superagent"); +}; + +/** + * Compose querystring to append to req.url + * + * @api private + */ + +Request.prototype._appendQueryString = function(){ + var query = this._query.join('&'); + if (query) { + this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query; + } + + if (this._sort) { + var index = this.url.indexOf('?'); + if (index >= 0) { + var queryArr = this.url.substring(index + 1).split('&'); + if (isFunction(this._sort)) { + queryArr.sort(this._sort); + } else { + queryArr.sort(); + } + this.url = this.url.substring(0, index) + '?' + queryArr.join('&'); + } + } +}; + +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +Request.prototype._isHost = function _isHost(obj) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; +} + +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype.end = function(fn){ + if (this._endCalled) { + console.warn("Warning: .end() was called twice. This is not supported in superagent"); + } + this._endCalled = true; + + // store callback + this._callback = fn || noop; + + // querystring + this._appendQueryString(); + + return this._end(); +}; + +Request.prototype._end = function() { + var self = this; + var xhr = this.xhr = request.getXHR(); + var data = this._formData || this._data; + + this._setTimeouts(); + + // state change + xhr.onreadystatechange = function(){ + var readyState = xhr.readyState; + if (readyState >= 2 && self._responseTimeoutTimer) { + clearTimeout(self._responseTimeoutTimer); + } + if (4 != readyState) { + return; + } + + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + var status; + try { status = xhr.status } catch(e) { status = 0; } + + if (!status) { + if (self.timedout || self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }; + + // progress + var handleProgress = function(direction, e) { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + } + e.direction = direction; + self.emit('progress', e); + } + if (this.hasListeners('progress')) { + try { + xhr.onprogress = handleProgress.bind(null, 'download'); + if (xhr.upload) { + xhr.upload.onprogress = handleProgress.bind(null, 'upload'); + } + } catch(e) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + + // initiate request + try { + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + } catch (err) { + // see #1149 + return this.callback(err); + } + + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { + // serialize stuff + var contentType = this._header['content-type']; + var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) { + serialize = request.serialize['application/json']; + } + if (serialize) data = serialize(data); + } + + // set header fields + for (var field in this.header) { + if (null == this.header[field]) continue; + + if (this.header.hasOwnProperty(field)) + xhr.setRequestHeader(field, this.header[field]); + } + + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data !== 'undefined' ? data : null); + return this; +}; + +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; + +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.options = function(url, data, fn){ + var req = request('OPTIONS', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * DELETE `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +function del(url, data, fn){ + var req = request('DELETE', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +request['del'] = del; +request['delete'] = del; + +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isObject(obj) { + return null !== obj && 'object' === typeof obj; +} + +module.exports = isObject; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var storage = __webpack_require__(10); +var AV = __webpack_require__(6); + +var removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage); + +var getCacheData = function getCacheData(cacheData, key) { + try { + cacheData = JSON.parse(cacheData); + } catch (e) { + return null; + } + if (cacheData) { + var expired = cacheData.expiredAt && cacheData.expiredAt < Date.now(); + if (!expired) { + return cacheData.value; + } + return removeAsync(key).then(function () { + return null; + }); + } + return null; +}; + +exports.getAsync = function (key) { + key = AV.applicationId + '/' + key; + return storage.getItemAsync(key).then(function (cache) { + return getCacheData(cache, key); + }); +}; + +exports.setAsync = function (key, value, ttl) { + var cache = { value: value }; + if (typeof ttl === 'number') { + cache.expiredAt = Date.now() + ttl; + } + return storage.setItemAsync(AV.applicationId + '/' + key, JSON.stringify(cache)); +}; + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(1); +var localStorage = __webpack_require__(36); + +var syncApiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +if (!localStorage.async) { + // wrap sync apis with async ones. + _(syncApiNames).each(function (apiName) { + if (typeof localStorage[apiName] === 'function') { + localStorage[apiName + 'Async'] = function () { + return Promise.resolve(localStorage[apiName].apply(localStorage, arguments)); + }; + } + }); +} else { + _(syncApiNames).each(function (apiName) { + if (typeof localStorage[apiName] !== 'function') { + localStorage[apiName] = function () { + var error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.'); + error.code = 'SYNC_API_NOT_AVAILABLE'; + throw error; + }; + } + }); +} + +module.exports = localStorage; + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = '2.1.4'; + +/***/ }), +/* 12 */ +/***/ (function(module, exports) { + +var charenc = { + // UTF-8 encoding + utf8: { + // Convert a string to a byte array + stringToBytes: function(str) { + return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))); + }, + + // Convert a byte array to a string + bytesToString: function(bytes) { + return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))); + } + }, + + // Binary encoding + bin: { + // Convert a string to a byte array + stringToBytes: function(str) { + for (var bytes = [], i = 0; i < str.length; i++) + bytes.push(str.charCodeAt(i) & 0xFF); + return bytes; + }, + + // Convert a byte array to a string + bytesToString: function(bytes) { + for (var str = [], i = 0; i < bytes.length; i++) + str.push(String.fromCharCode(bytes[i])); + return str.join(''); + } + } +}; + +module.exports = charenc; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + var PUBLIC_KEY = "*"; + + /** + * Creates a new ACL. + * If no argument is given, the ACL has no permissions for anyone. + * If the argument is a AV.User, the ACL will have read and write + * permission for only that user. + * If the argument is any other JSON object, that object will be interpretted + * as a serialized ACL created with toJSON(). + * @see AV.Object#setACL + * @class + * + *

An ACL, or Access Control List can be added to any + * AV.Object to restrict access to only a subset of users + * of your application.

+ */ + AV.ACL = function (arg1) { + var self = this; + self.permissionsById = {}; + if (_.isObject(arg1)) { + if (arg1 instanceof AV.User) { + self.setReadAccess(arg1, true); + self.setWriteAccess(arg1, true); + } else { + if (_.isFunction(arg1)) { + throw new Error('AV.ACL() called with a function. Did you forget ()?'); + } + AV._objectEach(arg1, function (accessList, userId) { + if (!_.isString(userId)) { + throw new Error('Tried to create an ACL with an invalid userId.'); + } + self.permissionsById[userId] = {}; + AV._objectEach(accessList, function (allowed, permission) { + if (permission !== "read" && permission !== "write") { + throw new Error('Tried to create an ACL with an invalid permission type.'); + } + if (!_.isBoolean(allowed)) { + throw new Error('Tried to create an ACL with an invalid permission value.'); + } + self.permissionsById[userId][permission] = allowed; + }); + }); + } + } + }; + + /** + * Returns a JSON-encoded version of the ACL. + * @return {Object} + */ + AV.ACL.prototype.toJSON = function () { + return _.clone(this.permissionsById); + }; + + AV.ACL.prototype._setAccess = function (accessType, userId, allowed) { + if (userId instanceof AV.User) { + userId = userId.id; + } else if (userId instanceof AV.Role) { + userId = "role:" + userId.getName(); + } + if (!_.isString(userId)) { + throw new Error('userId must be a string.'); + } + if (!_.isBoolean(allowed)) { + throw new Error('allowed must be either true or false.'); + } + var permissions = this.permissionsById[userId]; + if (!permissions) { + if (!allowed) { + // The user already doesn't have this permission, so no action needed. + return; + } else { + permissions = {}; + this.permissionsById[userId] = permissions; + } + } + + if (allowed) { + this.permissionsById[userId][accessType] = true; + } else { + delete permissions[accessType]; + if (_.isEmpty(permissions)) { + delete this.permissionsById[userId]; + } + } + }; + + AV.ACL.prototype._getAccess = function (accessType, userId) { + if (userId instanceof AV.User) { + userId = userId.id; + } else if (userId instanceof AV.Role) { + userId = "role:" + userId.getName(); + } + var permissions = this.permissionsById[userId]; + if (!permissions) { + return false; + } + return permissions[accessType] ? true : false; + }; + + /** + * Set whether the given user is allowed to read this object. + * @param userId An instance of AV.User or its objectId. + * @param {Boolean} allowed Whether that user should have read access. + */ + AV.ACL.prototype.setReadAccess = function (userId, allowed) { + this._setAccess("read", userId, allowed); + }; + + /** + * Get whether the given user id is *explicitly* allowed to read this object. + * Even if this returns false, the user may still be able to access it if + * getPublicReadAccess returns true or a role that the user belongs to has + * write access. + * @param userId An instance of AV.User or its objectId, or a AV.Role. + * @return {Boolean} + */ + AV.ACL.prototype.getReadAccess = function (userId) { + return this._getAccess("read", userId); + }; + + /** + * Set whether the given user id is allowed to write this object. + * @param userId An instance of AV.User or its objectId, or a AV.Role.. + * @param {Boolean} allowed Whether that user should have write access. + */ + AV.ACL.prototype.setWriteAccess = function (userId, allowed) { + this._setAccess("write", userId, allowed); + }; + + /** + * Get whether the given user id is *explicitly* allowed to write this object. + * Even if this returns false, the user may still be able to write it if + * getPublicWriteAccess returns true or a role that the user belongs to has + * write access. + * @param userId An instance of AV.User or its objectId, or a AV.Role. + * @return {Boolean} + */ + AV.ACL.prototype.getWriteAccess = function (userId) { + return this._getAccess("write", userId); + }; + + /** + * Set whether the public is allowed to read this object. + * @param {Boolean} allowed + */ + AV.ACL.prototype.setPublicReadAccess = function (allowed) { + this.setReadAccess(PUBLIC_KEY, allowed); + }; + + /** + * Get whether the public is allowed to read this object. + * @return {Boolean} + */ + AV.ACL.prototype.getPublicReadAccess = function () { + return this.getReadAccess(PUBLIC_KEY); + }; + + /** + * Set whether the public is allowed to write this object. + * @param {Boolean} allowed + */ + AV.ACL.prototype.setPublicWriteAccess = function (allowed) { + this.setWriteAccess(PUBLIC_KEY, allowed); + }; + + /** + * Get whether the public is allowed to write this object. + * @return {Boolean} + */ + AV.ACL.prototype.getPublicWriteAccess = function () { + return this.getWriteAccess(PUBLIC_KEY); + }; + + /** + * Get whether users belonging to the given role are allowed + * to read this object. Even if this returns false, the role may + * still be able to write it if a parent role has read access. + * + * @param role The name of the role, or a AV.Role object. + * @return {Boolean} true if the role has read access. false otherwise. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.getRoleReadAccess = function (role) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + return this.getReadAccess("role:" + role); + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Get whether users belonging to the given role are allowed + * to write this object. Even if this returns false, the role may + * still be able to write it if a parent role has write access. + * + * @param role The name of the role, or a AV.Role object. + * @return {Boolean} true if the role has write access. false otherwise. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.getRoleWriteAccess = function (role) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + return this.getWriteAccess("role:" + role); + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Set whether users belonging to the given role are allowed + * to read this object. + * + * @param role The name of the role, or a AV.Role object. + * @param {Boolean} allowed Whether the given role can read this object. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.setRoleReadAccess = function (role, allowed) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + this.setReadAccess("role:" + role, allowed); + return; + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Set whether users belonging to the given role are allowed + * to write this object. + * + * @param role The name of the role, or a AV.Role object. + * @param {Boolean} allowed Whether the given role can write this object. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.setRoleWriteAccess = function (role, allowed) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + this.setWriteAccess("role:" + role, allowed); + return; + } + throw new Error('role must be a AV.Role or a String'); + }; +}; + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * Contains functions for calling and declaring + *

+ * Some functions are only available from Cloud Code. + *

+ * + * @namespace + */ + AV.Cloud = AV.Cloud || {}; + + _.extend(AV.Cloud, /** @lends AV.Cloud */{ + /** + * Makes a call to a cloud function. + * @param {String} name The function name. + * @param {Object} data The parameters to send to the cloud function. + * @param {AuthOptions} options + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + run: function run(name, data, options) { + var request = AVRequest('functions', name, null, 'POST', AV._encode(data, null, true), options); + + return request.then(function (resp) { + return AV._decode(resp).result; + }); + }, + + /** + * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response + * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object} + * @param {String} name The function name. + * @param {Object} data The parameters to send to the cloud function. + * @param {AuthOptions} options + * @return {Promise} A promise that will be resolved with the result of the function. + */ + rpc: function rpc(name, data, options) { + if (_.isArray(data)) { + return Promise.reject(new Error('Can\'t pass Array as the param of rpc function in JavaScript SDK.')); + } + + return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function (resp) { + return AV._decode(resp).result; + }); + }, + + /** + * Make a call to request server date time. + * @return {Promise.} A promise that will be resolved with the result + * of the function. + * @since 0.5.9 + */ + getServerDate: function getServerDate() { + var request = AVRequest("date", null, null, 'GET'); + + return request.then(function (resp) { + return AV._decode(resp); + }); + }, + + /** + * Makes a call to request a sms code for operation verification. + * @param {Object} data The mobile phone number string or a JSON + * object that contains mobilePhoneNumber,template,op,ttl,name etc. + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + requestSmsCode: function requestSmsCode(data) { + if (_.isString(data)) { + data = { mobilePhoneNumber: data }; + } + if (!data.mobilePhoneNumber) { + throw new Error('Missing mobilePhoneNumber.'); + } + var request = AVRequest("requestSmsCode", null, null, 'POST', data); + return request; + }, + + /** + * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode + * @param {String} code The sms code sent by AV.Cloud.requestSmsCode + * @param {phone} phone The mobile phoner number(optional). + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + verifySmsCode: function verifySmsCode(code, phone) { + if (!code) throw new Error('Missing sms code.'); + var params = {}; + if (_.isString(phone)) { + params['mobilePhoneNumber'] = phone; + } + + var request = AVRequest("verifySmsCode", code, null, 'POST', params); + return request; + } + }); +}; + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + var eventSplitter = /\s+/; + var slice = Array.prototype.slice; + + /** + * @class + * + *

AV.Events is a fork of Backbone's Events module, provided for your + * convenience.

+ * + *

A module that can be mixed in to any object in order to provide + * it with custom events. You may bind callback functions to an event + * with `on`, or remove these functions with `off`. + * Triggering an event fires all callbacks in the order that `on` was + * called. + * + * @private + * @example + * var object = {}; + * _.extend(object, AV.Events); + * object.on('expand', function(){ alert('expanded'); }); + * object.trigger('expand');

+ * + */ + AV.Events = { + /** + * Bind one or more space separated events, `events`, to a `callback` + * function. Passing `"all"` will bind the callback to all events fired. + */ + on: function on(events, callback, context) { + + var calls, event, node, tail, list; + if (!callback) { + return this; + } + events = events.split(eventSplitter); + calls = this._callbacks || (this._callbacks = {}); + + // Create an immutable callback list, allowing traversal during + // modification. The tail is an empty object that will always be used + // as the next node. + event = events.shift(); + while (event) { + list = calls[event]; + node = list ? list.tail : {}; + node.next = tail = {}; + node.context = context; + node.callback = callback; + calls[event] = { tail: tail, next: list ? list.next : node }; + event = events.shift(); + } + + return this; + }, + + /** + * Remove one or many callbacks. If `context` is null, removes all callbacks + * with that function. If `callback` is null, removes all callbacks for the + * event. If `events` is null, removes all bound callbacks for all events. + */ + off: function off(events, callback, context) { + var event, calls, node, tail, cb, ctx; + + // No events, or removing *all* events. + if (!(calls = this._callbacks)) { + return; + } + if (!(events || callback || context)) { + delete this._callbacks; + return this; + } + + // Loop through the listed events and contexts, splicing them out of the + // linked list of callbacks if appropriate. + events = events ? events.split(eventSplitter) : _.keys(calls); + event = events.shift(); + while (event) { + node = calls[event]; + delete calls[event]; + if (!node || !(callback || context)) { + continue; + } + // Create a new list, omitting the indicated callbacks. + tail = node.tail; + node = node.next; + while (node !== tail) { + cb = node.callback; + ctx = node.context; + if (callback && cb !== callback || context && ctx !== context) { + this.on(event, cb, ctx); + } + node = node.next; + } + event = events.shift(); + } + + return this; + }, + + /** + * Trigger one or many events, firing all bound callbacks. Callbacks are + * passed the same arguments as `trigger` is, apart from the event name + * (unless you're listening on `"all"`, which will cause your callback to + * receive the true name of the event as the first argument). + */ + trigger: function trigger(events) { + var event, node, calls, tail, args, all, rest; + if (!(calls = this._callbacks)) { + return this; + } + all = calls.all; + events = events.split(eventSplitter); + rest = slice.call(arguments, 1); + + // For each event, walk through the linked list of callbacks twice, + // first to trigger the event, then to trigger any `"all"` callbacks. + event = events.shift(); + while (event) { + node = calls[event]; + if (node) { + tail = node.tail; + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, rest); + } + } + node = all; + if (node) { + tail = node.tail; + args = [event].concat(rest); + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, args); + } + } + event = events.shift(); + } + + return this; + } + }; + + /** + * @function + */ + AV.Events.bind = AV.Events.on; + + /** + * @function + */ + AV.Events.unbind = AV.Events.off; +}; + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var cos = __webpack_require__(33); +var qiniu = __webpack_require__(34); +var s3 = __webpack_require__(35); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var Promise = __webpack_require__(1); + +var _require = __webpack_require__(4), + tap = _require.tap; + +var debug = __webpack_require__(5)('leancloud:file'); +var parseBase64 = __webpack_require__(37); + +module.exports = function (AV) { + + // 挂载一些配置 + var avConfig = AV._config; + + var hexOctet = function hexOctet() { + return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + }; + + // port from browserify path module + // since react-native packager won't shim node modules. + var extname = function extname(path) { + return path.match(/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/)[4]; + }; + + var b64Digit = function b64Digit(number) { + if (number < 26) { + return String.fromCharCode(65 + number); + } + if (number < 52) { + return String.fromCharCode(97 + (number - 26)); + } + if (number < 62) { + return String.fromCharCode(48 + (number - 52)); + } + if (number === 62) { + return '+'; + } + if (number === 63) { + return '/'; + } + throw new Error('Tried to encode large digit ' + number + ' in base64.'); + }; + + var encodeBase64 = function encodeBase64(array) { + var chunks = []; + chunks.length = Math.ceil(array.length / 3); + _.times(chunks.length, function (i) { + var b1 = array[i * 3]; + var b2 = array[i * 3 + 1] || 0; + var b3 = array[i * 3 + 2] || 0; + + var has2 = i * 3 + 1 < array.length; + var has3 = i * 3 + 2 < array.length; + + chunks[i] = [b64Digit(b1 >> 2 & 0x3F), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0F), has2 ? b64Digit(b2 << 2 & 0x3C | b3 >> 6 & 0x03) : "=", has3 ? b64Digit(b3 & 0x3F) : "="].join(""); + }); + return chunks.join(""); + }; + + /** + * An AV.File is a local representation of a file that is saved to the AV + * cloud. + * @param name {String} The file's name. This will change to a unique value + * once the file has finished saving. + * @param data {Array} The data for the file, as either: + * 1. an Array of byte value Numbers, or + * 2. an Object like { base64: "..." } with a base64-encoded String. + * 3. a File object selected with a file upload control. (3) only works + * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+. + * 4.a Buffer object in Node.js runtime. + * + * For example:
+   * var fileUploadControl = $("#profilePhotoFileUpload")[0];
+   * if (fileUploadControl.files.length > 0) {
+   *   var file = fileUploadControl.files[0];
+   *   var name = "photo.jpg";
+   *   var file = new AV.File(name, file);
+   *   file.save().then(function() {
+   *     // The file has been saved to AV.
+   *   }, function(error) {
+   *     // The file either could not be read, or could not be saved to AV.
+   *   });
+   * }
+ * + * @class + * @param [mimeType] {String} Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + */ + AV.File = function (name, data, mimeType) { + + this.attributes = { + name: name, + url: '', + metaData: {}, + // 用来存储转换后要上传的 base64 String + base64: '' + }; + + if (_.isString(data)) { + throw new TypeError("Creating an AV.File from a String is not yet supported."); + } + if (_.isArray(data)) { + this.attributes.metaData.size = data.length; + data = { base64: encodeBase64(data) }; + } + + this._extName = ''; + this._data = data; + + var owner = void 0; + if (data && data.owner) { + owner = data.owner; + } else if (!AV._config.disableCurrentUser) { + try { + owner = AV.User.current(); + } catch (error) { + if ('SYNC_API_NOT_AVAILABLE' === error.code) { + console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().'); + } else { + throw error; + } + } + } + + this.attributes.metaData.owner = owner ? owner.id : 'unknown'; + + this.set('mime_type', mimeType); + }; + + /** + * Creates a fresh AV.File object with exists url for saving to AVOS Cloud. + * @param {String} name the file name + * @param {String} url the file url. + * @param {Object} [metaData] the file metadata object. + * @param {String} [type] Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + * @return {AV.File} the file object + */ + AV.File.withURL = function (name, url, metaData, type) { + if (!name || !url) { + throw new Error("Please provide file name and url"); + } + var file = new AV.File(name, null, type); + //copy metaData properties to file. + if (metaData) { + for (var prop in metaData) { + if (!file.attributes.metaData[prop]) file.attributes.metaData[prop] = metaData[prop]; + } + } + file.attributes.url = url; + //Mark the file is from external source. + file.attributes.metaData.__source = 'external'; + return file; + }; + + /** + * Creates a file object with exists objectId. + * @param {String} objectId The objectId string + * @return {AV.File} the file object + */ + AV.File.createWithoutData = function (objectId) { + var file = new AV.File(); + file.id = objectId; + return file; + }; + + AV.File.prototype = { + className: '_File', + + _toFullJSON: function _toFullJSON(seenObjects) { + var _this = this; + + var json = _.clone(this.attributes); + AV._objectEach(json, function (val, key) { + json[key] = AV._encode(val, seenObjects); + }); + AV._objectEach(this._operations, function (val, key) { + json[key] = val; + }); + + if (_.has(this, "id")) { + json.objectId = this.id; + } + _(['createdAt', 'updatedAt']).each(function (key) { + if (_.has(_this, key)) { + var val = _this[key]; + json[key] = _.isDate(val) ? val.toJSON() : val; + } + }); + json.__type = "File"; + return json; + }, + toJSON: function toJSON() { + var json = this._toFullJSON(); + // add id and keep __type for backward compatible + if (_.has(this, 'id')) { + json.id = this.id; + } + return json; + }, + + + /** + * Returns the ACL for this file. + * @returns {AV.ACL} An instance of AV.ACL. + */ + getACL: function getACL() { + return this._acl; + }, + + /** + * Sets the ACL to be used for this file. + * @param {AV.ACL} acl An instance of AV.ACL. + */ + setACL: function setACL(acl) { + if (!(acl instanceof AV.ACL)) { + return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.'); + } + this._acl = acl; + }, + + /** + * Gets the name of the file. Before save is called, this is the filename + * given by the user. After save is called, that name gets prefixed with a + * unique identifier. + */ + name: function name() { + return this.get('name'); + }, + + /** + * Gets the url of the file. It is only available after you save the file or + * after you get the file from a AV.Object. + * @return {String} + */ + url: function url() { + return this.get('url'); + }, + + /** + * Gets the attributs of the file object. + * @param {String} The attribute name which want to get. + * @returns {Any} + */ + get: function get(attrName) { + switch (attrName) { + case 'objectId': + return this.id; + case 'url': + case 'name': + case 'mime_type': + case 'metaData': + case 'createdAt': + case 'updatedAt': + return this.attributes[attrName]; + default: + return this.attributes.metaData[attrName]; + } + }, + + /** + * Set the metaData of the file object. + * @param {Object} Object is an key value Object for setting metaData. + * @param {String} attr is an optional metadata key. + * @param {Object} value is an optional metadata value. + * @returns {String|Number|Array|Object} + */ + set: function set() { + var _this2 = this; + + var set = function set(attrName, value) { + switch (attrName) { + case 'name': + case 'url': + case 'mime_type': + case 'base64': + case 'metaData': + _this2.attributes[attrName] = value; + break; + default: + // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面 + _this2.attributes.metaData[attrName] = value; + break; + } + }; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + switch (args.length) { + case 1: + // 传入一个 Object + for (var k in args[0]) { + set(k, args[0][k]); + } + break; + case 2: + set(args[0], args[1]); + break; + } + }, + + /** + *

Returns the file's metadata JSON object if no arguments is given.Returns the + * metadata value if a key is given.Set metadata value if key and value are both given.

+ *

+    *  var metadata = file.metaData(); //Get metadata JSON object.
+    *  var size = file.metaData('size');  // Get the size metadata value.
+    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.
+    *

+ * @return {Object} The file's metadata JSON object. + * @param {String} attr an optional metadata key. + * @param {Object} value an optional metadata value. + **/ + metaData: function metaData(attr, value) { + if (attr && value) { + this.attributes.metaData[attr] = value; + return this; + } else if (attr && !value) { + return this.attributes.metaData[attr]; + } else { + return this.attributes.metaData; + } + }, + + /** + * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。 + * @return {String} 缩略图URL + * @param {Number} width 宽度,单位:像素 + * @param {Number} heigth 高度,单位:像素 + * @param {Number} quality 质量,1-100的数字,默认100 + * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。 + * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。 + */ + + thumbnailURL: function thumbnailURL(width, height, quality, scaleToFit, fmt) { + var url = this.attributes.url; + if (!url) { + throw new Error('Invalid url.'); + } + if (!width || !height || width <= 0 || height <= 0) { + throw new Error('Invalid width or height value.'); + } + quality = quality || 100; + scaleToFit = !scaleToFit ? true : scaleToFit; + if (quality <= 0 || quality > 100) { + throw new Error('Invalid quality value.'); + } + fmt = fmt || 'png'; + var mode = scaleToFit ? 2 : 1; + return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt; + }, + + /** + * Returns the file's size. + * @return {Number} The file's size in bytes. + **/ + size: function size() { + return this.metaData().size; + }, + + /** + * Returns the file's owner. + * @return {String} The file's owner id. + */ + ownerId: function ownerId() { + return this.metaData().owner; + }, + + /** + * Destroy the file. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + if (!this.id) { + return Promise.reject(new Error('The file id is not eixsts.')); + } + var request = AVRequest("files", null, this.id, 'DELETE', null, options); + return request; + }, + + /** + * Request Qiniu upload token + * @param {string} type + * @return {Promise} Resolved with the response + * @private + */ + _fileToken: function _fileToken(type) { + var route = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'fileTokens'; + + var name = this.attributes.name; + + var extName = extname(name); + if (!extName && this._extName) { + name += this._extName; + extName = this._extName; + } + // Create 16-bits uuid as qiniu key. + var key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName; + var data = { + key: key, + name: name, + ACL: this._acl, + mime_type: type, + metaData: this.attributes.metaData + }; + this._qiniu_key = key; + return AVRequest(route, null, null, 'POST', data); + }, + + + /** + * @callback UploadProgressCallback + * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes + */ + /** + * Saves the file to the AV cloud. + * @param {Object} [options] + * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。 + * @return {Promise} Promise that is resolved when the save finishes. + */ + save: function save(options) { + var _this3 = this; + + if (this.id) { + throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.'); + } + if (!this._previousSave) { + if (this._data) { + var mimeType = this.get('mime_type'); + this._previousSave = this._fileToken(mimeType).then(function (uploadInfo) { + if (uploadInfo.mime_type) { + mimeType = uploadInfo.mime_type; + _this3.set('mime_type', mimeType); + } + _this3._token = uploadInfo.token; + return Promise.resolve().then(function () { + var data = _this3._data; + if (data && data.base64) { + return parseBase64(data.base64, mimeType); + } + if (data && data.blob) { + if (!data.blob.type && mimeType) { + data.blob.type = mimeType; + } + if (!data.blob.name) { + data.blob.name = _this3.get('name'); + } + if (true) { + _this3._extName = extname(data.blob.uri); + } + return data.blob; + } + if (typeof File !== "undefined" && data instanceof File) { + if (data.size) { + _this3.attributes.metaData.size = data.size; + } + if (data.name) { + _this3._extName = extname(data.name); + } + return data; + } + if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) { + _this3.attributes.metaData.size = data.length; + return data; + } + throw new TypeError('malformed file data'); + }).then(function (data) { + var uploadPromise = void 0; + switch (uploadInfo.provider) { + case 's3': + uploadPromise = s3(uploadInfo, data, _this3, options); + break; + case 'qcloud': + uploadPromise = cos(uploadInfo, data, _this3, options); + break; + case 'qiniu': + default: + uploadPromise = qiniu(uploadInfo, data, _this3, options); + break; + } + return uploadPromise.then(tap(function () { + return _this3._callback(true); + }), function (error) { + _this3._callback(false); + throw error; + }); + }); + }); + } else if (this.attributes.url && this.attributes.metaData.__source === 'external') { + // external link file. + var data = { + name: this.attributes.name, + ACL: this._acl, + metaData: this.attributes.metaData, + mime_type: this.mimeType, + url: this.attributes.url + }; + this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then(function (response) { + _this3.attributes.name = response.name; + _this3.attributes.url = response.url; + _this3.id = response.objectId; + if (response.size) { + _this3.attributes.metaData.size = response.size; + } + return _this3; + }); + } + } + return this._previousSave; + }, + _callback: function _callback(success) { + AVRequest('fileCallback', null, null, 'post', { + token: this._token, + result: success + }).catch(debug); + delete this._token; + delete this._data; + }, + + + /** + * fetch the file from server. If the server's representation of the + * model differs from its current attributes, they will be overriden, + * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option. + * @return {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch: function fetch(options) { + var options = null; + + var request = AVRequest('files', null, this.id, 'GET', options); + return request.then(this._finishFetch.bind(this)); + }, + _finishFetch: function _finishFetch(response) { + var value = AV.Object.prototype.parse(response); + value.attributes = { + name: value.name, + url: value.url, + mime_type: value.mime_type, + bucket: value.bucket + }; + value.attributes.metaData = value.metaData || {}; + value.id = value.objectId; + // clean + delete value.objectId; + delete value.metaData; + delete value.url; + delete value.name; + delete value.mime_type; + delete value.bucket; + _.extend(this, value); + return this; + } + }; +}; + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +/*global navigator: false */ +module.exports = function (AV) { + /** + * Creates a new GeoPoint with any of the following forms:
+ * @example + * new GeoPoint(otherGeoPoint) + * new GeoPoint(30, 30) + * new GeoPoint([30, 30]) + * new GeoPoint({latitude: 30, longitude: 30}) + * new GeoPoint() // defaults to (0, 0) + * @class + * + *

Represents a latitude / longitude point that may be associated + * with a key in a AVObject or used as a reference point for geo queries. + * This allows proximity-based queries on the key.

+ * + *

Only one key in a class may contain a GeoPoint.

+ * + *

Example:

+   *   var point = new AV.GeoPoint(30.0, -20.0);
+   *   var object = new AV.Object("PlaceObject");
+   *   object.set("location", point);
+   *   object.save();

+ */ + AV.GeoPoint = function (arg1, arg2) { + if (_.isArray(arg1)) { + AV.GeoPoint._validate(arg1[0], arg1[1]); + this.latitude = arg1[0]; + this.longitude = arg1[1]; + } else if (_.isObject(arg1)) { + AV.GeoPoint._validate(arg1.latitude, arg1.longitude); + this.latitude = arg1.latitude; + this.longitude = arg1.longitude; + } else if (_.isNumber(arg1) && _.isNumber(arg2)) { + AV.GeoPoint._validate(arg1, arg2); + this.latitude = arg1; + this.longitude = arg2; + } else { + this.latitude = 0; + this.longitude = 0; + } + + // Add properties so that anyone using Webkit or Mozilla will get an error + // if they try to set values that are out of bounds. + var self = this; + if (this.__defineGetter__ && this.__defineSetter__) { + // Use _latitude and _longitude to actually store the values, and add + // getters and setters for latitude and longitude. + this._latitude = this.latitude; + this._longitude = this.longitude; + this.__defineGetter__("latitude", function () { + return self._latitude; + }); + this.__defineGetter__("longitude", function () { + return self._longitude; + }); + this.__defineSetter__("latitude", function (val) { + AV.GeoPoint._validate(val, self.longitude); + self._latitude = val; + }); + this.__defineSetter__("longitude", function (val) { + AV.GeoPoint._validate(self.latitude, val); + self._longitude = val; + }); + } + }; + + /** + * @lends AV.GeoPoint.prototype + * @property {float} latitude North-south portion of the coordinate, in range + * [-90, 90]. Throws an exception if set out of range in a modern browser. + * @property {float} longitude East-west portion of the coordinate, in range + * [-180, 180]. Throws if set out of range in a modern browser. + */ + + /** + * Throws an exception if the given lat-long is out of bounds. + * @private + */ + AV.GeoPoint._validate = function (latitude, longitude) { + if (latitude < -90.0) { + throw new Error("AV.GeoPoint latitude " + latitude + " < -90.0."); + } + if (latitude > 90.0) { + throw new Error("AV.GeoPoint latitude " + latitude + " > 90.0."); + } + if (longitude < -180.0) { + throw new Error("AV.GeoPoint longitude " + longitude + " < -180.0."); + } + if (longitude > 180.0) { + throw new Error("AV.GeoPoint longitude " + longitude + " > 180.0."); + } + }; + + /** + * Creates a GeoPoint with the user's current location, if available. + * @return {Promise.} + */ + AV.GeoPoint.current = function () { + return new AV.Promise(function (resolve, reject) { + navigator.geolocation.getCurrentPosition(function (location) { + resolve(new AV.GeoPoint({ + latitude: location.coords.latitude, + longitude: location.coords.longitude + })); + }, reject); + }); + }; + + AV.GeoPoint.prototype = { + /** + * Returns a JSON representation of the GeoPoint, suitable for AV. + * @return {Object} + */ + toJSON: function toJSON() { + AV.GeoPoint._validate(this.latitude, this.longitude); + return { + "__type": "GeoPoint", + latitude: this.latitude, + longitude: this.longitude + }; + }, + + /** + * Returns the distance from this GeoPoint to another in radians. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + radiansTo: function radiansTo(point) { + var d2r = Math.PI / 180.0; + var lat1rad = this.latitude * d2r; + var long1rad = this.longitude * d2r; + var lat2rad = point.latitude * d2r; + var long2rad = point.longitude * d2r; + var deltaLat = lat1rad - lat2rad; + var deltaLong = long1rad - long2rad; + var sinDeltaLatDiv2 = Math.sin(deltaLat / 2); + var sinDeltaLongDiv2 = Math.sin(deltaLong / 2); + // Square of half the straight line chord distance between both points. + var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2; + a = Math.min(1.0, a); + return 2 * Math.asin(Math.sqrt(a)); + }, + + /** + * Returns the distance from this GeoPoint to another in kilometers. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + kilometersTo: function kilometersTo(point) { + return this.radiansTo(point) * 6371.0; + }, + + /** + * Returns the distance from this GeoPoint to another in miles. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + milesTo: function milesTo(point) { + return this.radiansTo(point) * 3958.8; + } + }; +}; + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var AV = __webpack_require__(6); +var request = __webpack_require__(2); + +var initialize = function initialize(appId, appKey, masterKey, hookKey) { + if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) { + console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.'); + } + AV.applicationId = appId; + AV.applicationKey = appKey; + AV.masterKey = masterKey; + if (false) { + AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY; + } + AV._useMasterKey = false; +}; + +var masterKeyWarn = function masterKeyWarn() { + console.warn('MasterKey is not supposed to be used in browser.'); +}; + +/** + * Call this method first to set up your authentication tokens for AV. + * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn . + * @function AV.init + * @param {Object} options + * @param {String} options.appId application id + * @param {String} options.appKey application key + * @param {String} options.masterKey application master key +*/ + +AV.init = function () { + if (arguments.length === 1) { + var options = arguments.length <= 0 ? undefined : arguments[0]; + if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { + if ("ReactNative" && options.masterKey) { + masterKeyWarn(); + } + initialize(options.appId, options.appKey, options.masterKey, options.hookKey); + request.setServerUrlByRegion(options.region); + } else { + throw new Error('AV.init(): Parameter is not correct.'); + } + } else { + // 兼容旧版本的初始化方法 + if ("ReactNative" && (arguments.length <= 3 ? undefined : arguments[3])) { + masterKeyWarn(); + } + initialize.apply(undefined, arguments); + request.setServerUrlByRegion('cn'); + } +}; + +// If we're running in node.js, allow using the master key. +if (false) { + AV.Cloud = AV.Cloud || {}; + /** + * Switches the LeanCloud SDK to using the Master key. The Master key grants + * priveleged access to the data in LeanCloud and can be used to bypass ACLs and + * other restrictions that are applied to the client SDKs. + *

Available in Cloud Code and Node.js only. + *

+ */ + AV.Cloud.useMasterKey = function () { + AV._useMasterKey = true; + }; +} + +// 兼容老版本的初始化方法 +AV.initialize = AV.init; + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * 包含了使用了 LeanCloud + * 离线数据分析功能的函数。 + *

+ * 仅在云引擎运行环境下有效。 + *

+ * @namespace + */ + AV.Insight = AV.Insight || {}; + + _.extend(AV.Insight, /** @lends AV.Insight */{ + + /** + * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用 + * AV.Insight.JobQuery 查询任务状态和结果。 + * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
+     *                   { "sql" : "select count(*) as c,gender from _User group by gender",
+     *                     "saveAs": {
+     *                         "className" : "UserGender",
+     *                         "limit": 1
+     *                      }
+     *                   }
+     *                  
+ * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。 + * @param {AuthOptions} [options] + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + startJob: function startJob(jobConfig, options) { + if (!jobConfig || !jobConfig.sql) { + throw new Error('Please provide the sql to run the job.'); + } + var data = { + jobConfig: jobConfig, + appId: AV.applicationId + }; + var request = AVRequest("bigquery", 'jobs', null, 'POST', AV._encode(data, null, true), options); + + return request.then(function (resp) { + return AV._decode(resp).id; + }); + }, + + /** + * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。 + *

+ * 仅在云引擎运行环境下有效。 + *

+ * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成 + * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息, + * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。 + * + */ + on: function on(event, cb) {} + }); + + /** + * 创建一个对象,用于查询 Insight 任务状态和结果。 + * @class + * @param {String} id 任务 id + * @since 0.5.5 + */ + AV.Insight.JobQuery = function (id, className) { + if (!id) { + throw new Error('Please provide the job id.'); + } + this.id = id; + this.className = className; + this._skip = 0; + this._limit = 100; + }; + + AV.Insight.JobQuery.prototype = { + + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * @param {Number} n the number of results to skip. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + skip: function skip(n) { + this._skip = n; + return this; + }, + + /** + * Sets the limit of the number of results to return. The default limit is + * 100, with a maximum of 1000 results being returned at a time. + * @param {Number} n the number of results to limit to. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + limit: function limit(n) { + this._limit = n; + return this; + }, + + /** + * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数, + * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间 + * startTime、endTime 等信息。 + * + * @param {AuthOptions} [options] + * @return {Promise} A promise that will be resolved with the result + * of the function. + * + */ + find: function find(options) { + var params = { + skip: this._skip, + limit: this._limit + }; + + var request = AVRequest("bigquery", 'jobs', this.id, "GET", params, options); + var self = this; + return request.then(function (response) { + if (response.error) { + return AV.Promise.reject(new AVError(response.code, response.error)); + } + return AV.Promise.resolve(response); + }); + } + + }; +}; + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var utils = __webpack_require__(4); + +var RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt']; +var checkReservedKey = function checkReservedKey(key) { + if (RESERVED_KEYS.indexOf(key) !== -1) { + throw new Error('key[' + key + '] is reserved'); + } +}; + +// AV.Object is analogous to the Java AVObject. +// It also implements the same interface as a Backbone model. + +module.exports = function (AV) { + /** + * Creates a new model with defined attributes. A client id (cid) is + * automatically generated and assigned for you. + * + *

You won't normally call this method directly. It is recommended that + * you use a subclass of AV.Object instead, created by calling + * extend.

+ * + *

However, if you don't want to use a subclass, or aren't sure which + * subclass is appropriate, you can use this form:

+   *     var object = new AV.Object("ClassName");
+   * 
+ * That is basically equivalent to:
+   *     var MyClass = AV.Object.extend("ClassName");
+   *     var object = new MyClass();
+   * 

+ * + * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @see AV.Object.extend + * + * @class + * + *

The fundamental unit of AV data, which implements the Backbone Model + * interface.

+ */ + AV.Object = function (attributes, options) { + // Allow new AV.Object("ClassName") as a shortcut to _create. + if (_.isString(attributes)) { + return AV.Object._create.apply(this, arguments); + } + + attributes = attributes || {}; + if (options && options.parse) { + attributes = this.parse(attributes); + attributes = this._mergeMagicFields(attributes); + } + var defaults = AV._getValue(this, 'defaults'); + if (defaults) { + attributes = _.extend({}, defaults, attributes); + } + if (options && options.collection) { + this.collection = options.collection; + } + + this._serverData = {}; // The last known data for this object from cloud. + this._opSetQueue = [{}]; // List of sets of changes to the data. + this._flags = {}; + this.attributes = {}; // The best estimate of this's current data. + + this._hashedJSON = {}; // Hash of values of containers at last save. + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this.set(attributes, { silent: true }); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this._hasData = true; + this._previousAttributes = _.clone(this.attributes); + this.initialize.apply(this, arguments); + }; + + /** + * @lends AV.Object.prototype + * @property {String} id The objectId of the AV Object. + */ + + /** + * Saves the given list of AV.Object. + * If any error is encountered, stops and calls the error handler. + * + *
+   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {
+   *     // All the objects were saved.
+   *   }, function(error) {
+   *     // An error occurred while saving one of the objects.
+   *   });
+   *
+   * @param {Array} list A list of AV.Object.
+   */
+  AV.Object.saveAll = function (list, options) {
+    return AV.Object._deepSaveAsync(list, null, options);
+  };
+
+  /**
+   * Fetch the given list of AV.Object.
+   *
+   * @param {AV.Object[]} objects A list of AV.Object
+   * @param {AuthOptions} options
+   * @return {Promise.} The given list of AV.Object, updated
+   */
+
+  AV.Object.fetchAll = function (objects, options) {
+    return AV.Promise.resolve().then(function () {
+      return AVRequest('batch', null, null, 'POST', {
+        requests: _.map(objects, function (object) {
+          if (!object.className) throw new Error('object must have className to fetch');
+          if (!object.id) throw new Error('object must have id to fetch');
+          if (object.dirty()) throw new Error('object is modified but not saved');
+          return {
+            method: 'GET',
+            path: '/1.1/classes/' + object.className + '/' + object.id
+          };
+        })
+      }, options);
+    }).then(function (response) {
+      _.forEach(objects, function (object, i) {
+        if (response[i].success) {
+          object._finishFetch(object.parse(response[i].success));
+        } else {
+          var error = new Error(response[i].error.error);
+          error.code = response[i].error.code;
+          throw error;
+        }
+      });
+      return objects;
+    });
+  };
+
+  // Attach all inheritable methods to the AV.Object prototype.
+  _.extend(AV.Object.prototype, AV.Events,
+  /** @lends AV.Object.prototype */{
+    _fetchWhenSave: false,
+
+    /**
+     * Initialize is an empty function by default. Override it with your own
+     * initialization logic.
+     */
+    initialize: function initialize() {},
+
+    /**
+      * Set whether to enable fetchWhenSave option when updating object.
+      * When set true, SDK would fetch the latest object after saving.
+      * Default is false.
+      *
+      * @deprecated use AV.Object#save with options.fetchWhenSave instead
+      * @param {boolean} enable  true to enable fetchWhenSave option.
+      */
+    fetchWhenSave: function fetchWhenSave(enable) {
+      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');
+      if (!_.isBoolean(enable)) {
+        throw new Error('Expect boolean value for fetchWhenSave');
+      }
+      this._fetchWhenSave = enable;
+    },
+
+    /**
+     * Returns the object's objectId.
+     * @return {String} the objectId.
+     */
+    getObjectId: function getObjectId() {
+      return this.id;
+    },
+
+    /**
+     * Returns the object's createdAt attribute.
+     * @return {Date}
+     */
+    getCreatedAt: function getCreatedAt() {
+      return this.createdAt || this.get('createdAt');
+    },
+
+    /**
+     * Returns the object's updatedAt attribute.
+     * @return {Date}
+     */
+    getUpdatedAt: function getUpdatedAt() {
+      return this.updatedAt || this.get('updatedAt');
+    },
+
+    /**
+     * Returns a JSON version of the object suitable for saving to AV.
+     * @return {Object}
+     */
+    toJSON: function toJSON() {
+      var json = this._toFullJSON();
+      AV._arrayEach(["__type", "className"], function (key) {
+        delete json[key];
+      });
+      return json;
+    },
+
+    _toFullJSON: function _toFullJSON(seenObjects) {
+      var _this = this;
+
+      var json = _.clone(this.attributes);
+      AV._objectEach(json, function (val, key) {
+        json[key] = AV._encode(val, seenObjects);
+      });
+      AV._objectEach(this._operations, function (val, key) {
+        json[key] = val;
+      });
+
+      if (_.has(this, "id")) {
+        json.objectId = this.id;
+      }
+      _(['createdAt', 'updatedAt']).each(function (key) {
+        if (_.has(_this, key)) {
+          var val = _this[key];
+          json[key] = _.isDate(val) ? val.toJSON() : val;
+        }
+      });
+      json.__type = "Object";
+      json.className = this.className;
+      return json;
+    },
+
+    /**
+     * Updates _hashedJSON to reflect the current state of this object.
+     * Adds any changed hash values to the set of pending changes.
+     * @private
+     */
+    _refreshCache: function _refreshCache() {
+      var self = this;
+      if (self._refreshingCache) {
+        return;
+      }
+      self._refreshingCache = true;
+      AV._objectEach(this.attributes, function (value, key) {
+        if (value instanceof AV.Object) {
+          value._refreshCache();
+        } else if (_.isObject(value)) {
+          if (self._resetCacheForKey(key)) {
+            self.set(key, new AV.Op.Set(value), { silent: true });
+          }
+        }
+      });
+      delete self._refreshingCache;
+    },
+
+    /**
+     * Returns true if this object has been modified since its last
+     * save/refresh.  If an attribute is specified, it returns true only if that
+     * particular attribute has been modified since the last save/refresh.
+     * @param {String} attr An attribute name (optional).
+     * @return {Boolean}
+     */
+    dirty: function dirty(attr) {
+      this._refreshCache();
+
+      var currentChanges = _.last(this._opSetQueue);
+
+      if (attr) {
+        return currentChanges[attr] ? true : false;
+      }
+      if (!this.id) {
+        return true;
+      }
+      if (_.keys(currentChanges).length > 0) {
+        return true;
+      }
+      return false;
+    },
+
+    /**
+     * Gets a Pointer referencing this Object.
+     * @private
+     */
+    _toPointer: function _toPointer() {
+      // if (!this.id) {
+      //   throw new Error("Can't serialize an unsaved AV.Object");
+      // }
+      return { __type: "Pointer",
+        className: this.className,
+        objectId: this.id };
+    },
+
+    /**
+     * Gets the value of an attribute.
+     * @param {String} attr The string name of an attribute.
+     */
+    get: function get(attr) {
+      switch (attr) {
+        case 'objectId':
+          return this.id;
+        case 'createdAt':
+        case 'updatedAt':
+          return this[attr];
+        default:
+          return this.attributes[attr];
+      }
+    },
+
+    /**
+     * Gets a relation on the given class for the attribute.
+     * @param {String} attr The attribute to get the relation for.
+     * @return {AV.Relation}
+     */
+    relation: function relation(attr) {
+      var value = this.get(attr);
+      if (value) {
+        if (!(value instanceof AV.Relation)) {
+          throw new Error("Called relation() on non-relation field " + attr);
+        }
+        value._ensureParentAndKey(this, attr);
+        return value;
+      } else {
+        return new AV.Relation(this, attr);
+      }
+    },
+
+    /**
+     * Gets the HTML-escaped value of an attribute.
+     */
+    escape: function escape(attr) {
+      var html = this._escapedAttributes[attr];
+      if (html) {
+        return html;
+      }
+      var val = this.attributes[attr];
+      var escaped;
+      if (utils.isNullOrUndefined(val)) {
+        escaped = '';
+      } else {
+        escaped = _.escape(val.toString());
+      }
+      this._escapedAttributes[attr] = escaped;
+      return escaped;
+    },
+
+    /**
+     * Returns true if the attribute contains a value that is not
+     * null or undefined.
+     * @param {String} attr The string name of the attribute.
+     * @return {Boolean}
+     */
+    has: function has(attr) {
+      return !utils.isNullOrUndefined(this.attributes[attr]);
+    },
+
+    /**
+     * Pulls "special" fields like objectId, createdAt, etc. out of attrs
+     * and puts them on "this" directly.  Removes them from attrs.
+     * @param attrs - A dictionary with the data for this AV.Object.
+     * @private
+     */
+    _mergeMagicFields: function _mergeMagicFields(attrs) {
+      // Check for changes of magic fields.
+      var model = this;
+      var specialFields = ["objectId", "createdAt", "updatedAt"];
+      AV._arrayEach(specialFields, function (attr) {
+        if (attrs[attr]) {
+          if (attr === "objectId") {
+            model.id = attrs[attr];
+          } else if ((attr === "createdAt" || attr === "updatedAt") && !_.isDate(attrs[attr])) {
+            model[attr] = AV._parseDate(attrs[attr]);
+          } else {
+            model[attr] = attrs[attr];
+          }
+          delete attrs[attr];
+        }
+      });
+      return attrs;
+    },
+
+    /**
+     * Returns the json to be sent to the server.
+     * @private
+     */
+    _startSave: function _startSave() {
+      this._opSetQueue.push({});
+    },
+
+    /**
+     * Called when a save fails because of an error. Any changes that were part
+     * of the save need to be merged with changes made after the save. This
+     * might throw an exception is you do conflicting operations. For example,
+     * if you do:
+     *   object.set("foo", "bar");
+     *   object.set("invalid field name", "baz");
+     *   object.save();
+     *   object.increment("foo");
+     * then this will throw when the save fails and the client tries to merge
+     * "bar" with the +1.
+     * @private
+     */
+    _cancelSave: function _cancelSave() {
+      var self = this;
+      var failedChanges = _.first(this._opSetQueue);
+      this._opSetQueue = _.rest(this._opSetQueue);
+      var nextChanges = _.first(this._opSetQueue);
+      AV._objectEach(failedChanges, function (op, key) {
+        var op1 = failedChanges[key];
+        var op2 = nextChanges[key];
+        if (op1 && op2) {
+          nextChanges[key] = op2._mergeWithPrevious(op1);
+        } else if (op1) {
+          nextChanges[key] = op1;
+        }
+      });
+      this._saving = this._saving - 1;
+    },
+
+    /**
+     * Called when a save completes successfully. This merges the changes that
+     * were saved into the known server data, and overrides it with any data
+     * sent directly from the server.
+     * @private
+     */
+    _finishSave: function _finishSave(serverData) {
+      // Grab a copy of any object referenced by this object. These instances
+      // may have already been fetched, and we don't want to lose their data.
+      // Note that doing it like this means we will unify separate copies of the
+      // same object, but that's a risk we have to take.
+      var fetchedObjects = {};
+      AV._traverse(this.attributes, function (object) {
+        if (object instanceof AV.Object && object.id && object._hasData) {
+          fetchedObjects[object.id] = object;
+        }
+      });
+
+      var savedChanges = _.first(this._opSetQueue);
+      this._opSetQueue = _.rest(this._opSetQueue);
+      this._applyOpSet(savedChanges, this._serverData);
+      this._mergeMagicFields(serverData);
+      var self = this;
+      AV._objectEach(serverData, function (value, key) {
+        self._serverData[key] = AV._decode(value, key);
+
+        // Look for any objects that might have become unfetched and fix them
+        // by replacing their values with the previously observed values.
+        var fetched = AV._traverse(self._serverData[key], function (object) {
+          if (object instanceof AV.Object && fetchedObjects[object.id]) {
+            return fetchedObjects[object.id];
+          }
+        });
+        if (fetched) {
+          self._serverData[key] = fetched;
+        }
+      });
+      this._rebuildAllEstimatedData();
+      this._saving = this._saving - 1;
+    },
+
+    /**
+     * Called when a fetch or login is complete to set the known server data to
+     * the given object.
+     * @private
+     */
+    _finishFetch: function _finishFetch(serverData, hasData) {
+      // Clear out any changes the user might have made previously.
+      this._opSetQueue = [{}];
+
+      // Bring in all the new server data.
+      this._mergeMagicFields(serverData);
+      var self = this;
+      AV._objectEach(serverData, function (value, key) {
+        self._serverData[key] = AV._decode(value, key);
+      });
+
+      // Refresh the attributes.
+      this._rebuildAllEstimatedData();
+
+      // Clear out the cache of mutable containers.
+      this._refreshCache();
+      this._opSetQueue = [{}];
+
+      this._hasData = hasData;
+    },
+
+    /**
+     * Applies the set of AV.Op in opSet to the object target.
+     * @private
+     */
+    _applyOpSet: function _applyOpSet(opSet, target) {
+      var self = this;
+      AV._objectEach(opSet, function (change, key) {
+        target[key] = change._estimate(target[key], self, key);
+        if (target[key] === AV.Op._UNSET) {
+          delete target[key];
+        }
+      });
+    },
+
+    /**
+     * Replaces the cached value for key with the current value.
+     * Returns true if the new value is different than the old value.
+     * @private
+     */
+    _resetCacheForKey: function _resetCacheForKey(key) {
+      var value = this.attributes[key];
+      if (_.isObject(value) && !(value instanceof AV.Object) && !(value instanceof AV.File)) {
+
+        value = value.toJSON ? value.toJSON() : value;
+        var json = JSON.stringify(value);
+        if (this._hashedJSON[key] !== json) {
+          var wasSet = !!this._hashedJSON[key];
+          this._hashedJSON[key] = json;
+          return wasSet;
+        }
+      }
+      return false;
+    },
+
+    /**
+     * Populates attributes[key] by starting with the last known data from the
+     * server, and applying all of the local changes that have been made to that
+     * key since then.
+     * @private
+     */
+    _rebuildEstimatedDataForKey: function _rebuildEstimatedDataForKey(key) {
+      var self = this;
+      delete this.attributes[key];
+      if (this._serverData[key]) {
+        this.attributes[key] = this._serverData[key];
+      }
+      AV._arrayEach(this._opSetQueue, function (opSet) {
+        var op = opSet[key];
+        if (op) {
+          self.attributes[key] = op._estimate(self.attributes[key], self, key);
+          if (self.attributes[key] === AV.Op._UNSET) {
+            delete self.attributes[key];
+          } else {
+            self._resetCacheForKey(key);
+          }
+        }
+      });
+    },
+
+    /**
+     * Populates attributes by starting with the last known data from the
+     * server, and applying all of the local changes that have been made since
+     * then.
+     * @private
+     */
+    _rebuildAllEstimatedData: function _rebuildAllEstimatedData() {
+      var self = this;
+
+      var previousAttributes = _.clone(this.attributes);
+
+      this.attributes = _.clone(this._serverData);
+      AV._arrayEach(this._opSetQueue, function (opSet) {
+        self._applyOpSet(opSet, self.attributes);
+        AV._objectEach(opSet, function (op, key) {
+          self._resetCacheForKey(key);
+        });
+      });
+
+      // Trigger change events for anything that changed because of the fetch.
+      AV._objectEach(previousAttributes, function (oldValue, key) {
+        if (self.attributes[key] !== oldValue) {
+          self.trigger('change:' + key, self, self.attributes[key], {});
+        }
+      });
+      AV._objectEach(this.attributes, function (newValue, key) {
+        if (!_.has(previousAttributes, key)) {
+          self.trigger('change:' + key, self, newValue, {});
+        }
+      });
+    },
+
+    /**
+     * Sets a hash of model attributes on the object, firing
+     * "change" unless you choose to silence it.
+     *
+     * 

You can call it with an object containing keys and values, or with one + * key and value. For example:

+     *   gameTurn.set({
+     *     player: player1,
+     *     diceRoll: 2
+     *   }, {
+     *     error: function(gameTurnAgain, error) {
+     *       // The set failed validation.
+     *     }
+     *   });
+     *
+     *   game.set("currentPlayer", player2, {
+     *     error: function(gameTurnAgain, error) {
+     *       // The set failed validation.
+     *     }
+     *   });
+     *
+     *   game.set("finished", true);

+ * + * @param {String} key The key to set. + * @param {Any} value The value to give it. + * @param {Object} [options] + * @param {Boolean} [options.silent] + * @return {AV.Object} self if succeeded, throws if the value is not valid. + * @see AV.Object#validate + */ + set: function set(key, value, options) { + var attrs; + if (_.isObject(key) || utils.isNullOrUndefined(key)) { + attrs = _.mapObject(key, function (v, k) { + checkReservedKey(k); + return AV._decode(v, k); + }); + options = value; + } else { + attrs = {}; + checkReservedKey(key); + attrs[key] = AV._decode(value, key); + } + + // Extract attributes and options. + options = options || {}; + if (!attrs) { + return this; + } + if (attrs instanceof AV.Object) { + attrs = attrs.attributes; + } + + // If the unset option is used, every attribute should be a Unset. + if (options.unset) { + AV._objectEach(attrs, function (unused_value, key) { + attrs[key] = new AV.Op.Unset(); + }); + } + + // Apply all the attributes to get the estimated values. + var dataToValidate = _.clone(attrs); + var self = this; + AV._objectEach(dataToValidate, function (value, key) { + if (value instanceof AV.Op) { + dataToValidate[key] = value._estimate(self.attributes[key], self, key); + if (dataToValidate[key] === AV.Op._UNSET) { + delete dataToValidate[key]; + } + } + }); + + // Run validation. + this._validate(attrs, options); + + options.changes = {}; + var escaped = this._escapedAttributes; + var prev = this._previousAttributes || {}; + + // Update attributes. + AV._arrayEach(_.keys(attrs), function (attr) { + var val = attrs[attr]; + + // If this is a relation object we need to set the parent correctly, + // since the location where it was parsed does not have access to + // this object. + if (val instanceof AV.Relation) { + val.parent = self; + } + + if (!(val instanceof AV.Op)) { + val = new AV.Op.Set(val); + } + + // See if this change will actually have any effect. + var isRealChange = true; + if (val instanceof AV.Op.Set && _.isEqual(self.attributes[attr], val.value)) { + isRealChange = false; + } + + if (isRealChange) { + delete escaped[attr]; + if (options.silent) { + self._silent[attr] = true; + } else { + options.changes[attr] = true; + } + } + + var currentChanges = _.last(self._opSetQueue); + currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]); + self._rebuildEstimatedDataForKey(attr); + + if (isRealChange) { + self.changed[attr] = self.attributes[attr]; + if (!options.silent) { + self._pending[attr] = true; + } + } else { + delete self.changed[attr]; + delete self._pending[attr]; + } + }); + + if (!options.silent) { + this.change(options); + } + return this; + }, + + /** + * Remove an attribute from the model, firing "change" unless + * you choose to silence it. This is a noop if the attribute doesn't + * exist. + */ + unset: function unset(attr, options) { + options = options || {}; + options.unset = true; + return this.set(attr, null, options); + }, + + /** + * Atomically increments the value of the given attribute the next time the + * object is saved. If no amount is specified, 1 is used by default. + * + * @param attr {String} The key. + * @param amount {Number} The amount to increment by. + */ + increment: function increment(attr, amount) { + if (_.isUndefined(amount) || _.isNull(amount)) { + amount = 1; + } + return this.set(attr, new AV.Op.Increment(amount)); + }, + + /** + * Atomically add an object to the end of the array associated with a given + * key. + * @param attr {String} The key. + * @param item {} The item to add. + */ + add: function add(attr, item) { + return this.set(attr, new AV.Op.Add(utils.ensureArray(item))); + }, + + /** + * Atomically add an object to the array associated with a given key, only + * if it is not already present in the array. The position of the insert is + * not guaranteed. + * + * @param attr {String} The key. + * @param item {} The object to add. + */ + addUnique: function addUnique(attr, item) { + return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item))); + }, + + /** + * Atomically remove all instances of an object from the array associated + * with a given key. + * + * @param attr {String} The key. + * @param item {} The object to remove. + */ + remove: function remove(attr, item) { + return this.set(attr, new AV.Op.Remove(utils.ensureArray(item))); + }, + + /** + * Returns an instance of a subclass of AV.Op describing what kind of + * modification has been performed on this field since the last time it was + * saved. For example, after calling object.increment("x"), calling + * object.op("x") would return an instance of AV.Op.Increment. + * + * @param attr {String} The key. + * @returns {AV.Op} The operation, or undefined if none. + */ + op: function op(attr) { + return _.last(this._opSetQueue)[attr]; + }, + + /** + * Clear all attributes on the model, firing "change" unless + * you choose to silence it. + */ + clear: function clear(options) { + options = options || {}; + options.unset = true; + var keysToClear = _.extend(this.attributes, this._operations); + return this.set(keysToClear, options); + }, + + /** + * Returns a JSON-encoded set of operations to be sent with the next save + * request. + * @private + */ + _getSaveJSON: function _getSaveJSON() { + var json = _.clone(_.first(this._opSetQueue)); + AV._objectEach(json, function (op, key) { + json[key] = op.toJSON(); + }); + return json; + }, + + /** + * Returns true if this object can be serialized for saving. + * @private + */ + _canBeSerialized: function _canBeSerialized() { + return AV.Object._canBeSerializedAsValue(this.attributes); + }, + + /** + * Fetch the model from the server. If the server's representation of the + * model differs from its current attributes, they will be overriden, + * triggering a "change" event. + * @param {Object} fetchOptions Optional options to set 'keys' and + * 'include' option. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch: function fetch() { + var fetchOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var options = arguments[1]; + + if (_.isArray(fetchOptions.keys)) { + fetchOptions.keys = fetchOptions.keys.join(','); + } + if (_.isArray(fetchOptions.include)) { + fetchOptions.include = fetchOptions.include.join(','); + } + + var self = this; + var request = AVRequest('classes', this.className, this.id, 'GET', fetchOptions, options); + return request.then(function (response) { + self._finishFetch(self.parse(response), true); + return self; + }); + }, + + /** + * Set a hash of model attributes, and save the model to the server. + * updatedAt will be updated when the request returns. + * You can either call it as:
+     *   object.save();
+ * or
+     *   object.save(null, options);
+ * or
+     *   object.save(attrs, options);
+ * or
+     *   object.save(key, value, options);
+ * + * For example,
+     *   gameTurn.save({
+     *     player: "Jake Cutter",
+     *     diceRoll: 2
+     *   }).then(function(gameTurnAgain) {
+     *     // The save was successful.
+     *   }, function(error) {
+     *     // The save failed.  Error is an instance of AVError.
+     *   });
+ * @param {AuthOptions} options AuthOptions plus: + * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded + * @param {AV.Query} options.query Save object only when it matches the query + * @return {AV.Promise} A promise that is fulfilled when the save + * completes. + * @see AVError + */ + save: function save(arg1, arg2, arg3) { + var i, attrs, current, options, saved; + if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) { + attrs = arg1; + options = arg2; + } else { + attrs = {}; + attrs[arg1] = arg2; + options = arg3; + } + + options = _.clone(options) || {}; + if (options.wait) { + current = _.clone(this.attributes); + } + + var setOptions = _.clone(options) || {}; + if (setOptions.wait) { + setOptions.silent = true; + } + if (attrs) { + this.set(attrs, setOptions); + } + + var model = this; + + // If there is any unsaved child, save it first. + model._refreshCache(); + + var unsavedChildren = []; + var unsavedFiles = []; + AV.Object._findUnsavedChildren(model.attributes, unsavedChildren, unsavedFiles); + if (unsavedChildren.length + unsavedFiles.length > 0) { + return AV.Object._deepSaveAsync(this.attributes, model, options).then(function () { + return model.save(null, options); + }); + } + + this._startSave(); + this._saving = (this._saving || 0) + 1; + + this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve(); + this._allPreviousSaves = this._allPreviousSaves.catch(function (e) {}).then(function () { + var method = model.id ? 'PUT' : 'POST'; + + var json = model._getSaveJSON(); + + if (model._fetchWhenSave) { + //Sepcial-case fetchWhenSave when updating object. + json._fetchWhenSave = true; + } + + if (options.fetchWhenSave) { + json._fetchWhenSave = true; + } + if (options.query) { + var queryJSON; + if (typeof options.query.toJSON === 'function') { + queryJSON = options.query.toJSON(); + if (queryJSON) { + json._where = queryJSON.where; + } + } + if (!json._where) { + var error = new Error('options.query is not an AV.Query'); + throw error; + } + } + + _.extend(json, model._flags); + + var route = "classes"; + var className = model.className; + if (model.className === "_User" && !model.id) { + // Special-case user sign-up. + route = "users"; + className = null; + } + //hook makeRequest in options. + var makeRequest = options._makeRequest || AVRequest; + var request = makeRequest(route, className, model.id, method, json, options); + + request = request.then(function (resp) { + var serverAttrs = model.parse(resp); + if (options.wait) { + serverAttrs = _.extend(attrs || {}, serverAttrs); + } + model._finishSave(serverAttrs); + if (options.wait) { + model.set(current, setOptions); + } + return model; + }, function (error) { + model._cancelSave(); + throw error; + }); + + return request; + }); + return this._allPreviousSaves; + }, + + /** + * Destroy this model on the server if it was already persisted. + * Optimistically removes the model from its collection, if it has one. + * @param {AuthOptions} options AuthOptions plus: + * @param {Boolean} [options.wait] wait for the server to respond + * before removal. + * + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + options = options || {}; + var model = this; + + var triggerDestroy = function triggerDestroy() { + model.trigger('destroy', model, model.collection, options); + }; + + if (!this.id) { + return triggerDestroy(); + } + + if (!options.wait) { + triggerDestroy(); + } + + var request = AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options); + return request.then(function () { + if (options.wait) { + triggerDestroy(); + } + return model; + }); + }, + + /** + * Converts a response into the hash of attributes to be set on the model. + * @ignore + */ + parse: function parse(resp) { + var output = _.clone(resp); + _(["createdAt", "updatedAt"]).each(function (key) { + if (output[key]) { + output[key] = AV._parseDate(output[key]); + } + }); + if (!output.updatedAt) { + output.updatedAt = output.createdAt; + } + return output; + }, + + /** + * Creates a new model with identical attributes to this one. + * @return {AV.Object} + */ + clone: function clone() { + return new this.constructor(this.attributes); + }, + + /** + * Returns true if this object has never been saved to AV. + * @return {Boolean} + */ + isNew: function isNew() { + return !this.id; + }, + + /** + * Call this method to manually fire a `"change"` event for this model and + * a `"change:attribute"` event for each changed attribute. + * Calling this will cause all objects observing the model to update. + */ + change: function change(options) { + options = options || {}; + var changing = this._changing; + this._changing = true; + + // Silent changes become pending changes. + var self = this; + AV._objectEach(this._silent, function (attr) { + self._pending[attr] = true; + }); + + // Silent changes are triggered. + var changes = _.extend({}, options.changes, this._silent); + this._silent = {}; + AV._objectEach(changes, function (unused_value, attr) { + self.trigger('change:' + attr, self, self.get(attr), options); + }); + if (changing) { + return this; + } + + // This is to get around lint not letting us make a function in a loop. + var deleteChanged = function deleteChanged(value, attr) { + if (!self._pending[attr] && !self._silent[attr]) { + delete self.changed[attr]; + } + }; + + // Continue firing `"change"` events while there are pending changes. + while (!_.isEmpty(this._pending)) { + this._pending = {}; + this.trigger('change', this, options); + // Pending and silent changes still remain. + AV._objectEach(this.changed, deleteChanged); + self._previousAttributes = _.clone(this.attributes); + } + + this._changing = false; + return this; + }, + + /** + * Determine if the model has changed since the last "change" + * event. If you specify an attribute name, determine if that attribute + * has changed. + * @param {String} attr Optional attribute name + * @return {Boolean} + */ + hasChanged: function hasChanged(attr) { + if (!arguments.length) { + return !_.isEmpty(this.changed); + } + return this.changed && _.has(this.changed, attr); + }, + + /** + * Returns an object containing all the attributes that have changed, or + * false if there are no changed attributes. Useful for determining what + * parts of a view need to be updated and/or what attributes need to be + * persisted to the server. Unset attributes will be set to undefined. + * You can also pass an attributes object to diff against the model, + * determining if there *would be* a change. + */ + changedAttributes: function changedAttributes(diff) { + if (!diff) { + return this.hasChanged() ? _.clone(this.changed) : false; + } + var changed = {}; + var old = this._previousAttributes; + AV._objectEach(diff, function (diffVal, attr) { + if (!_.isEqual(old[attr], diffVal)) { + changed[attr] = diffVal; + } + }); + return changed; + }, + + /** + * Gets the previous value of an attribute, recorded at the time the last + * "change" event was fired. + * @param {String} attr Name of the attribute to get. + */ + previous: function previous(attr) { + if (!arguments.length || !this._previousAttributes) { + return null; + } + return this._previousAttributes[attr]; + }, + + /** + * Gets all of the attributes of the model at the time of the previous + * "change" event. + * @return {Object} + */ + previousAttributes: function previousAttributes() { + return _.clone(this._previousAttributes); + }, + + /** + * Checks if the model is currently in a valid state. It's only possible to + * get into an *invalid* state if you're using silent changes. + * @return {Boolean} + */ + isValid: function isValid() { + try { + this.validate(this.attributes); + } catch (error) { + return false; + } + return true; + }, + + /** + * You should not call this function directly unless you subclass + * AV.Object, in which case you can override this method + * to provide additional validation on set and + * save. Your implementation should throw an Error if + * the attrs is invalid + * + * @param {Object} attrs The current data to validate. + * @see AV.Object#set + */ + validate: function validate(attrs) { + if (_.has(attrs, "ACL") && !(attrs.ACL instanceof AV.ACL)) { + throw new AVError(AVError.OTHER_CAUSE, "ACL must be a AV.ACL."); + } + }, + + /** + * Run validation against a set of incoming attributes, returning `true` + * if all is well. If a specific `error` callback has been passed, + * call that instead of firing the general `"error"` event. + * @private + */ + _validate: function _validate(attrs, options) { + if (options.silent || !this.validate) { + return; + } + attrs = _.extend({}, this.attributes, attrs); + this.validate(attrs); + }, + + /** + * Returns the ACL for this object. + * @returns {AV.ACL} An instance of AV.ACL. + * @see AV.Object#get + */ + getACL: function getACL() { + return this.get("ACL"); + }, + + /** + * Sets the ACL to be used for this object. + * @param {AV.ACL} acl An instance of AV.ACL. + * @param {Object} options Optional Backbone-like options object to be + * passed in to set. + * @return {Boolean} Whether the set passed validation. + * @see AV.Object#set + */ + setACL: function setACL(acl, options) { + return this.set("ACL", acl, options); + }, + + disableBeforeHook: function disableBeforeHook() { + this.ignoreHook('beforeSave'); + this.ignoreHook('beforeUpdate'); + this.ignoreHook('beforeDelete'); + }, + + disableAfterHook: function disableAfterHook() { + this.ignoreHook('afterSave'); + this.ignoreHook('afterUpdate'); + this.ignoreHook('afterDelete'); + }, + + ignoreHook: function ignoreHook(hookName) { + if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) { + console.trace('Unsupported hookName: ' + hookName); + } + + if (!AV.hookKey) { + console.trace('ignoreHook required hookKey'); + } + + if (!this._flags.__ignore_hooks) { + this._flags.__ignore_hooks = []; + } + + this._flags.__ignore_hooks.push(hookName); + } + }); + + /** + * Creates an instance of a subclass of AV.Object for the give classname + * and id. + * @param {String} className The name of the AV class backing this model. + * @param {String} id The object id of this model. + * @return {AV.Object} A new subclass instance of AV.Object. + */ + AV.Object.createWithoutData = function (className, id, hasData) { + var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + result.id = id; + result._hasData = hasData; + return result; + }; + /** + * Delete objects in batch. + * @param {AV.Object[]} objects The AV.Object array to be deleted. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the save + * completes. + */ + AV.Object.destroyAll = function (objects) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!objects || objects.length === 0) { + return AV.Promise.resolve(); + } + var objectsByClassNameAndFlags = _.groupBy(objects, function (object) { + return JSON.stringify({ + className: object.className, + flags: object._flags + }); + }); + var body = { + requests: _.map(objectsByClassNameAndFlags, function (objects) { + var ids = _.map(objects, 'id').join(','); + return { + method: 'DELETE', + path: '/1.1/classes/' + objects[0].className + '/' + ids, + body: objects[0]._flags + }; + }) + }; + return AVRequest('batch', null, null, 'POST', body, options); + }; + + /** + * Returns the appropriate subclass for making new instances of the given + * className string. + * @private + */ + AV.Object._getSubclass = function (className) { + if (!_.isString(className)) { + throw new Error('AV.Object._getSubclass requires a string argument.'); + } + var ObjectClass = AV.Object._classMap[className]; + if (!ObjectClass) { + ObjectClass = AV.Object.extend(className); + AV.Object._classMap[className] = ObjectClass; + } + return ObjectClass; + }; + + /** + * Creates an instance of a subclass of AV.Object for the given classname. + * @private + */ + AV.Object._create = function (className, attributes, options, noDefaultACL) { + var ObjectClass = AV.Object._getSubclass(className); + return new ObjectClass(attributes, options, noDefaultACL); + }; + + // Set up a map of className to class so that we can create new instances of + // AV Objects from JSON automatically. + AV.Object._classMap = {}; + + AV.Object._extend = AV._extend; + + /** + * Creates a new model with defined attributes, + * It's the same with + *
+   *   new AV.Object(attributes, options);
+   *  
+ * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @return {AV.Object} + * @since v0.4.4 + * @see AV.Object + * @see AV.Object.extend + */ + AV.Object['new'] = function (attributes, options) { + return new AV.Object(attributes, options); + }; + + /** + * Creates a new subclass of AV.Object for the given AV class name. + * + *

Every extension of a AV class will inherit from the most recent + * previous extension of that class. When a AV.Object is automatically + * created by parsing JSON, it will use the most recent extension of that + * class.

+ * + *

You should call either:

+   *     var MyClass = AV.Object.extend("MyClass", {
+   *         Instance properties
+   *     }, {
+   *         Class properties
+   *     });
+ * or, for Backbone compatibility:
+   *     var MyClass = AV.Object.extend({
+   *         className: "MyClass",
+   *         Other instance properties
+   *     }, {
+   *         Class properties
+   *     });

+ * + * @param {String} className The name of the AV class backing this model. + * @param {Object} protoProps Instance properties to add to instances of the + * class returned from this method. + * @param {Object} classProps Class properties to add the class returned from + * this method. + * @return {Class} A new subclass of AV.Object. + */ + AV.Object.extend = function (className, protoProps, classProps) { + // Handle the case with only two args. + if (!_.isString(className)) { + if (className && _.has(className, "className")) { + return AV.Object.extend(className.className, className, protoProps); + } else { + throw new Error("AV.Object.extend's first argument should be the className."); + } + } + + // If someone tries to subclass "User", coerce it to the right type. + if (className === "User") { + className = "_User"; + } + + var NewClassObject = null; + if (_.has(AV.Object._classMap, className)) { + var OldClassObject = AV.Object._classMap[className]; + // This new subclass has been told to extend both from "this" and from + // OldClassObject. This is multiple inheritance, which isn't supported. + // For now, let's just pick one. + if (protoProps || classProps) { + NewClassObject = OldClassObject._extend(protoProps, classProps); + } else { + return OldClassObject; + } + } else { + protoProps = protoProps || {}; + protoProps._className = className; + NewClassObject = this._extend(protoProps, classProps); + } + // Extending a subclass should reuse the classname automatically. + NewClassObject.extend = function (arg0) { + if (_.isString(arg0) || arg0 && _.has(arg0, "className")) { + return AV.Object.extend.apply(NewClassObject, arguments); + } + var newArguments = [className].concat(_.toArray(arguments)); + return AV.Object.extend.apply(NewClassObject, newArguments); + }; + NewClassObject['new'] = function (attributes, options) { + return new NewClassObject(attributes, options); + }; + AV.Object._classMap[className] = NewClassObject; + return NewClassObject; + }; + + // ES6 class syntax support + Object.defineProperty(AV.Object.prototype, 'className', { + get: function get() { + var className = this._className || this.constructor._LCClassName || this.constructor.name; + // If someone tries to subclass "User", coerce it to the right type. + if (className === "User") { + return "_User"; + } + return className; + } + }); + + /** + * Register a class. + * If a subclass of AV.Object is defined with your own implement + * rather then AV.Object.extend, the subclass must be registered. + * @param {Function} klass A subclass of AV.Object + * @param {String} [name] Specify the name of the class. Useful when the class might be uglified. + * @example + * class Person extend AV.Object {} + * AV.Object.register(Person); + */ + AV.Object.register = function (klass, name) { + if (!(klass.prototype instanceof AV.Object)) { + throw new Error('registered class is not a subclass of AV.Object'); + } + var className = name || klass.name; + if (!className.length) { + throw new Error('registered class must be named'); + } + if (name) { + klass._LCClassName = name; + } + AV.Object._classMap[className] = klass; + }; + + AV.Object._findUnsavedChildren = function (object, children, files) { + AV._traverse(object, function (object) { + if (object instanceof AV.Object) { + object._refreshCache(); + if (object.dirty()) { + children.push(object); + } + return; + } + + if (object instanceof AV.File) { + if (!object.url() && !object.id) { + files.push(object); + } + return; + } + }); + }; + + AV.Object._canBeSerializedAsValue = function (object) { + var canBeSerializedAsValue = true; + + if (object instanceof AV.Object || object instanceof AV.File) { + canBeSerializedAsValue = !!object.id; + } else if (_.isArray(object)) { + AV._arrayEach(object, function (child) { + if (!AV.Object._canBeSerializedAsValue(child)) { + canBeSerializedAsValue = false; + } + }); + } else if (_.isObject(object)) { + AV._objectEach(object, function (child) { + if (!AV.Object._canBeSerializedAsValue(child)) { + canBeSerializedAsValue = false; + } + }); + } + + return canBeSerializedAsValue; + }; + + AV.Object._deepSaveAsync = function (object, model, options) { + var unsavedChildren = []; + var unsavedFiles = []; + AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles); + if (model) { + unsavedChildren = _.filter(unsavedChildren, function (object) { + return object != model; + }); + } + + var promise = AV.Promise.resolve(); + _.each(unsavedFiles, function (file) { + promise = promise.then(function () { + return file.save(); + }); + }); + + var objects = _.uniq(unsavedChildren); + var remaining = _.uniq(objects); + + return promise.then(function () { + return AV.Promise._continueWhile(function () { + return remaining.length > 0; + }, function () { + + // Gather up all the objects that can be saved in this batch. + var batch = []; + var newRemaining = []; + AV._arrayEach(remaining, function (object) { + // Limit batches to 20 objects. + if (batch.length > 20) { + newRemaining.push(object); + return; + } + + if (object._canBeSerialized()) { + batch.push(object); + } else { + newRemaining.push(object); + } + }); + remaining = newRemaining; + + // If we can't save any objects, there must be a circular reference. + if (batch.length === 0) { + return AV.Promise.reject(new AVError(AVError.OTHER_CAUSE, "Tried to save a batch with a cycle.")); + } + + // Reserve a spot in every object's save queue. + var readyToStart = AV.Promise.resolve(_.map(batch, function (object) { + return object._allPreviousSaves || AV.Promise.resolve(); + })); + + // Save a single batch, whether previous saves succeeded or failed. + var bathSavePromise = readyToStart.then(function () { + return AVRequest("batch", null, null, "POST", { + requests: _.map(batch, function (object) { + var json = object._getSaveJSON(); + _.extend(json, object._flags); + var method = "POST"; + + var path = "/1.1/classes/" + object.className; + if (object.id) { + path = path + "/" + object.id; + method = "PUT"; + } + + object._startSave(); + + return { + method: method, + path: path, + body: json + }; + }) + + }, options).then(function (response) { + var error; + AV._arrayEach(batch, function (object, i) { + if (response[i].success) { + object._finishSave(object.parse(response[i].success)); + } else { + error = error || response[i].error; + object._cancelSave(); + } + }); + if (error) { + return AV.Promise.reject(new AVError(error.code, error.error)); + } + }); + }); + AV._arrayEach(batch, function (object) { + object._allPreviousSaves = bathSavePromise; + }); + return bathSavePromise; + }); + }).then(function () { + return object; + }); + }; +}; + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + + /** + * @private + * @class + * A AV.Op is an atomic operation that can be applied to a field in a + * AV.Object. For example, calling object.set("foo", "bar") + * is an example of a AV.Op.Set. Calling object.unset("foo") + * is a AV.Op.Unset. These operations are stored in a AV.Object and + * sent to the server as part of object.save() operations. + * Instances of AV.Op should be immutable. + * + * You should not create subclasses of AV.Op or instantiate AV.Op + * directly. + */ + AV.Op = function () { + this._initialize.apply(this, arguments); + }; + + AV.Op.prototype = { + _initialize: function _initialize() {} + }; + + _.extend(AV.Op, { + /** + * To create a new Op, call AV.Op._extend(); + * @private + */ + _extend: AV._extend, + + // A map of __op string to decoder function. + _opDecoderMap: {}, + + /** + * Registers a function to convert a json object with an __op field into an + * instance of a subclass of AV.Op. + * @private + */ + _registerDecoder: function _registerDecoder(opName, decoder) { + AV.Op._opDecoderMap[opName] = decoder; + }, + + /** + * Converts a json object into an instance of a subclass of AV.Op. + * @private + */ + _decode: function _decode(json) { + var decoder = AV.Op._opDecoderMap[json.__op]; + if (decoder) { + return decoder(json); + } else { + return undefined; + } + } + }); + + /* + * Add a handler for Batch ops. + */ + AV.Op._registerDecoder("Batch", function (json) { + var op = null; + AV._arrayEach(json.ops, function (nextOp) { + nextOp = AV.Op._decode(nextOp); + op = nextOp._mergeWithPrevious(op); + }); + return op; + }); + + /** + * @private + * @class + * A Set operation indicates that either the field was changed using + * AV.Object.set, or it is a mutable container that was detected as being + * changed. + */ + AV.Op.Set = AV.Op._extend( /** @lends AV.Op.Set.prototype */{ + _initialize: function _initialize(value) { + this._value = value; + }, + + /** + * Returns the new value of this field after the set. + */ + value: function value() { + return this._value; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return AV._encode(this.value()); + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + return this; + }, + + _estimate: function _estimate(oldValue) { + return this.value(); + } + }); + + /** + * A sentinel value that is returned by AV.Op.Unset._estimate to + * indicate the field should be deleted. Basically, if you find _UNSET as a + * value in your object, you should remove that key. + */ + AV.Op._UNSET = {}; + + /** + * @private + * @class + * An Unset operation indicates that this field has been deleted from the + * object. + */ + AV.Op.Unset = AV.Op._extend( /** @lends AV.Op.Unset.prototype */{ + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Delete" }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + return this; + }, + + _estimate: function _estimate(oldValue) { + return AV.Op._UNSET; + } + }); + + AV.Op._registerDecoder("Delete", function (json) { + return new AV.Op.Unset(); + }); + + /** + * @private + * @class + * An Increment is an atomic operation where the numeric value for the field + * will be increased by a given amount. + */ + AV.Op.Increment = AV.Op._extend( + /** @lends AV.Op.Increment.prototype */{ + + _initialize: function _initialize(amount) { + this._amount = amount; + }, + + /** + * Returns the amount to increment by. + * @return {Number} the amount to increment by. + */ + amount: function amount() { + return this._amount; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Increment", amount: this._amount }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.amount()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(previous.value() + this.amount()); + } else if (previous instanceof AV.Op.Increment) { + return new AV.Op.Increment(this.amount() + previous.amount()); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return this.amount(); + } + return oldValue + this.amount(); + } + }); + + AV.Op._registerDecoder("Increment", function (json) { + return new AV.Op.Increment(json.amount); + }); + + /** + * @private + * @class + * Add is an atomic operation where the given objects will be appended to the + * array that is stored in this field. + */ + AV.Op.Add = AV.Op._extend( /** @lends AV.Op.Add.prototype */{ + _initialize: function _initialize(objects) { + this._objects = objects; + }, + + /** + * Returns the objects to be added to the array. + * @return {Array} The objects to be added to the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Add", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.objects()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.Add) { + return new AV.Op.Add(previous.objects().concat(this.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return _.clone(this.objects()); + } else { + return oldValue.concat(this.objects()); + } + } + }); + + AV.Op._registerDecoder("Add", function (json) { + return new AV.Op.Add(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * AddUnique is an atomic operation where the given items will be appended to + * the array that is stored in this field only if they were not already + * present in the array. + */ + AV.Op.AddUnique = AV.Op._extend( + /** @lends AV.Op.AddUnique.prototype */{ + + _initialize: function _initialize(objects) { + this._objects = _.uniq(objects); + }, + + /** + * Returns the objects to be added to the array. + * @return {Array} The objects to be added to the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "AddUnique", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.objects()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.AddUnique) { + return new AV.Op.AddUnique(this._estimate(previous.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return _.clone(this.objects()); + } else { + // We can't just take the _.uniq(_.union(...)) of oldValue and + // this.objects, because the uniqueness may not apply to oldValue + // (especially if the oldValue was set via .set()) + var newValue = _.clone(oldValue); + AV._arrayEach(this.objects(), function (obj) { + if (obj instanceof AV.Object && obj.id) { + var matchingObj = _.find(newValue, function (anObj) { + return anObj instanceof AV.Object && anObj.id === obj.id; + }); + if (!matchingObj) { + newValue.push(obj); + } else { + var index = _.indexOf(newValue, matchingObj); + newValue[index] = obj; + } + } else if (!_.contains(newValue, obj)) { + newValue.push(obj); + } + }); + return newValue; + } + } + }); + + AV.Op._registerDecoder("AddUnique", function (json) { + return new AV.Op.AddUnique(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * Remove is an atomic operation where the given objects will be removed from + * the array that is stored in this field. + */ + AV.Op.Remove = AV.Op._extend( /** @lends AV.Op.Remove.prototype */{ + _initialize: function _initialize(objects) { + this._objects = _.uniq(objects); + }, + + /** + * Returns the objects to be removed from the array. + * @return {Array} The objects to be removed from the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Remove", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return previous; + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.Remove) { + return new AV.Op.Remove(_.union(previous.objects(), this.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return []; + } else { + var newValue = _.difference(oldValue, this.objects()); + // If there are saved AV Objects being removed, also remove them. + AV._arrayEach(this.objects(), function (obj) { + if (obj instanceof AV.Object && obj.id) { + newValue = _.reject(newValue, function (other) { + return other instanceof AV.Object && other.id === obj.id; + }); + } + }); + return newValue; + } + } + }); + + AV.Op._registerDecoder("Remove", function (json) { + return new AV.Op.Remove(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * A Relation operation indicates that the field is an instance of + * AV.Relation, and objects are being added to, or removed from, that + * relation. + */ + AV.Op.Relation = AV.Op._extend( + /** @lends AV.Op.Relation.prototype */{ + + _initialize: function _initialize(adds, removes) { + this._targetClassName = null; + + var self = this; + + var pointerToId = function pointerToId(object) { + if (object instanceof AV.Object) { + if (!object.id) { + throw new Error('You can\'t add an unsaved AV.Object to a relation.'); + } + if (!self._targetClassName) { + self._targetClassName = object.className; + } + if (self._targetClassName !== object.className) { + throw new Error("Tried to create a AV.Relation with 2 different types: " + self._targetClassName + " and " + object.className + "."); + } + return object.id; + } + return object; + }; + + this.relationsToAdd = _.uniq(_.map(adds, pointerToId)); + this.relationsToRemove = _.uniq(_.map(removes, pointerToId)); + }, + + /** + * Returns an array of unfetched AV.Object that are being added to the + * relation. + * @return {Array} + */ + added: function added() { + var self = this; + return _.map(this.relationsToAdd, function (objectId) { + var object = AV.Object._create(self._targetClassName); + object.id = objectId; + return object; + }); + }, + + /** + * Returns an array of unfetched AV.Object that are being removed from + * the relation. + * @return {Array} + */ + removed: function removed() { + var self = this; + return _.map(this.relationsToRemove, function (objectId) { + var object = AV.Object._create(self._targetClassName); + object.id = objectId; + return object; + }); + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + var adds = null; + var removes = null; + var self = this; + var idToPointer = function idToPointer(id) { + return { __type: 'Pointer', + className: self._targetClassName, + objectId: id }; + }; + var pointers = null; + if (this.relationsToAdd.length > 0) { + pointers = _.map(this.relationsToAdd, idToPointer); + adds = { "__op": "AddRelation", "objects": pointers }; + } + + if (this.relationsToRemove.length > 0) { + pointers = _.map(this.relationsToRemove, idToPointer); + removes = { "__op": "RemoveRelation", "objects": pointers }; + } + + if (adds && removes) { + return { "__op": "Batch", "ops": [adds, removes] }; + } + + return adds || removes || {}; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + throw new Error('You can\'t modify a relation after deleting it.'); + } else if (previous instanceof AV.Op.Relation) { + if (previous._targetClassName && previous._targetClassName !== this._targetClassName) { + throw new Error("Related object must be of class " + previous._targetClassName + ", but " + this._targetClassName + " was passed in."); + } + var newAdd = _.union(_.difference(previous.relationsToAdd, this.relationsToRemove), this.relationsToAdd); + var newRemove = _.union(_.difference(previous.relationsToRemove, this.relationsToAdd), this.relationsToRemove); + + var newRelation = new AV.Op.Relation(newAdd, newRemove); + newRelation._targetClassName = this._targetClassName; + return newRelation; + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue, object, key) { + if (!oldValue) { + var relation = new AV.Relation(object, key); + relation.targetClassName = this._targetClassName; + } else if (oldValue instanceof AV.Relation) { + if (this._targetClassName) { + if (oldValue.targetClassName) { + if (oldValue.targetClassName !== this._targetClassName) { + throw new Error("Related object must be a " + oldValue.targetClassName + ", but a " + this._targetClassName + " was passed in."); + } + } else { + oldValue.targetClassName = this._targetClassName; + } + } + return oldValue; + } else { + throw new Error('Op is invalid after previous op.'); + } + } + }); + + AV.Op._registerDecoder("AddRelation", function (json) { + return new AV.Op.Relation(AV._decode(json.objects), []); + }); + AV.Op._registerDecoder("RemoveRelation", function (json) { + return new AV.Op.Relation([], AV._decode(json.objects)); + }); +}; + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + AV.Installation = AV.Object.extend("_Installation"); + + /** + * @namespace + */ + AV.Push = AV.Push || {}; + + /** + * Sends a push notification. + * @param {Object} data The data of the push notification. + * @param {String[]} [data.channels] An Array of channels to push to. + * @param {Date} [data.push_time] A Date object for when to send the push. + * @param {Date} [data.expiration_time] A Date object for when to expire + * the push. + * @param {Number} [data.expiration_interval] The seconds from now to expire the push. + * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match + * a set of installations to push to. + * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match + * a set of installations to push to. + * @param {Date} data.data The data to send as part of the push + * @param {AuthOptions} [options] + * @return {Promise} + */ + AV.Push.send = function (data, options) { + if (data.where) { + data.where = data.where.toJSON().where; + } + + if (data.where && data.cql) { + throw new Error("Both where and cql can't be set"); + } + + if (data.push_time) { + data.push_time = data.push_time.toJSON(); + } + + if (data.expiration_time) { + data.expiration_time = data.expiration_time.toJSON(); + } + + if (data.expiration_time && data.expiration_time_interval) { + throw new Error("Both expiration_time and expiration_time_interval can't be set"); + } + + var request = AVRequest('push', null, null, 'POST', data, options); + return request; + }; +}; + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var debug = __webpack_require__(5)('leancloud:query'); +var Promise = __webpack_require__(1); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; + +var _require = __webpack_require__(4), + ensureArray = _require.ensureArray; + +var requires = function requires(value, message) { + if (value === undefined) { + throw new Error(message); + } +}; + +// AV.Query is a way to create a list of AV.Objects. +module.exports = function (AV) { + /** + * Creates a new AV.Query for the given AV.Object subclass. + * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string. + * @class + * + *

AV.Query defines a query that is used to fetch AV.Objects. The + * most common use case is finding all objects that match a query through the + * find method. For example, this sample code fetches all objects + * of class MyClass. It calls a different function depending on + * whether the fetch succeeded or not. + * + *

+   * var query = new AV.Query(MyClass);
+   * query.find().then(function(results) {
+   *   // results is an array of AV.Object.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ * + *

An AV.Query can also be used to retrieve a single object whose id is + * known, through the get method. For example, this sample code fetches an + * object of class MyClass and id myId. It calls a + * different function depending on whether the fetch succeeded or not. + * + *

+   * var query = new AV.Query(MyClass);
+   * query.get(myId).then(function(object) {
+   *   // object is an instance of AV.Object.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ * + *

An AV.Query can also be used to count the number of objects that match + * the query without retrieving all of those objects. For example, this + * sample code counts the number of objects of the class MyClass + *

+   * var query = new AV.Query(MyClass);
+   * query.count().then(function(number) {
+   *   // There are number instances of MyClass.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ */ + AV.Query = function (objectClass) { + if (_.isString(objectClass)) { + objectClass = AV.Object._getSubclass(objectClass); + } + + this.objectClass = objectClass; + + this.className = objectClass.prototype.className; + + this._where = {}; + this._include = []; + this._select = []; + this._limit = -1; // negative limit means, do not send a limit + this._skip = 0; + this._extraOptions = {}; + }; + + /** + * Constructs a AV.Query that is the OR of the passed in queries. For + * example: + *
var compoundQuery = AV.Query.or(query1, query2, query3);
+ * + * will create a compoundQuery that is an or of the query1, query2, and + * query3. + * @param {...AV.Query} var_args The list of queries to OR. + * @return {AV.Query} The query that is the OR of the passed in queries. + */ + AV.Query.or = function () { + var queries = _.toArray(arguments); + var className = null; + AV._arrayEach(queries, function (q) { + if (_.isNull(className)) { + className = q.className; + } + + if (className !== q.className) { + throw new Error('All queries must be for the same class'); + } + }); + var query = new AV.Query(className); + query._orQuery(queries); + return query; + }; + + /** + * Constructs a AV.Query that is the AND of the passed in queries. For + * example: + *
var compoundQuery = AV.Query.and(query1, query2, query3);
+ * + * will create a compoundQuery that is an 'and' of the query1, query2, and + * query3. + * @param {...AV.Query} var_args The list of queries to AND. + * @return {AV.Query} The query that is the AND of the passed in queries. + */ + AV.Query.and = function () { + var queries = _.toArray(arguments); + var className = null; + AV._arrayEach(queries, function (q) { + if (_.isNull(className)) { + className = q.className; + } + + if (className !== q.className) { + throw new Error('All queries must be for the same class'); + } + }); + var query = new AV.Query(className); + query._andQuery(queries); + return query; + }; + + /** + * Retrieves a list of AVObjects that satisfy the CQL. + * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}. + * + * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}. + * @param {Array} pvalues An array contains placeholder values. + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the results when + * the query completes. + */ + AV.Query.doCloudQuery = function (cql, pvalues, options) { + var params = { cql: cql }; + if (_.isArray(pvalues)) { + params.pvalues = pvalues; + } else { + options = pvalues; + } + + var request = AVRequest('cloudQuery', null, null, 'GET', params, options); + return request.then(function (response) { + //query to process results. + var query = new AV.Query(response.className); + var results = _.map(response.results, function (json) { + var obj = query._newObject(response); + if (obj._finishFetch) { + obj._finishFetch(query._processResult(json), true); + } + return obj; + }); + return { + results: results, + count: response.count, + className: response.className + }; + }); + }; + + AV.Query._extend = AV._extend; + + AV.Query.prototype = { + //hook to iterate result. Added by dennis. + _processResult: function _processResult(obj) { + return obj; + }, + + /** + * Constructs an AV.Object whose id is already known by fetching data from + * the server. + * + * @param {String} objectId The id of the object to be fetched. + * @param {AuthOptions} options + * @return {Promise.} + */ + get: function get(objectId, options) { + if (!objectId) { + var errorObject = new AVError(AVError.OBJECT_NOT_FOUND, "Object not found."); + throw errorObject; + } + + var self = this; + + var obj = self._newObject(); + obj.id = objectId; + + var queryJSON = self.toJSON(); + var fetchOptions = {}; + + if (queryJSON.keys) fetchOptions.keys = queryJSON.keys; + if (queryJSON.include) fetchOptions.include = queryJSON.include; + + return obj.fetch(fetchOptions, options); + }, + + /** + * Returns a JSON representation of this query. + * @return {Object} + */ + toJSON: function toJSON() { + var params = { + where: this._where + }; + + if (this._include.length > 0) { + params.include = this._include.join(","); + } + if (this._select.length > 0) { + params.keys = this._select.join(","); + } + if (this._limit >= 0) { + params.limit = this._limit; + } + if (this._skip > 0) { + params.skip = this._skip; + } + if (this._order !== undefined) { + params.order = this._order; + } + + AV._objectEach(this._extraOptions, function (v, k) { + params[k] = v; + }); + + return params; + }, + + _newObject: function _newObject(response) { + var obj; + if (response && response.className) { + obj = new AV.Object(response.className); + } else { + obj = new this.objectClass(); + } + return obj; + }, + _createRequest: function _createRequest() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.toJSON(); + var options = arguments[1]; + + if (JSON.stringify(params).length > 2000) { + var body = { + requests: [{ + method: 'GET', + path: '/1.1/classes/' + this.className, + params: params + }] + }; + return AVRequest('batch', null, null, 'POST', body, options).then(function (response) { + var result = response[0]; + if (result.success) { + return result.success; + } + var error = new Error(result.error.error || 'Unknown batch error'); + error.code = result.error.code; + throw error; + }); + } + return AVRequest('classes', this.className, null, "GET", params, options); + }, + _parseResponse: function _parseResponse(response) { + var _this = this; + + return _.map(response.results, function (json) { + var obj = _this._newObject(response); + if (obj._finishFetch) { + obj._finishFetch(_this._processResult(json), true); + } + return obj; + }); + }, + + + /** + * Retrieves a list of AVObjects that satisfy this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the results when + * the query completes. + */ + find: function find(options) { + var request = this._createRequest(undefined, options); + return request.then(this._parseResponse.bind(this)); + }, + + + /** + * scan a Query. masterKey required. + * + * @since 2.1.0 + * @param {object} [options] + * @param {string} [options.orderedBy] specify the key to sort + * @param {number} [options.batchSize] specify the batch size for each request + * @param {AuthOptions} [authOptions] + * @return {AsyncIterator.} + * @example const scan = new AV.Query(TestClass).scan({ + * orderedBy: 'objectId', + * batchSize: 10, + * }, { + * useMasterKey: true, + * }); + * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next())); + * getTen().then(results => { + * // results are fisrt 10 instances of TestClass + * return getTen(); + * }).then(results => { + * // 11 - 20 + * }); + */ + scan: function scan() { + var _this2 = this; + + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + orderedBy = _ref.orderedBy, + batchSize = _ref.batchSize; + + var authOptions = arguments[1]; + + var condition = this.toJSON(); + debug('scan %O', condition); + if (condition.order) { + console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.'); + delete condition.order; + } + if (condition.skip) { + console.warn('The skip option of the query is ignored for Query#scan.'); + delete condition.skip; + } + if (condition.limit) { + console.warn('The limit option of the query is ignored for Query#scan.'); + delete condition.limit; + } + if (orderedBy) condition.scan_key = orderedBy; + if (batchSize) condition.limit = batchSize; + var promise = Promise.resolve([]); + var cursor = void 0; + var done = false; + return { + next: function next() { + promise = promise.then(function (remainResults) { + if (done) return []; + if (remainResults.length > 1) return remainResults; + // no cursor means we have reached the end + // except for the first time + if (!cursor && remainResults.length !== 0) { + done = true; + return remainResults; + } + // when only 1 item left in queue + // start the next request to see if it is the last one + return AVRequest('scan/classes', _this2.className, null, 'GET', cursor ? _.extend({}, condition, { cursor: cursor }) : condition, authOptions).then(function (response) { + cursor = response.cursor; + return _this2._parseResponse(response); + }).then(function (results) { + if (!results.length) done = true; + return remainResults.concat(results); + }); + }); + return promise.then(function (remainResults) { + return remainResults.shift(); + }).then(function (result) { + return { + value: result, + done: done + }; + }); + } + }; + }, + + + /** + * Delete objects retrieved by this query. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the save + * completes. + */ + destroyAll: function destroyAll(options) { + var self = this; + return self.find(options).then(function (objects) { + return AV.Object.destroyAll(objects, options); + }); + }, + + /** + * Counts the number of objects that match this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the count when + * the query completes. + */ + count: function count(options) { + var params = this.toJSON(); + params.limit = 0; + params.count = 1; + var request = this._createRequest(params, options); + + return request.then(function (response) { + return response.count; + }); + }, + + /** + * Retrieves at most one AV.Object that satisfies this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the object when + * the query completes. + */ + first: function first(options) { + var self = this; + + var params = this.toJSON(); + params.limit = 1; + var request = this._createRequest(params, options); + + return request.then(function (response) { + return _.map(response.results, function (json) { + var obj = self._newObject(); + if (obj._finishFetch) { + obj._finishFetch(self._processResult(json), true); + } + return obj; + })[0]; + }); + }, + + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * @param {Number} n the number of results to skip. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + skip: function skip(n) { + requires(n, 'undefined is not a valid skip value'); + this._skip = n; + return this; + }, + + /** + * Sets the limit of the number of results to return. The default limit is + * 100, with a maximum of 1000 results being returned at a time. + * @param {Number} n the number of results to limit to. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + limit: function limit(n) { + requires(n, 'undefined is not a valid limit value'); + this._limit = n; + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be equal to the provided value. + * @param {String} key The key to check. + * @param value The value that the AV.Object must contain. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + equalTo: function equalTo(key, value) { + requires(key, 'undefined is not a valid key'); + requires(value, 'undefined is not a valid value'); + this._where[key] = AV._encode(value); + return this; + }, + + /** + * Helper for condition queries + * @private + */ + _addCondition: function _addCondition(key, condition, value) { + requires(key, 'undefined is not a valid condition key'); + requires(condition, 'undefined is not a valid condition'); + requires(value, 'undefined is not a valid condition value'); + + // Check if we already have a condition + if (!this._where[key]) { + this._where[key] = {}; + } + this._where[key][condition] = AV._encode(value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular + * array key's length to be equal to the provided value. + * @param {String} key The array key to check. + * @param value The length value. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + sizeEqualTo: function sizeEqualTo(key, value) { + this._addCondition(key, "$size", value); + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be not equal to the provided value. + * @param {String} key The key to check. + * @param value The value that must not be equalled. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + notEqualTo: function notEqualTo(key, value) { + this._addCondition(key, "$ne", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than the provided value. + * @param {String} key The key to check. + * @param value The value that provides an upper bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + lessThan: function lessThan(key, value) { + this._addCondition(key, "$lt", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than the provided value. + * @param {String} key The key to check. + * @param value The value that provides an lower bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + greaterThan: function greaterThan(key, value) { + this._addCondition(key, "$gt", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than or equal to the provided value. + * @param {String} key The key to check. + * @param value The value that provides an upper bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + lessThanOrEqualTo: function lessThanOrEqualTo(key, value) { + this._addCondition(key, "$lte", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than or equal to the provided value. + * @param {String} key The key to check. + * @param value The value that provides an lower bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + greaterThanOrEqualTo: function greaterThanOrEqualTo(key, value) { + this._addCondition(key, "$gte", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be contained in the provided list of values. + * @param {String} key The key to check. + * @param {Array} values The values that will match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + containedIn: function containedIn(key, values) { + this._addCondition(key, "$in", values); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * not be contained in the provided list of values. + * @param {String} key The key to check. + * @param {Array} values The values that will not match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + notContainedIn: function notContainedIn(key, values) { + this._addCondition(key, "$nin", values); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * contain each one of the provided list of values. + * @param {String} key The key to check. This key's value must be an array. + * @param {Array} values The values that will match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + containsAll: function containsAll(key, values) { + this._addCondition(key, "$all", values); + return this; + }, + + /** + * Add a constraint for finding objects that contain the given key. + * @param {String} key The key that should exist. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + exists: function exists(key) { + this._addCondition(key, "$exists", true); + return this; + }, + + /** + * Add a constraint for finding objects that do not contain a given key. + * @param {String} key The key that should not exist + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotExist: function doesNotExist(key) { + this._addCondition(key, "$exists", false); + return this; + }, + + /** + * Add a regular expression constraint for finding string values that match + * the provided regular expression. + * This may be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {RegExp} regex The regular expression pattern to match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matches: function matches(key, regex, modifiers) { + this._addCondition(key, "$regex", regex); + if (!modifiers) { + modifiers = ""; + } + // Javascript regex options support mig as inline options but store them + // as properties of the object. We support mi & should migrate them to + // modifiers + if (regex.ignoreCase) { + modifiers += 'i'; + } + if (regex.multiline) { + modifiers += 'm'; + } + + if (modifiers && modifiers.length) { + this._addCondition(key, "$options", modifiers); + } + return this; + }, + + /** + * Add a constraint that requires that a key's value matches a AV.Query + * constraint. + * @param {String} key The key that the contains the object to match the + * query. + * @param {AV.Query} query The query that should match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matchesQuery: function matchesQuery(key, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$inQuery", queryJSON); + return this; + }, + + /** + * Add a constraint that requires that a key's value not matches a + * AV.Query constraint. + * @param {String} key The key that the contains the object to match the + * query. + * @param {AV.Query} query The query that should not match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotMatchQuery: function doesNotMatchQuery(key, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$notInQuery", queryJSON); + return this; + }, + + /** + * Add a constraint that requires that a key's value matches a value in + * an object returned by a different AV.Query. + * @param {String} key The key that contains the value that is being + * matched. + * @param {String} queryKey The key in the objects returned by the query to + * match against. + * @param {AV.Query} query The query to run. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matchesKeyInQuery: function matchesKeyInQuery(key, queryKey, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$select", { key: queryKey, query: queryJSON }); + return this; + }, + + /** + * Add a constraint that requires that a key's value not match a value in + * an object returned by a different AV.Query. + * @param {String} key The key that contains the value that is being + * excluded. + * @param {String} queryKey The key in the objects returned by the query to + * match against. + * @param {AV.Query} query The query to run. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotMatchKeyInQuery: function doesNotMatchKeyInQuery(key, queryKey, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$dontSelect", { key: queryKey, query: queryJSON }); + return this; + }, + + /** + * Add constraint that at least one of the passed in queries matches. + * @param {Array} queries + * @return {AV.Query} Returns the query, so you can chain this call. + * @private + */ + _orQuery: function _orQuery(queries) { + var queryJSON = _.map(queries, function (q) { + return q.toJSON().where; + }); + + this._where.$or = queryJSON; + return this; + }, + + /** + * Add constraint that both of the passed in queries matches. + * @param {Array} queries + * @return {AV.Query} Returns the query, so you can chain this call. + * @private + */ + _andQuery: function _andQuery(queries) { + var queryJSON = _.map(queries, function (q) { + return q.toJSON().where; + }); + + this._where.$and = queryJSON; + return this; + }, + + /** + * Converts a string into a regex that matches it. + * Surrounding with \Q .. \E does this, we just need to escape \E's in + * the text separately. + * @private + */ + _quote: function _quote(s) { + return "\\Q" + s.replace("\\E", "\\E\\\\E\\Q") + "\\E"; + }, + + /** + * Add a constraint for finding string values that contain a provided + * string. This may be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} substring The substring that the value must contain. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + contains: function contains(key, value) { + this._addCondition(key, "$regex", this._quote(value)); + return this; + }, + + /** + * Add a constraint for finding string values that start with a provided + * string. This query will use the backend index, so it will be fast even + * for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} prefix The substring that the value must start with. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + startsWith: function startsWith(key, value) { + this._addCondition(key, "$regex", "^" + this._quote(value)); + return this; + }, + + /** + * Add a constraint for finding string values that end with a provided + * string. This will be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} suffix The substring that the value must end with. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + endsWith: function endsWith(key, value) { + this._addCondition(key, "$regex", this._quote(value) + "$"); + return this; + }, + + /** + * Sorts the results in ascending order by the given key. + * + * @param {String} key The key to order by. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + ascending: function ascending(key) { + requires(key, 'undefined is not a valid key'); + this._order = key; + return this; + }, + + /** + * Also sorts the results in ascending order by the given key. The previous sort keys have + * precedence over this key. + * + * @param {String} key The key to order by + * @return {AV.Query} Returns the query so you can chain this call. + */ + addAscending: function addAscending(key) { + requires(key, 'undefined is not a valid key'); + if (this._order) this._order += ',' + key;else this._order = key; + return this; + }, + + /** + * Sorts the results in descending order by the given key. + * + * @param {String} key The key to order by. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + descending: function descending(key) { + requires(key, 'undefined is not a valid key'); + this._order = "-" + key; + return this; + }, + + /** + * Also sorts the results in descending order by the given key. The previous sort keys have + * precedence over this key. + * + * @param {String} key The key to order by + * @return {AV.Query} Returns the query so you can chain this call. + */ + addDescending: function addDescending(key) { + requires(key, 'undefined is not a valid key'); + if (this._order) this._order += ',-' + key;else this._order = '-' + key; + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + near: function near(key, point) { + if (!(point instanceof AV.GeoPoint)) { + // Try to cast it to a GeoPoint, so that near("loc", [20,30]) works. + point = new AV.GeoPoint(point); + } + this._addCondition(key, "$nearSphere", point); + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param maxDistance Maximum distance (in radians) of results to return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinRadians: function withinRadians(key, point, distance) { + this.near(key, point); + this._addCondition(key, "$maxDistance", distance); + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 3958.8 miles. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Number} maxDistance Maximum distance (in miles) of results to + * return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinMiles: function withinMiles(key, point, distance) { + return this.withinRadians(key, point, distance / 3958.8); + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 6371.0 kilometers. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Number} maxDistance Maximum distance (in kilometers) of results + * to return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinKilometers: function withinKilometers(key, point, distance) { + return this.withinRadians(key, point, distance / 6371.0); + }, + + /** + * Add a constraint to the query that requires a particular key's + * coordinates be contained within a given rectangular geographic bounding + * box. + * @param {String} key The key to be constrained. + * @param {AV.GeoPoint} southwest + * The lower-left inclusive corner of the box. + * @param {AV.GeoPoint} northeast + * The upper-right inclusive corner of the box. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinGeoBox: function withinGeoBox(key, southwest, northeast) { + if (!(southwest instanceof AV.GeoPoint)) { + southwest = new AV.GeoPoint(southwest); + } + if (!(northeast instanceof AV.GeoPoint)) { + northeast = new AV.GeoPoint(northeast); + } + this._addCondition(key, '$within', { '$box': [southwest, northeast] }); + return this; + }, + + /** + * Include nested AV.Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetch. + * @param {String[]} keys The name of the key to include. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + include: function include(keys) { + var _this3 = this; + + requires(keys, 'undefined is not a valid key'); + _(arguments).forEach(function (keys) { + _this3._include = _this3._include.concat(ensureArray(keys)); + }); + return this; + }, + + /** + * Restrict the fields of the returned AV.Objects to include only the + * provided keys. If this is called multiple times, then all of the keys + * specified in each of the calls will be included. + * @param {String[]} keys The names of the keys to include. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + select: function select(keys) { + var _this4 = this; + + requires(keys, 'undefined is not a valid key'); + _(arguments).forEach(function (keys) { + _this4._select = _this4._select.concat(ensureArray(keys)); + }); + return this; + }, + + /** + * Iterates over each result of a query, calling a callback for each one. If + * the callback returns a promise, the iteration will not continue until + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are + * processed in an unspecified order. The query may not have any sort order, + * and may not use limit or skip. + * @param callback {Function} Callback that will be called with each result + * of the query. + * @return {Promise} A promise that will be fulfilled once the + * iteration has completed. + */ + each: function each(callback) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + + if (this._order || this._skip || this._limit >= 0) { + var error = new Error("Cannot iterate on a query with sort, skip, or limit."); + return AV.Promise.reject(error); + } + + var query = new AV.Query(this.objectClass); + // We can override the batch size from the options. + // This is undocumented, but useful for testing. + query._limit = options.batchSize || 100; + query._where = _.clone(this._where); + query._include = _.clone(this._include); + + query.ascending('objectId'); + + var finished = false; + return AV.Promise._continueWhile(function () { + return !finished; + }, function () { + return query.find(options).then(function (results) { + var callbacksDone = AV.Promise.resolve(); + _.each(results, function (result) { + callbacksDone = callbacksDone.then(function () { + return callback(result); + }); + }); + + return callbacksDone.then(function () { + if (results.length >= query._limit) { + query.greaterThan("objectId", results[results.length - 1].id); + } else { + finished = true; + } + }); + }); + }); + } + }; + + AV.FriendShipQuery = AV.Query._extend({ + _objectClass: AV.User, + _newObject: function _newObject() { + return new AV.User(); + }, + _processResult: function _processResult(json) { + if (json && json[this._friendshipTag]) { + var user = json[this._friendshipTag]; + if (user.__type === 'Pointer' && user.className === '_User') { + delete user.__type; + delete user.className; + } + return user; + } else { + return null; + } + } + }); +}; + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + /** + * Creates a new Relation for the given parent object and key. This + * constructor should rarely be used directly, but rather created by + * {@link AV.Object#relation}. + * @param {AV.Object} parent The parent of this relation. + * @param {String} key The key for this relation on the parent. + * @see AV.Object#relation + * @class + * + *

+ * A class that is used to access all of the children of a many-to-many + * relationship. Each instance of AV.Relation is associated with a + * particular parent object and key. + *

+ */ + AV.Relation = function (parent, key) { + if (!_.isString(key)) { + throw new TypeError('key must be a string'); + } + this.parent = parent; + this.key = key; + this.targetClassName = null; + }; + + /** + * Creates a query that can be used to query the parent objects in this relation. + * @param {String} parentClass The parent class or name. + * @param {String} relationKey The relation field key in parent. + * @param {AV.Object} child The child object. + * @return {AV.Query} + */ + AV.Relation.reverseQuery = function (parentClass, relationKey, child) { + var query = new AV.Query(parentClass); + query.equalTo(relationKey, child._toPointer()); + return query; + }; + + AV.Relation.prototype = { + /** + * Makes sure that this relation has the right parent and key. + * @private + */ + _ensureParentAndKey: function _ensureParentAndKey(parent, key) { + this.parent = this.parent || parent; + this.key = this.key || key; + if (this.parent !== parent) { + throw new Error("Internal Error. Relation retrieved from two different Objects."); + } + if (this.key !== key) { + throw new Error("Internal Error. Relation retrieved from two different keys."); + } + }, + + /** + * Adds a AV.Object or an array of AV.Objects to the relation. + * @param {AV.Object|AV.Object[]} objects The item or items to add. + */ + add: function add(objects) { + if (!_.isArray(objects)) { + objects = [objects]; + } + + var change = new AV.Op.Relation(objects, []); + this.parent.set(this.key, change); + this.targetClassName = change._targetClassName; + }, + + /** + * Removes a AV.Object or an array of AV.Objects from this relation. + * @param {AV.Object|AV.Object[]} objects The item or items to remove. + */ + remove: function remove(objects) { + if (!_.isArray(objects)) { + objects = [objects]; + } + + var change = new AV.Op.Relation([], objects); + this.parent.set(this.key, change); + this.targetClassName = change._targetClassName; + }, + + /** + * Returns a JSON version of the object suitable for saving to disk. + * @return {Object} + */ + toJSON: function toJSON() { + return { "__type": "Relation", "className": this.targetClassName }; + }, + + /** + * Returns a AV.Query that is limited to objects in this + * relation. + * @return {AV.Query} + */ + query: function query() { + var targetClass; + var query; + if (!this.targetClassName) { + targetClass = AV.Object._getSubclass(this.parent.className); + query = new AV.Query(targetClass); + query._extraOptions.redirectClassNameForKey = this.key; + } else { + targetClass = AV.Object._getSubclass(this.targetClassName); + query = new AV.Query(targetClass); + } + query._addCondition("$relatedTo", "object", this.parent._toPointer()); + query._addCondition("$relatedTo", "key", this.key); + + return query; + } + }; +}; + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); + +module.exports = function (AV) { + AV.Role = AV.Object.extend("_Role", /** @lends AV.Role.prototype */{ + // Instance Methods + + /** + * Represents a Role on the AV server. Roles represent groupings of + * Users for the purposes of granting permissions (e.g. specifying an ACL + * for an Object). Roles are specified by their sets of child users and + * child roles, all of which are granted any permissions that the parent + * role has. + * + *

Roles must have a name (which cannot be changed after creation of the + * role), and must specify an ACL.

+ * An AV.Role is a local representation of a role persisted to the AV + * cloud. + * @class AV.Role + * @param {String} name The name of the Role to create. + * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL + * `{'*': { read: true }}` will be used. + */ + constructor: function constructor(name, acl, noDefaultACL) { + if (_.isString(name)) { + AV.Object.prototype.constructor.call(this, null, null); + this.setName(name); + } else { + AV.Object.prototype.constructor.call(this, name, acl); + } + if (acl === undefined) { + if (!noDefaultACL) { + if (!this.getACL()) { + console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.'); + var defaultAcl = new AV.ACL(); + defaultAcl.setPublicReadAccess(true); + this.setACL(defaultAcl); + } + } + } else if (!(acl instanceof AV.ACL)) { + throw new TypeError('acl must be an instance of AV.ACL'); + } else { + this.setACL(acl); + } + }, + + /** + * Gets the name of the role. You can alternatively call role.get("name") + * + * @return {String} the name of the role. + */ + getName: function getName() { + return this.get("name"); + }, + + /** + * Sets the name for a role. This value must be set before the role has + * been saved to the server, and cannot be set once the role has been + * saved. + * + *

+ * A role's name can only contain alphanumeric characters, _, -, and + * spaces. + *

+ * + *

This is equivalent to calling role.set("name", name)

+ * + * @param {String} name The name of the role. + */ + setName: function setName(name, options) { + return this.set("name", name, options); + }, + + /** + * Gets the AV.Relation for the AV.Users that are direct + * children of this role. These users are granted any privileges that this + * role has been granted (e.g. read or write access through ACLs). You can + * add or remove users from the role through this relation. + * + *

This is equivalent to calling role.relation("users")

+ * + * @return {AV.Relation} the relation for the users belonging to this + * role. + */ + getUsers: function getUsers() { + return this.relation("users"); + }, + + /** + * Gets the AV.Relation for the AV.Roles that are direct + * children of this role. These roles' users are granted any privileges that + * this role has been granted (e.g. read or write access through ACLs). You + * can add or remove child roles from this role through this relation. + * + *

This is equivalent to calling role.relation("roles")

+ * + * @return {AV.Relation} the relation for the roles belonging to this + * role. + */ + getRoles: function getRoles() { + return this.relation("roles"); + }, + + /** + * @ignore + */ + validate: function validate(attrs, options) { + if ("name" in attrs && attrs.name !== this.getName()) { + var newName = attrs.name; + if (this.id && this.id !== attrs.objectId) { + // Check to see if the objectId being set matches this.id. + // This happens during a fetch -- the id is set before calling fetch. + // Let the name be set in this case. + return new AVError(AVError.OTHER_CAUSE, "A role's name can only be set before it has been saved."); + } + if (!_.isString(newName)) { + return new AVError(AVError.OTHER_CAUSE, "A role's name must be a String."); + } + if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) { + return new AVError(AVError.OTHER_CAUSE, "A role's name can only contain alphanumeric characters, _," + " -, and spaces."); + } + } + if (AV.Object.prototype.validate) { + return AV.Object.prototype.validate.call(this, attrs, options); + } + return false; + } + }); +}; + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * A builder to generate sort string for app searching.For example: + * @class + * @since 0.5.1 + * @example + * var builder = new AV.SearchSortBuilder(); + * builder.ascending('key1').descending('key2','max'); + * var query = new AV.SearchQuery('Player'); + * query.sortBy(builder); + * query.find().then(); + */ + AV.SearchSortBuilder = function () { + this._sortFields = []; + }; + + AV.SearchSortBuilder.prototype = { + _addField: function _addField(key, order, mode, missing) { + var field = {}; + field[key] = { + order: order || 'asc', + mode: mode || 'avg', + missing: '_' + (missing || 'last') + }; + this._sortFields.push(field); + return this; + }, + + /** + * Sorts the results in ascending order by the given key and options. + * + * @param {String} key The key to order by. + * @param {String} mode The sort mode, default is 'avg', you can choose + * 'max' or 'min' too. + * @param {String} missing The missing key behaviour, default is 'last', + * you can choose 'first' too. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + ascending: function ascending(key, mode, missing) { + return this._addField(key, 'asc', mode, missing); + }, + + /** + * Sorts the results in descending order by the given key and options. + * + * @param {String} key The key to order by. + * @param {String} mode The sort mode, default is 'avg', you can choose + * 'max' or 'min' too. + * @param {String} missing The missing key behaviour, default is 'last', + * you can choose 'first' too. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + descending: function descending(key, mode, missing) { + return this._addField(key, 'desc', mode, missing); + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Object} options The other options such as mode,order, unit etc. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + whereNear: function whereNear(key, point, options) { + options = options || {}; + var field = {}; + var geo = { + lat: point.latitude, + lon: point.longitude + }; + var m = { + order: options.order || 'asc', + mode: options.mode || 'avg', + unit: options.unit || 'km' + }; + m[key] = geo; + field['_geo_distance'] = m; + + this._sortFields.push(field); + return this; + }, + + /** + * Build a sort string by configuration. + * @return {String} the sort string. + */ + build: function build() { + return JSON.stringify(AV._encode(this._sortFields)); + } + }; + + /** + * App searching query.Use just like AV.Query: + * + * Visit App Searching Guide + * for more details. + * @class + * @since 0.5.1 + * @example + * var query = new AV.SearchQuery('Player'); + * query.queryString('*'); + * query.find().then(function(results) { + * console.log('Found %d objects', query.hits()); + * //Process results + * }); + */ + AV.SearchQuery = AV.Query._extend( /** @lends AV.SearchQuery.prototype */{ + _sid: null, + _hits: 0, + _queryString: null, + _highlights: null, + _sortBuilder: null, + _createRequest: function _createRequest(params, options) { + return AVRequest('search/select', null, null, 'GET', params || this.toJSON(), options); + }, + + /** + * Sets the sid of app searching query.Default is null. + * @param {String} sid Scroll id for searching. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + sid: function sid(_sid) { + this._sid = _sid; + return this; + }, + + /** + * Sets the query string of app searching. + * @param {String} q The query string. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + queryString: function queryString(q) { + this._queryString = q; + return this; + }, + + /** + * Sets the highlight fields. Such as + *

+     *   query.highlights('title');
+     *   //or pass an array.
+     *   query.highlights(['title', 'content'])
+     * 
+ * @param {String[]} highlights a list of fields. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + highlights: function highlights(_highlights) { + var objects; + if (_highlights && _.isString(_highlights)) { + objects = arguments; + } else { + objects = _highlights; + } + this._highlights = objects; + return this; + }, + + /** + * Sets the sort builder for this query. + * @see AV.SearchSortBuilder + * @param { AV.SearchSortBuilder} builder The sort builder. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + * + */ + sortBy: function sortBy(builder) { + this._sortBuilder = builder; + return this; + }, + + /** + * Returns the number of objects that match this query. + * @return {Number} + */ + hits: function hits() { + if (!this._hits) { + this._hits = 0; + } + return this._hits; + }, + + _processResult: function _processResult(json) { + delete json['className']; + delete json['_app_url']; + delete json['_deeplink']; + return json; + }, + + /** + * Returns true when there are more documents can be retrieved by this + * query instance, you can call find function to get more results. + * @see AV.SearchQuery#find + * @return {Boolean} + */ + hasMore: function hasMore() { + return !this._hitEnd; + }, + + /** + * Reset current query instance state(such as sid, hits etc) except params + * for a new searching. After resetting, hasMore() will return true. + */ + reset: function reset() { + this._hitEnd = false; + this._sid = null; + this._hits = 0; + }, + + /** + * Retrieves a list of AVObjects that satisfy this query. + * Either options.success or options.error is called when the find + * completes. + * + * @see AV.Query#find + * @return {AV.Promise} A promise that is resolved with the results when + * the query completes. + */ + find: function find() { + var self = this; + + var request = this._createRequest(); + + return request.then(function (response) { + //update sid for next querying. + if (response.sid) { + self._oldSid = self._sid; + self._sid = response.sid; + } else { + self._sid = null; + self._hitEnd = true; + } + self._hits = response.hits || 0; + + return _.map(response.results, function (json) { + if (json.className) { + response.className = json.className; + } + var obj = self._newObject(response); + obj.appURL = json['_app_url']; + obj._finishFetch(self._processResult(json), true); + return obj; + }); + }); + }, + + toJSON: function toJSON() { + var params = AV.SearchQuery.__super__.toJSON.call(this); + delete params.where; + if (this.className) { + params.clazz = this.className; + } + if (this._sid) { + params.sid = this._sid; + } + if (!this._queryString) { + throw new Error('Please set query string.'); + } else { + params.q = this._queryString; + } + if (this._highlights) { + params.highlights = this._highlights.join(','); + } + if (this._sortBuilder && params.order) { + throw new Error('sort and order can not be set at same time.'); + } + if (this._sortBuilder) { + params.sort = this._sortBuilder.build(); + } + + return params; + } + }); +}; + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + var getUser = function getUser() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return AV.User.currentAsync().then(function (currUser) { + return currUser || AV.User._fetchUserBySessionToken(options.sessionToken); + }); + }; + + var getUserPointer = function getUserPointer(options) { + return getUser(options).then(function (currUser) { + return AV.Object.createWithoutData('_User', currUser.id)._toPointer(); + }); + }; + + /** + * Contains functions to deal with Status in LeanCloud. + * @class + */ + AV.Status = function (imageUrl, message) { + this.data = {}; + this.inboxType = 'default'; + this.query = null; + if (imageUrl && (typeof imageUrl === 'undefined' ? 'undefined' : _typeof(imageUrl)) === 'object') { + this.data = imageUrl; + } else { + if (imageUrl) { + this.data.image = imageUrl; + } + if (message) { + this.data.message = message; + } + } + return this; + }; + + AV.Status.prototype = { + /** + * Gets the value of an attribute in status data. + * @param {String} attr The string name of an attribute. + */ + get: function get(attr) { + return this.data[attr]; + }, + /** + * Sets a hash of model attributes on the status data. + * @param {String} key The key to set. + * @param {} value The value to give it. + */ + set: function set(key, value) { + this.data[key] = value; + return this; + }, + /** + * Destroy this status,then it will not be avaiable in other user's inboxes. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + if (!this.id) return AV.Promise.reject(new Error('The status id is not exists.')); + var request = AVRequest('statuses', null, this.id, 'DELETE', options); + return request; + }, + /** + * Cast the AV.Status object to an AV.Object pointer. + * @return {AV.Object} A AV.Object pointer. + */ + toObject: function toObject() { + if (!this.id) return null; + return AV.Object.createWithoutData('_Status', this.id); + }, + _getDataJSON: function _getDataJSON() { + var json = _.clone(this.data); + return AV._encode(json); + }, + /** + * Send a status by a AV.Query object. + * @since 0.3.0 + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * // send a status to male users + * var status = new AVStatus('image url', 'a message'); + * status.query = new AV.Query('_User'); + * status.query.equalTo('gender', 'male'); + * status.send().then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + send: function send() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + if (!this.query) { + return AV.Status.sendStatusToFollowers(this, options); + } + + return getUserPointer(options).then(function (currUser) { + var query = _this.query.toJSON(); + query.className = _this.query.className; + var data = {}; + data.query = query; + _this.data = _this.data || {}; + _this.data.source = _this.data.source || currUser; + data.data = _this._getDataJSON(); + data.inboxType = _this.inboxType || 'default'; + + return AVRequest('statuses', null, null, 'POST', data, options); + }).then(function (response) { + _this.id = response.objectId; + _this.createdAt = AV._parseDate(response.createdAt); + return _this; + }); + }, + + _finishFetch: function _finishFetch(serverData) { + this.id = serverData.objectId; + this.createdAt = AV._parseDate(serverData.createdAt); + this.updatedAt = AV._parseDate(serverData.updatedAt); + this.messageId = serverData.messageId; + delete serverData.messageId; + delete serverData.objectId; + delete serverData.createdAt; + delete serverData.updatedAt; + this.data = AV._decode(serverData); + } + }; + + /** + * Send a status to current signined user's followers. + * @since 0.3.0 + * @param {AV.Status} status A status object to be send to followers. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * var status = new AVStatus('image url', 'a message'); + * AV.Status.sendStatusToFollowers(status).then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + AV.Status.sendStatusToFollowers = function (status) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + return getUserPointer(options).then(function (currUser) { + var query = {}; + query.className = '_Follower'; + query.keys = 'follower'; + query.where = { user: currUser }; + var data = {}; + data.query = query; + status.data = status.data || {}; + status.data.source = status.data.source || currUser; + data.data = status._getDataJSON(); + data.inboxType = status.inboxType || 'default'; + + var request = AVRequest('statuses', null, null, 'POST', data, options); + return request.then(function (response) { + status.id = response.objectId; + status.createdAt = AV._parseDate(response.createdAt); + return status; + }); + }); + }; + + /** + *

Send a status from current signined user to other user's private status inbox.

+ * @since 0.3.0 + * @param {AV.Status} status A status object to be send to followers. + * @param {String} target The target user or user's objectId. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * // send a private status to user '52e84e47e4b0f8de283b079b' + * var status = new AVStatus('image url', 'a message'); + * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + AV.Status.sendPrivateStatus = function (status, target) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + if (!target) { + throw new Error("Invalid target user."); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error("Invalid target user."); + } + return getUserPointer(options).then(function (currUser) { + var query = {}; + query.className = '_User'; + query.where = { objectId: userObjectId }; + var data = {}; + data.query = query; + status.data = status.data || {}; + status.data.source = status.data.source || currUser; + data.data = status._getDataJSON(); + data.inboxType = 'private'; + status.inboxType = 'private'; + + var request = AVRequest('statuses', null, null, 'POST', data, options); + return request.then(function (response) { + status.id = response.objectId; + status.createdAt = AV._parseDate(response.createdAt); + return status; + }); + }); + }; + + /** + * Count unread statuses in someone's inbox. + * @since 0.3.0 + * @param {Object} owner The status owner. + * @param {String} inboxType The inbox type, 'default' by default. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the count + * completes. + * @example + * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){ + * console.log(response.unread); //unread statuses number. + * console.log(response.total); //total statuses number. + * }); + */ + AV.Status.countUnreadStatuses = function (owner) { + var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!_.isString(inboxType)) options = inboxType; + if (!options.sessionToken && owner == null && !AV.User.current()) { + throw new Error('Please signin an user or pass the owner objectId.'); + } + return getUser(options).then(function (owner) { + var params = {}; + params.inboxType = AV._encode(inboxType); + params.owner = AV._encode(owner); + return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options); + }); + }; + + /** + * reset unread statuses count in someone's inbox. + * @since 2.1.0 + * @param {Object} owner The status owner. + * @param {String} inboxType The inbox type, 'default' by default. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the reset + * completes. + * @example + * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){ + * console.log(response.unread); //unread statuses number. + * console.log(response.total); //total statuses number. + * }); + */ + AV.Status.resetUnreadCount = function (owner) { + var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!_.isString(inboxType)) options = inboxType; + if (!options.sessionToken && owner == null && !AV.User.current()) { + throw new Error('Please signin an user or pass the owner objectId.'); + } + return getUser(options).then(function (owner) { + var params = {}; + params.inboxType = AV._encode(inboxType); + params.owner = AV._encode(owner); + return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options); + }); + }; + + /** + * Create a status query to find someone's published statuses. + * @since 0.3.0 + * @param {Object} source The status source. + * @return {AV.Query} The query object for status. + * @example + * //Find current user's published statuses. + * var query = AV.Status.statusQuery(AV.User.current()); + * query.find().then(function(statuses){ + * //process statuses + * }); + */ + AV.Status.statusQuery = function (source) { + var query = new AV.Query('_Status'); + if (source) { + query.equalTo('source', source); + } + return query; + }; + + /** + *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

+ * @class + */ + AV.InboxQuery = AV.Query._extend( /** @lends AV.InboxQuery.prototype */{ + _objectClass: AV.Status, + _sinceId: 0, + _maxId: 0, + _inboxType: 'default', + _owner: null, + _newObject: function _newObject() { + return new AV.Status(); + }, + _createRequest: function _createRequest(params, options) { + return AVRequest('subscribe/statuses', null, null, 'GET', params || this.toJSON(), options); + }, + + /** + * Sets the messageId of results to skip before returning any results. + * This is useful for pagination. + * Default is zero. + * @param {Number} n the mesage id. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + sinceId: function sinceId(id) { + this._sinceId = id; + return this; + }, + /** + * Sets the maximal messageId of results。 + * This is useful for pagination. + * Default is zero that is no limition. + * @param {Number} n the mesage id. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + maxId: function maxId(id) { + this._maxId = id; + return this; + }, + /** + * Sets the owner of the querying inbox. + * @param {Object} owner The inbox owner. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + owner: function owner(_owner) { + this._owner = _owner; + return this; + }, + /** + * Sets the querying inbox type.default is 'default'. + * @param {Object} owner The inbox type. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + inboxType: function inboxType(type) { + this._inboxType = type; + return this; + }, + toJSON: function toJSON() { + var params = AV.InboxQuery.__super__.toJSON.call(this); + params.owner = AV._encode(this._owner); + params.inboxType = AV._encode(this._inboxType); + params.sinceId = AV._encode(this._sinceId); + params.maxId = AV._encode(this._maxId); + return params; + } + }); + + /** + * Create a inbox status query to find someone's inbox statuses. + * @since 0.3.0 + * @param {Object} owner The inbox's owner + * @param {String} inboxType The inbox type,'default' by default. + * @return {AV.InboxQuery} The inbox query object. + * @see AV.InboxQuery + * @example + * //Find current user's default inbox statuses. + * var query = AV.Status.inboxQuery(AV.User.current()); + * //find the statuses after the last message id + * query.sinceId(lastMessageId); + * query.find().then(function(statuses){ + * //process statuses + * }); + */ + AV.Status.inboxQuery = function (owner, inboxType) { + var query = new AV.InboxQuery(AV.Status); + if (owner) { + query._owner = owner; + } + if (inboxType) { + query._inboxType = inboxType; + } + return query; + }; +}; + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var Promise = __webpack_require__(1); + +var getWeappLoginCode = function getWeappLoginCode() { + if (typeof wx === 'undefined' || typeof wx.login !== 'function') { + throw new Error('Weapp Login is only available in Weapp'); + } + return new Promise(function (resolve, reject) { + wx.login({ + success: function success(_ref) { + var code = _ref.code, + errMsg = _ref.errMsg; + + if (code) { + resolve(code); + } else { + reject(new Error(errMsg)); + } + } + }); + }); +}; + +module.exports = function (AV) { + /** + * @class + * + *

An AV.User object is a local representation of a user persisted to the + * LeanCloud server. This class is a subclass of an AV.Object, and retains the + * same functionality of an AV.Object, but also extends it with various + * user specific methods, like authentication, signing up, and validation of + * uniqueness.

+ */ + AV.User = AV.Object.extend("_User", /** @lends AV.User.prototype */{ + // Instance Variables + _isCurrentUser: false, + + // Instance Methods + + /** + * Internal method to handle special fields in a _User response. + * @private + */ + _mergeMagicFields: function _mergeMagicFields(attrs) { + if (attrs.sessionToken) { + this._sessionToken = attrs.sessionToken; + delete attrs.sessionToken; + } + AV.User.__super__._mergeMagicFields.call(this, attrs); + }, + + /** + * Removes null values from authData (which exist temporarily for + * unlinking) + * @private + */ + _cleanupAuthData: function _cleanupAuthData() { + if (!this.isCurrent()) { + return; + } + var authData = this.get('authData'); + if (!authData) { + return; + } + AV._objectEach(this.get('authData'), function (value, key) { + if (!authData[key]) { + delete authData[key]; + } + }); + }, + + /** + * Synchronizes authData for all providers. + * @private + */ + _synchronizeAllAuthData: function _synchronizeAllAuthData() { + var authData = this.get('authData'); + if (!authData) { + return; + } + + var self = this; + AV._objectEach(this.get('authData'), function (value, key) { + self._synchronizeAuthData(key); + }); + }, + + /** + * Synchronizes auth data for a provider (e.g. puts the access token in the + * right place to be used by the Facebook SDK). + * @private + */ + _synchronizeAuthData: function _synchronizeAuthData(provider) { + if (!this.isCurrent()) { + return; + } + var authType; + if (_.isString(provider)) { + authType = provider; + provider = AV.User._authProviders[authType]; + } else { + authType = provider.getAuthType(); + } + var authData = this.get('authData'); + if (!authData || !provider) { + return; + } + var success = provider.restoreAuthentication(authData[authType]); + if (!success) { + this._unlinkFrom(provider); + } + }, + + _handleSaveResult: function _handleSaveResult(makeCurrent) { + // Clean up and synchronize the authData object, removing any unset values + if (makeCurrent && !AV._config.disableCurrentUser) { + this._isCurrentUser = true; + } + this._cleanupAuthData(); + this._synchronizeAllAuthData(); + // Don't keep the password around. + delete this._serverData.password; + this._rebuildEstimatedDataForKey("password"); + this._refreshCache(); + if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) { + // Some old version of leanengine-node-sdk will overwrite + // AV.User._saveCurrentUser which returns no Promise. + // So we need a Promise wrapper. + return Promise.resolve(AV.User._saveCurrentUser(this)); + } else { + return Promise.resolve(); + } + }, + + /** + * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can + * call linkWith on the user (even if it doesn't exist yet on the server). + * @private + */ + _linkWith: function _linkWith(provider, data) { + var _this = this; + + var authType; + if (_.isString(provider)) { + authType = provider; + provider = AV.User._authProviders[provider]; + } else { + authType = provider.getAuthType(); + } + if (data) { + var authData = this.get('authData') || {}; + authData[authType] = data; + return this.save({ authData: authData }).then(function (model) { + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + } else { + return provider.authenticate().then(function (result) { + return _this._linkWith(provider, result); + }); + } + }, + + /** + * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。 + * 仅在小程序中可用。 + * + * @return {AV.User} + */ + linkWithWeapp: function linkWithWeapp() { + var _this2 = this; + + return getWeappLoginCode().then(function (code) { + return _this2._linkWith('lc_weapp', { code: code }); + }); + }, + + + /** + * Unlinks a user from a service. + * @private + */ + _unlinkFrom: function _unlinkFrom(provider) { + var _this3 = this; + + if (_.isString(provider)) { + provider = AV.User._authProviders[provider]; + } + return this._linkWith(provider, null).then(function (model) { + _this3._synchronizeAuthData(provider); + return model; + }); + }, + + /** + * Checks whether a user is linked to a service. + * @private + */ + _isLinked: function _isLinked(provider) { + var authType; + if (_.isString(provider)) { + authType = provider; + } else { + authType = provider.getAuthType(); + } + var authData = this.get('authData') || {}; + return !!authData[authType]; + }, + + logOut: function logOut() { + this._logOutWithAll(); + this._isCurrentUser = false; + }, + + /** + * Deauthenticates all providers. + * @private + */ + _logOutWithAll: function _logOutWithAll() { + var authData = this.get('authData'); + if (!authData) { + return; + } + var self = this; + AV._objectEach(this.get('authData'), function (value, key) { + self._logOutWith(key); + }); + }, + + /** + * Deauthenticates a single provider (e.g. removing access tokens from the + * Facebook SDK). + * @private + */ + _logOutWith: function _logOutWith(provider) { + if (!this.isCurrent()) { + return; + } + if (_.isString(provider)) { + provider = AV.User._authProviders[provider]; + } + if (provider && provider.deauthenticate) { + provider.deauthenticate(); + } + }, + + /** + * Signs up a new user. You should call this instead of save for + * new AV.Users. This will create a new AV.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {Object} attrs Extra fields to set on the new user, or null. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the signup + * finishes. + * @see AV.User.signUp + */ + signUp: function signUp(attrs, options) { + var error; + + var username = attrs && attrs.username || this.get("username"); + if (!username || username === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up user with an empty name."); + throw error; + } + + var password = attrs && attrs.password || this.get("password"); + if (!password || password === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up user with an empty password."); + throw error; + } + + return this.save(attrs, options).then(function (model) { + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + }, + + /** + * Signs up a new user with mobile phone and sms code. + * You should call this instead of save for + * new AV.Users. This will create a new AV.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {Object} attrs Extra fields to set on the new user, or null. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the signup + * finishes. + * @see AV.User.signUpOrlogInWithMobilePhone + * @see AV.Cloud.requestSmsCode + */ + signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(attrs) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var error; + + var mobilePhoneNumber = attrs && attrs.mobilePhoneNumber || this.get("mobilePhoneNumber"); + if (!mobilePhoneNumber || mobilePhoneNumber === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up or login user by mobilePhoneNumber " + "with an empty mobilePhoneNumber."); + throw error; + } + + var smsCode = attrs && attrs.smsCode || this.get("smsCode"); + if (!smsCode || smsCode === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up or login user by mobilePhoneNumber " + "with an empty smsCode."); + throw error; + } + + options._makeRequest = function (route, className, id, method, json) { + return AVRequest('usersByMobilePhone', null, null, "POST", json); + }; + return this.save(attrs, options).then(function (model) { + delete model.attributes.smsCode; + delete model._serverData.smsCode; + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + }, + + /** + * Logs in a AV.User. On success, this saves the session to localStorage, + * so you can retrieve the currently logged in user using + * current. + * + *

A username and password must be set before calling logIn.

+ * + * @see AV.User.logIn + * @return {Promise} A promise that is fulfilled with the user when + * the login is complete. + */ + logIn: function logIn() { + var model = this; + var request = AVRequest('login', null, null, 'POST', this.toJSON()); + return request.then(function (resp) { + var serverAttrs = model.parse(resp); + model._finishFetch(serverAttrs); + return model._handleSaveResult(true).then(function () { + if (!serverAttrs.smsCode) delete model.attributes['smsCode']; + return model; + }); + }); + }, + /** + * @see AV.Object#save + */ + save: function save(arg1, arg2, arg3) { + var i, attrs, current, options, saved; + if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) { + attrs = arg1; + options = arg2; + } else { + attrs = {}; + attrs[arg1] = arg2; + options = arg3; + } + options = options || {}; + + return AV.Object.prototype.save.call(this, attrs, options).then(function (model) { + return model._handleSaveResult(false).then(function () { + return model; + }); + }); + }, + + /** + * Follow a user + * @since 0.3.0 + * @param {AV.User | String} target The target user or user's objectId to follow. + * @param {AuthOptions} options + */ + follow: function follow(target, options) { + if (!this.id) { + throw new Error('Please signin.'); + } + if (!target) { + throw new Error('Invalid target user.'); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error('Invalid target user.'); + } + var route = 'users/' + this.id + '/friendship/' + userObjectId; + var request = AVRequest(route, null, null, 'POST', null, options); + return request; + }, + + /** + * Unfollow a user. + * @since 0.3.0 + * @param {AV.User | String} target The target user or user's objectId to unfollow. + * @param {AuthOptions} options + */ + unfollow: function unfollow(target, options) { + if (!this.id) { + throw new Error('Please signin.'); + } + if (!target) { + throw new Error('Invalid target user.'); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error('Invalid target user.'); + } + var route = 'users/' + this.id + '/friendship/' + userObjectId; + var request = AVRequest(route, null, null, 'DELETE', null, options); + return request; + }, + + /** + *Create a follower query to query the user's followers. + * @since 0.3.0 + * @see AV.User#followerQuery + */ + followerQuery: function followerQuery() { + return AV.User.followerQuery(this.id); + }, + + /** + *Create a followee query to query the user's followees. + * @since 0.3.0 + * @see AV.User#followeeQuery + */ + followeeQuery: function followeeQuery() { + return AV.User.followeeQuery(this.id); + }, + + /** + * @see AV.Object#fetch + */ + fetch: function fetch(fetchOptions, options) { + return AV.Object.prototype.fetch.call(this, fetchOptions, options).then(function (model) { + return model._handleSaveResult(false).then(function () { + return model; + }); + }); + }, + + /** + * Update user's new password safely based on old password. + * @param {String} oldPassword the old password. + * @param {String} newPassword the new password. + * @param {AuthOptions} options + */ + updatePassword: function updatePassword(oldPassword, newPassword, options) { + var route = 'users/' + this.id + '/updatePassword'; + var params = { + old_password: oldPassword, + new_password: newPassword + }; + var request = AVRequest(route, null, null, 'PUT', params, options); + return request; + }, + + /** + * Returns true if current would return this user. + * @see AV.User#current + */ + isCurrent: function isCurrent() { + return this._isCurrentUser; + }, + + /** + * Returns get("username"). + * @return {String} + * @see AV.Object#get + */ + getUsername: function getUsername() { + return this.get("username"); + }, + + /** + * Returns get("mobilePhoneNumber"). + * @return {String} + * @see AV.Object#get + */ + getMobilePhoneNumber: function getMobilePhoneNumber() { + return this.get("mobilePhoneNumber"); + }, + + /** + * Calls set("mobilePhoneNumber", phoneNumber, options) and returns the result. + * @param {String} mobilePhoneNumber + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setMobilePhoneNumber: function setMobilePhoneNumber(phone, options) { + return this.set("mobilePhoneNumber", phone, options); + }, + + /** + * Calls set("username", username, options) and returns the result. + * @param {String} username + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setUsername: function setUsername(username, options) { + return this.set("username", username, options); + }, + + /** + * Calls set("password", password, options) and returns the result. + * @param {String} password + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setPassword: function setPassword(password, options) { + return this.set("password", password, options); + }, + + /** + * Returns get("email"). + * @return {String} + * @see AV.Object#get + */ + getEmail: function getEmail() { + return this.get("email"); + }, + + /** + * Calls set("email", email, options) and returns the result. + * @param {String} email + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setEmail: function setEmail(email, options) { + return this.set("email", email, options); + }, + + /** + * Checks whether this user is the current user and has been authenticated. + * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(), + * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id + * @return (Boolean) whether this user is the current user and is logged in. + */ + authenticated: function authenticated() { + console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。'); + return !!this._sessionToken && !AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id; + }, + + /** + * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。 + * + * @since 2.0.0 + * @return Promise. + */ + isAuthenticated: function isAuthenticated() { + var _this4 = this; + + return Promise.resolve().then(function () { + return !!_this4._sessionToken && AV.User._fetchUserBySessionToken(_this4._sessionToken).then(function () { + return true; + }, function (error) { + if (error.code === 211) { + return false; + } + throw error; + }); + }); + }, + + + /** + * Get sessionToken of current user. + * @return {String} sessionToken + */ + getSessionToken: function getSessionToken() { + return this._sessionToken; + }, + + + /** + * Refresh sessionToken of current user. + * @since 2.1.0 + * @param {AuthOptions} [options] + * @return {Promise.} user with refreshed sessionToken + */ + refreshSessionToken: function refreshSessionToken(options) { + var _this5 = this; + + return AVRequest('users/' + this.id + '/refreshSessionToken', null, null, 'PUT', null, options).then(function (response) { + _this5._finishFetch(response); + return _this5._handleSaveResult(true).then(function () { + return _this5; + }); + }); + }, + + + /** + * Get this user's Roles. + * @param {AuthOptions} [options] + * @return {Promise} A promise that is fulfilled with the roles when + * the query is complete. + */ + getRoles: function getRoles(options) { + return AV.Relation.reverseQuery("_Role", "users", this).find(options); + } + }, /** @lends AV.User */{ + // Class Variables + + // The currently logged-in user. + _currentUser: null, + + // Whether currentUser is known to match the serialized version on disk. + // This is useful for saving a localstorage check if you try to load + // _currentUser frequently while there is none stored. + _currentUserMatchesDisk: false, + + // The localStorage key suffix that the current user is stored under. + _CURRENT_USER_KEY: "currentUser", + + // The mapping of auth provider names to actual providers + _authProviders: {}, + + // Class Methods + + /** + * Signs up a new user with a username (or email) and password. + * This will create a new AV.User on the server, and also persist the + * session in localStorage so that you can access the user using + * {@link #current}. + * + * @param {String} username The username (or email) to sign up with. + * @param {String} password The password to sign up with. + * @param {Object} attrs Extra fields to set on the new user. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the signup completes. + * @see AV.User#signUp + */ + signUp: function signUp(username, password, attrs, options) { + attrs = attrs || {}; + attrs.username = username; + attrs.password = password; + var user = AV.Object._create("_User"); + return user.signUp(attrs, options); + }, + + /** + * Logs in a user with a username (or email) and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} username The username (or email) to log in with. + * @param {String} password The password to log in with. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logIn: function logIn(username, password, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ username: username, password: password }); + return user.logIn(options); + }, + + /** + * Logs in a user with a session token. On success, this saves the session + * to disk, so you can retrieve the currently logged in user using + * current. + * + * @param {String} sessionToken The sessionToken to log in with. + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + become: function become(sessionToken) { + return this._fetchUserBySessionToken(sessionToken).then(function (user) { + return user._handleSaveResult(true).then(function () { + return user; + }); + }); + }, + + _fetchUserBySessionToken: function _fetchUserBySessionToken(sessionToken) { + var user = AV.Object._create("_User"); + return AVRequest("users", "me", null, "GET", { + session_token: sessionToken + }).then(function (resp) { + var serverAttrs = user.parse(resp); + user._finishFetch(serverAttrs); + return user; + }); + }, + + /** + * Logs in a user with a mobile phone number and sms code sent by + * AV.User.requestLoginSmsCode.On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} mobilePhone The user's mobilePhoneNumber + * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logInWithMobilePhoneSmsCode: function logInWithMobilePhoneSmsCode(mobilePhone, smsCode, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode }); + return user.logIn(options); + }, + + /** + * Sign up or logs in a user with a mobilePhoneNumber and smsCode. + * On success, this saves the session to disk, so you can retrieve the currently + * logged in user using current. + * + * @param {String} mobilePhoneNumber The user's mobilePhoneNumber. + * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode + * @param {Object} attributes The user's other attributes such as username etc. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#signUpOrlogInWithMobilePhone + * @see AV.Cloud.requestSmsCode + */ + signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(mobilePhoneNumber, smsCode, attrs, options) { + attrs = attrs || {}; + attrs.mobilePhoneNumber = mobilePhoneNumber; + attrs.smsCode = smsCode; + var user = AV.Object._create("_User"); + return user.signUpOrlogInWithMobilePhone(attrs, options); + }, + + /** + * Logs in a user with a mobile phone number and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} mobilePhone The user's mobilePhoneNumber + * @param {String} password The password to log in with. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logInWithMobilePhone: function logInWithMobilePhone(mobilePhone, password, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password }); + return user.logIn(options); + }, + + /** + * Sign up or logs in a user with a third party auth data(AccessToken). + * On success, this saves the session to disk, so you can retrieve the currently + * logged in user using current. + * + * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 } + * @param {string} platform Available platform for sign up. + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) { + * //Access user here + * }).catch(function(error) { + * //console.error("error: ", error); + * }); + * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户} + */ + signUpOrlogInWithAuthData: function signUpOrlogInWithAuthData(authData, platform) { + return AV.User._logInWith(platform, authData); + }, + + + /** + * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。 + * 仅在小程序中可用。 + * + * @since 2.0.0 + * @return {AV.User} + */ + loginWithWeapp: function loginWithWeapp() { + var _this6 = this; + + return getWeappLoginCode().then(function (code) { + return _this6.signUpOrlogInWithAuthData({ code: code }, 'lc_weapp'); + }); + }, + + + /** + * Associate a user with a third party auth data(AccessToken). + * + * @param {AV.User} userObj A user which you want to associate. + * @param {string} platform Available platform for sign up. + * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 } + * @return {Promise} A promise that is fulfilled with the user when completed. + * @example AV.User.associateWithAuthData(loginUser, 'weixin', { + * openid: 'abc123', + * access_token: '123abc', + * expires_in: 1382686496 + * }).then(function(user) { + * //Access user here + * }).catch(function(error) { + * //console.error("error: ", error); + * }); + */ + associateWithAuthData: function associateWithAuthData(userObj, platform, authData) { + return userObj._linkWith(platform, authData); + }, + + /** + * Logs out the currently logged in user session. This will remove the + * session from disk, log out of linked services, and future calls to + * current will return null. + * @return {Promise} + */ + logOut: function logOut() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return Promise.resolve(null); + } + + if (AV.User._currentUser !== null) { + AV.User._currentUser._logOutWithAll(); + AV.User._currentUser._isCurrentUser = false; + } + AV.User._currentUserMatchesDisk = true; + AV.User._currentUser = null; + return AV.localStorage.removeItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)); + }, + + /** + *Create a follower query for special user to query the user's followers. + * @param {String} userObjectId The user object id. + * @return {AV.FriendShipQuery} + * @since 0.3.0 + */ + followerQuery: function followerQuery(userObjectId) { + if (!userObjectId || !_.isString(userObjectId)) { + throw new Error('Invalid user object id.'); + } + var query = new AV.FriendShipQuery('_Follower'); + query._friendshipTag = 'follower'; + query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId)); + return query; + }, + + /** + *Create a followee query for special user to query the user's followees. + * @param {String} userObjectId The user object id. + * @return {AV.FriendShipQuery} + * @since 0.3.0 + */ + followeeQuery: function followeeQuery(userObjectId) { + if (!userObjectId || !_.isString(userObjectId)) { + throw new Error('Invalid user object id.'); + } + var query = new AV.FriendShipQuery('_Followee'); + query._friendshipTag = 'followee'; + query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId)); + return query; + }, + + /** + * Requests a password reset email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * reset their password on the AV site. + * + * @param {String} email The email address associated with the user that + * forgot their password. + * @return {Promise} + */ + requestPasswordReset: function requestPasswordReset(email) { + var json = { email: email }; + var request = AVRequest("requestPasswordReset", null, null, "POST", json); + return request; + }, + + /** + * Requests a verify email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * verify their email address on the AV site. + * + * @param {String} email The email address associated with the user that + * doesn't verify their email address. + * @return {Promise} + */ + requestEmailVerify: function requestEmailVerify(email) { + var json = { email: email }; + var request = AVRequest("requestEmailVerify", null, null, "POST", json); + return request; + }, + + /** + * Requests a verify sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * verify their mobile phone number by calling AV.User.verifyMobilePhone + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that doesn't verify their mobile phone number. + * @return {Promise} + */ + requestMobilePhoneVerify: function requestMobilePhoneVerify(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestMobilePhoneVerify", null, null, "POST", json); + return request; + }, + + /** + * Requests a reset password sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * reset their account's password by calling AV.User.resetPasswordBySmsCode + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that doesn't verify their mobile phone number. + * @return {Promise} + */ + requestPasswordResetBySmsCode: function requestPasswordResetBySmsCode(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestPasswordResetBySmsCode", null, null, "POST", json); + return request; + }, + + /** + * Makes a call to reset user's account password by sms code and new password. + * The sms code is sent by AV.User.requestPasswordResetBySmsCode. + * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode + * @param {String} password The new password. + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + resetPasswordBySmsCode: function resetPasswordBySmsCode(code, password) { + var json = { password: password }; + var request = AVRequest("resetPasswordBySmsCode", null, code, "PUT", json); + return request; + }, + + /** + * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode + * If verify successfully,the user mobilePhoneVerified attribute will be true. + * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + verifyMobilePhone: function verifyMobilePhone(code) { + var request = AVRequest("verifyMobilePhone", null, code, "POST", null); + return request; + }, + + /** + * Requests a logIn sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * login by AV.User.logInWithMobilePhoneSmsCode function. + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that want to login by AV.User.logInWithMobilePhoneSmsCode + * @return {Promise} + */ + requestLoginSmsCode: function requestLoginSmsCode(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestLoginSmsCode", null, null, "POST", json); + return request; + }, + + /** + * Retrieves the currently logged in AVUser with a valid session, + * either from memory or localStorage, if necessary. + * @return {Promise.} resolved with the currently logged in AV.User. + */ + currentAsync: function currentAsync() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return Promise.resolve(null); + } + + if (AV.User._currentUser) { + return Promise.resolve(AV.User._currentUser); + } + + if (AV.User._currentUserMatchesDisk) { + + return Promise.resolve(AV.User._currentUser); + } + + return AV.localStorage.getItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)).then(function (userData) { + if (!userData) { + return null; + } + + // Load the user from local storage. + AV.User._currentUserMatchesDisk = true; + + AV.User._currentUser = AV.Object._create("_User"); + AV.User._currentUser._isCurrentUser = true; + + var json = JSON.parse(userData); + AV.User._currentUser.id = json._id; + delete json._id; + AV.User._currentUser._sessionToken = json._sessionToken; + delete json._sessionToken; + AV.User._currentUser._finishFetch(json); + //AV.User._currentUser.set(json); + + AV.User._currentUser._synchronizeAllAuthData(); + AV.User._currentUser._refreshCache(); + AV.User._currentUser._opSetQueue = [{}]; + return AV.User._currentUser; + }); + }, + + /** + * Retrieves the currently logged in AVUser with a valid session, + * either from memory or localStorage, if necessary. + * @return {AV.User} The currently logged in AV.User. + */ + current: function current() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return null; + } + + if (AV.User._currentUser) { + return AV.User._currentUser; + } + + if (AV.User._currentUserMatchesDisk) { + + return AV.User._currentUser; + } + + // Load the user from local storage. + AV.User._currentUserMatchesDisk = true; + + var userData = AV.localStorage.getItem(AV._getAVPath(AV.User._CURRENT_USER_KEY)); + if (!userData) { + + return null; + } + AV.User._currentUser = AV.Object._create("_User"); + AV.User._currentUser._isCurrentUser = true; + + var json = JSON.parse(userData); + AV.User._currentUser.id = json._id; + delete json._id; + AV.User._currentUser._sessionToken = json._sessionToken; + delete json._sessionToken; + AV.User._currentUser._finishFetch(json); + //AV.User._currentUser.set(json); + + AV.User._currentUser._synchronizeAllAuthData(); + AV.User._currentUser._refreshCache(); + AV.User._currentUser._opSetQueue = [{}]; + return AV.User._currentUser; + }, + + /** + * Persists a user as currentUser to localStorage, and into the singleton. + * @private + */ + _saveCurrentUser: function _saveCurrentUser(user) { + var promise; + if (AV.User._currentUser !== user) { + promise = AV.User.logOut(); + } else { + promise = Promise.resolve(); + } + return promise.then(function () { + user._isCurrentUser = true; + AV.User._currentUser = user; + + var json = user.toJSON(); + json._id = user.id; + json._sessionToken = user._sessionToken; + return AV.localStorage.setItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY), JSON.stringify(json)).then(function () { + AV.User._currentUserMatchesDisk = true; + }); + }); + }, + + _registerAuthenticationProvider: function _registerAuthenticationProvider(provider) { + AV.User._authProviders[provider.getAuthType()] = provider; + // Synchronize the current user with the auth provider. + if (!AV._config.disableCurrentUser && AV.User.current()) { + AV.User.current()._synchronizeAuthData(provider.getAuthType()); + } + }, + + _logInWith: function _logInWith(provider, options) { + var user = AV.Object._create("_User"); + return user._linkWith(provider, options); + } + + }); +}; + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/*! + * LeanCloud JavaScript SDK + * https://leancloud.cn + * + * Copyright 2016 LeanCloud.cn, Inc. + * The LeanCloud JavaScript SDK is freely distributable under the MIT license. + */ + +var AV = __webpack_require__(6); + +AV._ = __webpack_require__(0); +AV.version = __webpack_require__(11); +AV.Promise = __webpack_require__(1); +AV.localStorage = __webpack_require__(10); +AV.Cache = __webpack_require__(9); +AV.Error = __webpack_require__(3); + +__webpack_require__(19); +__webpack_require__(16)(AV); +__webpack_require__(18)(AV); +__webpack_require__(14)(AV); +__webpack_require__(22)(AV); +__webpack_require__(25)(AV); +__webpack_require__(17)(AV); +__webpack_require__(21)(AV); +__webpack_require__(26)(AV); +__webpack_require__(29)(AV); +__webpack_require__(24)(AV); +__webpack_require__(15)(AV); +__webpack_require__(23)(AV); +__webpack_require__(28)(AV); +__webpack_require__(27)(AV); +__webpack_require__(20)(AV); + +module.exports = AV; + +/** + * Options to controll the authentication for an operation + * @typedef {Object} AuthOptions + * @property {String} [sessionToken] Specify a user to excute the operation as. + * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided. + * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set. + */ + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = []; + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var version = __webpack_require__(11); +var comments = ["ReactNative" || 'Node.js'].concat(__webpack_require__(31)); + +module.exports = 'LeanCloud-JS-SDK/' + version + ' (' + comments.join('; ') + ')'; + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var debug = __webpack_require__(5)('cos'); +var Promise = __webpack_require__(1); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + var uploadUrl = uploadInfo.upload_url + "?sign=" + encodeURIComponent(uploadInfo.token); + + return new Promise(function (resolve, reject) { + var req = request('POST', uploadUrl).field('fileContent', data).field('op', 'upload'); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (res) { + debug(res.status, res.body, res.text); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var Promise = __webpack_require__(1); +var debug = __webpack_require__(5)('qiniu'); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + // Get the uptoken to upload files to qiniu. + var uptoken = uploadInfo.token; + return new Promise(function (resolve, reject) { + var req = request('POST', 'https://up.qbox.me').field('file', data).field('name', file.attributes.name).field('key', file._qiniu_key).field('token', uptoken); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (res) { + debug(res.status, res.body, res.text); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var AVPromise = __webpack_require__(1); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + return new Promise(function (resolve, reject) { + // 海外节点,针对 S3 才会返回 upload_url + var req = request('PUT', uploadInfo.upload_url).set('Content-Type', file.get('mime_type')).send(data); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(1); + +// interface Storage { +// readonly attribute boolean async; +// string getItem(string key); +// void setItem(string key, string value); +// void removeItem(string key); +// void clear(); +// Promise getItemAsync(string key); +// Promise setItemAsync(string key, string value); +// Promise removeItemAsync(string key); +// Promise clearAsync(); +// } +var Storage = {}; +var apiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +var AsyncStorage = __webpack_require__(50).AsyncStorage; +_(apiNames).each(function (apiName) { + Storage[apiName + 'Async'] = function () { + return Promise.resolve(AsyncStorage[apiName].apply(AsyncStorage, arguments)); + }; +}); +Storage.async = true; + +module.exports = Storage; + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var dataURItoBlob = function dataURItoBlob(dataURI, type) { + var byteString; + + // 传入的 base64,不是 dataURL + if (dataURI.indexOf('base64') < 0) { + byteString = atob(dataURI); + } else if (dataURI.split(',')[0].indexOf('base64') >= 0) { + type = type || dataURI.split(',')[0].split(':')[1].split(';')[0]; + byteString = atob(dataURI.split(',')[1]); + } else { + byteString = unescape(dataURI.split(',')[1]); + } + var ia = new Uint8Array(byteString.length); + for (var i = 0; i < byteString.length; i++) { + ia[i] = byteString.charCodeAt(i); + } + return new Blob([ia], { type: type }); +}; + +module.exports = dataURItoBlob; + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + + +/***/ }), +/* 39 */ +/***/ (function(module, exports) { + +(function() { + var base64map + = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', + + crypt = { + // Bit-wise rotation left + rotl: function(n, b) { + return (n << b) | (n >>> (32 - b)); + }, + + // Bit-wise rotation right + rotr: function(n, b) { + return (n << (32 - b)) | (n >>> b); + }, + + // Swap big-endian to little-endian and vice versa + endian: function(n) { + // If number given, swap endian + if (n.constructor == Number) { + return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; + } + + // Else, assume array and swap all items + for (var i = 0; i < n.length; i++) + n[i] = crypt.endian(n[i]); + return n; + }, + + // Generate an array of any length of random bytes + randomBytes: function(n) { + for (var bytes = []; n > 0; n--) + bytes.push(Math.floor(Math.random() * 256)); + return bytes; + }, + + // Convert a byte array to big-endian 32-bit words + bytesToWords: function(bytes) { + for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) + words[b >>> 5] |= bytes[i] << (24 - b % 32); + return words; + }, + + // Convert big-endian 32-bit words to a byte array + wordsToBytes: function(words) { + for (var bytes = [], b = 0; b < words.length * 32; b += 8) + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); + return bytes; + }, + + // Convert a byte array to a hex string + bytesToHex: function(bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + } + return hex.join(''); + }, + + // Convert a hex string to a byte array + hexToBytes: function(hex) { + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.substr(c, 2), 16)); + return bytes; + }, + + // Convert a byte array to a base-64 string + bytesToBase64: function(bytes) { + for (var base64 = [], i = 0; i < bytes.length; i += 3) { + var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + for (var j = 0; j < 4; j++) + if (i * 8 + j * 6 <= bytes.length * 8) + base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); + else + base64.push('='); + } + return base64.join(''); + }, + + // Convert a base-64 string to a byte array + base64ToBytes: function(base64) { + // Remove non-base-64 characters + base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); + + for (var bytes = [], i = 0, imod4 = 0; i < base64.length; + imod4 = ++i % 4) { + if (imod4 == 0) continue; + bytes.push(((base64map.indexOf(base64.charAt(i - 1)) + & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) + | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); + } + return bytes; + } + }; + + module.exports = crypt; +})(); + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __webpack_require__(44); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (namespaces || '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + + +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var require;/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version 4.1.0 + */ + +(function (global, factory) { + true ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; +} + +function isFunction(x) { + return typeof x === 'function'; +} + +var _isArray = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +var isArray = _isArray; + +var len = 0; +var vertxNext = undefined; +var customSchedulerFn = undefined; + +var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +}; + +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = typeof window !== 'undefined' ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + + return useSetTimeout(); +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + node.data = iterations = ++iterations % 2; + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } + + len = 0; +} + +function attemptVertx() { + try { + var r = require; + var vertx = __webpack_require__(51); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} + +var scheduleFlush = undefined; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && "function" === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} + +function then(onFulfillment, onRejection) { + var _arguments = arguments; + + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var _state = parent._state; + + if (_state) { + (function () { + var callback = _arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; +} + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} + +var PROMISE_ID = Math.random().toString(36).substring(16); + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + _resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + _reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return _resolve(promise, value); + }, function (reason) { + return _reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then$$) { + if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$ === GET_THEN_ERROR) { + _reject(promise, GET_THEN_ERROR.error); + GET_THEN_ERROR.error = null; + } else if (then$$ === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$)) { + handleForeignThenable(promise, maybeThenable, then$$); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + + parent._onerror = null; + + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { + return; + } + + var child = undefined, + callback = undefined, + detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value.error = null; + } else { + succeeded = true; + } + + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + _resolve(promise, value); + } else if (failed) { + _reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + _reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + _resolve(promise, value); + }, function rejectPromise(reason) { + _reject(promise, reason); + }); + } catch (e) { + _reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + _reject(this.promise, validationError()); + } +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._enumerate = function () { + var length = this.length; + var _input = this._input; + + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(_input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + + if (resolve$$ === resolve) { + var _then = getThen(entry); + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$) { + return resolve$$(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$(entry), i); + } +}; + +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; + +Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); +}; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +function all(entries) { + return new Enumerator(this, entries).promise; +} + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = resolve; +Promise.reject = reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; + +Promise.prototype = { + constructor: Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + let result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + let author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: then, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function _catch(onRejection) { + return this.then(null, onRejection); + } +}; + +function polyfill() { + var local = undefined; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } + + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + + local.Promise = Promise; +} + +// Strange compat.. +Promise.polyfill = polyfill; +Promise.Promise = Promise; + +return Promise; + +}))); +//# sourceMappingURL=es6-promise.map + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(13))) + +/***/ }), +/* 42 */ +/***/ (function(module, exports) { + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +(function(){ + var crypt = __webpack_require__(39), + utf8 = __webpack_require__(12).utf8, + isBuffer = __webpack_require__(42), + bin = __webpack_require__(12).bin, + + // The core + md5 = function (message, options) { + // Convert to byte array + if (message.constructor == String) + if (options && options.encoding === 'binary') + message = bin.stringToBytes(message); + else + message = utf8.stringToBytes(message); + else if (isBuffer(message)) + message = Array.prototype.slice.call(message, 0); + else if (!Array.isArray(message)) + message = message.toString(); + // else, assume byte array already + + var m = crypt.bytesToWords(message), + l = message.length * 8, + a = 1732584193, + b = -271733879, + c = -1732584194, + d = 271733878; + + // Swap endian + for (var i = 0; i < m.length; i++) { + m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF | + ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00; + } + + // Padding + m[l >>> 5] |= 0x80 << (l % 32); + m[(((l + 64) >>> 9) << 4) + 14] = l; + + // Method shortcuts + var FF = md5._ff, + GG = md5._gg, + HH = md5._hh, + II = md5._ii; + + for (var i = 0; i < m.length; i += 16) { + + var aa = a, + bb = b, + cc = c, + dd = d; + + a = FF(a, b, c, d, m[i+ 0], 7, -680876936); + d = FF(d, a, b, c, m[i+ 1], 12, -389564586); + c = FF(c, d, a, b, m[i+ 2], 17, 606105819); + b = FF(b, c, d, a, m[i+ 3], 22, -1044525330); + a = FF(a, b, c, d, m[i+ 4], 7, -176418897); + d = FF(d, a, b, c, m[i+ 5], 12, 1200080426); + c = FF(c, d, a, b, m[i+ 6], 17, -1473231341); + b = FF(b, c, d, a, m[i+ 7], 22, -45705983); + a = FF(a, b, c, d, m[i+ 8], 7, 1770035416); + d = FF(d, a, b, c, m[i+ 9], 12, -1958414417); + c = FF(c, d, a, b, m[i+10], 17, -42063); + b = FF(b, c, d, a, m[i+11], 22, -1990404162); + a = FF(a, b, c, d, m[i+12], 7, 1804603682); + d = FF(d, a, b, c, m[i+13], 12, -40341101); + c = FF(c, d, a, b, m[i+14], 17, -1502002290); + b = FF(b, c, d, a, m[i+15], 22, 1236535329); + + a = GG(a, b, c, d, m[i+ 1], 5, -165796510); + d = GG(d, a, b, c, m[i+ 6], 9, -1069501632); + c = GG(c, d, a, b, m[i+11], 14, 643717713); + b = GG(b, c, d, a, m[i+ 0], 20, -373897302); + a = GG(a, b, c, d, m[i+ 5], 5, -701558691); + d = GG(d, a, b, c, m[i+10], 9, 38016083); + c = GG(c, d, a, b, m[i+15], 14, -660478335); + b = GG(b, c, d, a, m[i+ 4], 20, -405537848); + a = GG(a, b, c, d, m[i+ 9], 5, 568446438); + d = GG(d, a, b, c, m[i+14], 9, -1019803690); + c = GG(c, d, a, b, m[i+ 3], 14, -187363961); + b = GG(b, c, d, a, m[i+ 8], 20, 1163531501); + a = GG(a, b, c, d, m[i+13], 5, -1444681467); + d = GG(d, a, b, c, m[i+ 2], 9, -51403784); + c = GG(c, d, a, b, m[i+ 7], 14, 1735328473); + b = GG(b, c, d, a, m[i+12], 20, -1926607734); + + a = HH(a, b, c, d, m[i+ 5], 4, -378558); + d = HH(d, a, b, c, m[i+ 8], 11, -2022574463); + c = HH(c, d, a, b, m[i+11], 16, 1839030562); + b = HH(b, c, d, a, m[i+14], 23, -35309556); + a = HH(a, b, c, d, m[i+ 1], 4, -1530992060); + d = HH(d, a, b, c, m[i+ 4], 11, 1272893353); + c = HH(c, d, a, b, m[i+ 7], 16, -155497632); + b = HH(b, c, d, a, m[i+10], 23, -1094730640); + a = HH(a, b, c, d, m[i+13], 4, 681279174); + d = HH(d, a, b, c, m[i+ 0], 11, -358537222); + c = HH(c, d, a, b, m[i+ 3], 16, -722521979); + b = HH(b, c, d, a, m[i+ 6], 23, 76029189); + a = HH(a, b, c, d, m[i+ 9], 4, -640364487); + d = HH(d, a, b, c, m[i+12], 11, -421815835); + c = HH(c, d, a, b, m[i+15], 16, 530742520); + b = HH(b, c, d, a, m[i+ 2], 23, -995338651); + + a = II(a, b, c, d, m[i+ 0], 6, -198630844); + d = II(d, a, b, c, m[i+ 7], 10, 1126891415); + c = II(c, d, a, b, m[i+14], 15, -1416354905); + b = II(b, c, d, a, m[i+ 5], 21, -57434055); + a = II(a, b, c, d, m[i+12], 6, 1700485571); + d = II(d, a, b, c, m[i+ 3], 10, -1894986606); + c = II(c, d, a, b, m[i+10], 15, -1051523); + b = II(b, c, d, a, m[i+ 1], 21, -2054922799); + a = II(a, b, c, d, m[i+ 8], 6, 1873313359); + d = II(d, a, b, c, m[i+15], 10, -30611744); + c = II(c, d, a, b, m[i+ 6], 15, -1560198380); + b = II(b, c, d, a, m[i+13], 21, 1309151649); + a = II(a, b, c, d, m[i+ 4], 6, -145523070); + d = II(d, a, b, c, m[i+11], 10, -1120210379); + c = II(c, d, a, b, m[i+ 2], 15, 718787259); + b = II(b, c, d, a, m[i+ 9], 21, -343485551); + + a = (a + aa) >>> 0; + b = (b + bb) >>> 0; + c = (c + cc) >>> 0; + d = (d + dd) >>> 0; + } + + return crypt.endian([a, b, c, d]); + }; + + // Auxiliary functions + md5._ff = function (a, b, c, d, x, s, t) { + var n = a + (b & c | ~b & d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._gg = function (a, b, c, d, x, s, t) { + var n = a + (b & d | c & ~d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._hh = function (a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._ii = function (a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + + // Package private blocksize + md5._blocksize = 16; + md5._digestsize = 16; + + module.exports = function (message, options) { + if (message === undefined || message === null) + throw new Error('Illegal argument ' + message); + + var digestbytes = crypt.wordsToBytes(md5(message, options)); + return options && options.asBytes ? digestbytes : + options && options.asString ? bin.bytesToString(digestbytes) : + crypt.bytesToHex(digestbytes); + }; + +})(); + + +/***/ }), +/* 44 */ +/***/ (function(module, exports) { + +/** + * Helpers. + */ + +var s = 1000 +var m = s * 60 +var h = m * 60 +var d = h * 24 +var y = d * 365.25 + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {} + var type = typeof val + if (type === 'string' && val.length > 0) { + return parse(val) + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? + fmtLong(val) : + fmtShort(val) + } + throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) +} + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str) + if (str.length > 10000) { + return + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) + if (!match) { + return + } + var n = parseFloat(match[1]) + var type = (match[2] || 'ms').toLowerCase() + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y + case 'days': + case 'day': + case 'd': + return n * d + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n + default: + return undefined + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd' + } + if (ms >= h) { + return Math.round(ms / h) + 'h' + } + if (ms >= m) { + return Math.round(ms / m) + 'm' + } + if (ms >= s) { + return Math.round(ms / s) + 's' + } + return ms + 'ms' +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms' +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name + } + return Math.ceil(ms / n) + ' ' + name + 's' +} + + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Check if `fn` is a function. + * + * @param {Function} fn + * @return {Boolean} + * @api private + */ +var isObject = __webpack_require__(8); + +function isFunction(fn) { + var tag = isObject(fn) ? Object.prototype.toString.call(fn) : ''; + return tag === '[object Function]'; +} + +module.exports = isFunction; + + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Module of mixed-in functions shared between node and client code + */ +var isObject = __webpack_require__(8); + +/** + * Expose `RequestBase`. + */ + +module.exports = RequestBase; + +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in RequestBase.prototype) { + obj[key] = RequestBase.prototype[key]; + } + return obj; +} + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.clearTimeout = function _clearTimeout(){ + clearTimeout(this._timer); + clearTimeout(this._responseTimeoutTimer); + delete this._timer; + delete this._responseTimeoutTimer; + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.parse = function parse(fn){ + this._parser = fn; + return this; +}; + +/** + * Set format of binary response body. + * In browser valid formats are 'blob' and 'arraybuffer', + * which return Blob and ArrayBuffer, respectively. + * + * In Node all values result in Buffer. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.responseType = function(val){ + this._responseType = val; + return this; +}; + +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.serialize = function serialize(fn){ + this._serializer = fn; + return this; +}; + +/** + * Set timeouts. + * + * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. + * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. + * + * Value of 0 or false means no timeout. + * + * @param {Number|Object} ms or {response, read, deadline} + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.timeout = function timeout(options){ + if (!options || 'object' !== typeof options) { + this._timeout = options; + this._responseTimeout = 0; + return this; + } + + for(var option in options) { + switch(option) { + case 'deadline': + this._timeout = options.deadline; + break; + case 'response': + this._responseTimeout = options.response; + break; + default: + console.warn("Unknown timeout option", option); + } + } + return this; +}; + +/** + * Set number of retry attempts on error. + * + * Failed requests will be retried 'count' times if timeout or err.code >= 500. + * + * @param {Number} count + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.retry = function retry(count){ + // Default to 1 if no count passed or true + if (arguments.length === 0 || count === true) count = 1; + if (count <= 0) count = 0; + this._maxRetries = count; + this._retries = 0; + return this; +}; + +/** + * Retry request + * + * @return {Request} for chaining + * @api private + */ + +RequestBase.prototype._retry = function() { + this.clearTimeout(); + + // node + if (this.req) { + this.req = null; + this.req = this.request(); + } + + this._aborted = false; + this.timedout = false; + + return this._end(); +}; + +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} [reject] + * @return {Request} + */ + +RequestBase.prototype.then = function then(resolve, reject) { + if (!this._fullfilledPromise) { + var self = this; + if (this._endCalled) { + console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"); + } + this._fullfilledPromise = new Promise(function(innerResolve, innerReject){ + self.end(function(err, res){ + if (err) innerReject(err); else innerResolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +} + +RequestBase.prototype.catch = function(cb) { + return this.then(undefined, cb); +}; + +/** + * Allow for extension + */ + +RequestBase.prototype.use = function use(fn) { + fn(this); + return this; +} + +RequestBase.prototype.ok = function(cb) { + if ('function' !== typeof cb) throw Error("Callback required"); + this._okCallback = cb; + return this; +}; + +RequestBase.prototype._isResponseOK = function(res) { + if (!res) { + return false; + } + + if (this._okCallback) { + return this._okCallback(res); + } + + return res.status >= 200 && res.status < 300; +}; + + +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + +RequestBase.prototype.get = function(field){ + return this._header[field.toLowerCase()]; +}; + +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + +RequestBase.prototype.getHeader = RequestBase.prototype.get; + +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function(field, val){ + if (isObject(field)) { + for (var key in field) { + this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; + +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + */ +RequestBase.prototype.unset = function(field){ + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; + +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name + * @param {String|Blob|File|Buffer|fs.ReadStream} val + * @return {Request} for chaining + * @api public + */ +RequestBase.prototype.field = function(name, val) { + + // name should be either a string or an object. + if (null === name || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + + if (this._data) { + console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObject(name)) { + for (var key in name) { + this.field(key, name[key]); + } + return this; + } + + if (Array.isArray(val)) { + for (var i in val) { + this.field(name, val[i]); + } + return this; + } + + // val should be defined now + if (null === val || undefined === val) { + throw new Error('.field(name, val) val can not be empty'); + } + if ('boolean' === typeof val) { + val = '' + val; + } + this._getFormData().append(name, val); + return this; +}; + +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */ +RequestBase.prototype.abort = function(){ + if (this._aborted) { + return this; + } + this._aborted = true; + this.xhr && this.xhr.abort(); // browser + this.req && this.req.abort(); // node + this.clearTimeout(); + this.emit('abort'); + return this; +}; + +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ + +RequestBase.prototype.withCredentials = function(on){ + // This is browser-only functionality. Node side is no-op. + if(on==undefined) on = true; + this._withCredentials = on; + return this; +}; + +/** + * Set the max redirects to `n`. Does noting in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.redirects = function(n){ + this._maxRedirects = n; + return this; +}; + +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + +RequestBase.prototype.toJSON = function(){ + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; + + +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.send = function(data){ + var isObj = isObject(data); + var type = this._header['content-type']; + + if (this._formData) { + console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObj && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw Error("Can't merge these send calls"); + } + + // merge + if (isObj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + + if (!isObj || this._isHost(data)) { + return this; + } + + // default to json + if (!type) this.type('json'); + return this; +}; + + +/** + * Sort `querystring` by the sort function + * + * + * Examples: + * + * // default order + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery() + * .end(callback) + * + * // customized sort function + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery(function(a, b){ + * return a.length - b.length; + * }) + * .end(callback) + * + * + * @param {Function} sort + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.sortQuery = function(sort) { + // _sort default to true but otherwise can be a function or boolean + this._sort = typeof sort === 'undefined' ? true : sort; + return this; +}; + +/** + * Invoke callback with timeout error. + * + * @api private + */ + +RequestBase.prototype._timeoutError = function(reason, timeout, errno){ + if (this._aborted) { + return; + } + var err = new Error(reason + timeout + 'ms exceeded'); + err.timeout = timeout; + err.code = 'ECONNABORTED'; + err.errno = errno; + this.timedout = true; + this.abort(); + this.callback(err); +}; + +RequestBase.prototype._setTimeouts = function() { + var self = this; + + // deadline + if (this._timeout && !this._timer) { + this._timer = setTimeout(function(){ + self._timeoutError('Timeout of ', self._timeout, 'ETIME'); + }, this._timeout); + } + // response timeout + if (this._responseTimeout && !this._responseTimeoutTimer) { + this._responseTimeoutTimer = setTimeout(function(){ + self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); + }, this._responseTimeout); + } +} + + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * Module dependencies. + */ + +var utils = __webpack_require__(49); + +/** + * Expose `ResponseBase`. + */ + +module.exports = ResponseBase; + +/** + * Initialize a new `ResponseBase`. + * + * @api public + */ + +function ResponseBase(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in ResponseBase.prototype) { + obj[key] = ResponseBase.prototype[key]; + } + return obj; +} + +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + +ResponseBase.prototype.get = function(field){ + return this.header[field.toLowerCase()]; +}; + +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + +ResponseBase.prototype._setHeaderProperties = function(header){ + // TODO: moar! + // TODO: make this a util + + // content-type + var ct = header['content-type'] || ''; + this.type = utils.type(ct); + + // params + var params = utils.params(ct); + for (var key in params) this[key] = params[key]; + + this.links = {}; + + // links + try { + if (header.link) { + this.links = utils.parseLinks(header.link); + } + } catch (err) { + // ignore + } +}; + +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + +ResponseBase.prototype._setStatusProperties = function(status){ + var type = status / 100 | 0; + + // status / class + this.status = this.statusCode = status; + this.statusType = type; + + // basics + this.info = 1 == type; + this.ok = 2 == type; + this.redirect = 3 == type; + this.clientError = 4 == type; + this.serverError = 5 == type; + this.error = (4 == type || 5 == type) + ? this.toError() + : false; + + // sugar + this.accepted = 202 == status; + this.noContent = 204 == status; + this.badRequest = 400 == status; + this.unauthorized = 401 == status; + this.notAcceptable = 406 == status; + this.forbidden = 403 == status; + this.notFound = 404 == status; +}; + + +/***/ }), +/* 48 */ +/***/ (function(module, exports) { + +var ERROR_CODES = [ + 'ECONNRESET', + 'ETIMEDOUT', + 'EADDRINFO', + 'ESOCKETTIMEDOUT' +]; + +/** + * Determine if a request should be retried. + * (Borrowed from segmentio/superagent-retry) + * + * @param {Error} err + * @param {Response} [res] + * @returns {Boolean} + */ +module.exports = function shouldRetry(err, res) { + if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true; + if (res && res.status && res.status >= 500) return true; + // Superagent timeout + if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true; + if (err && 'crossDomain' in err) return true; + return false; +}; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports) { + + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.type = function(str){ + return str.split(/ *; */).shift(); +}; + +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.params = function(str){ + return str.split(/ *; */).reduce(function(obj, str){ + var parts = str.split(/ *= */); + var key = parts.shift(); + var val = parts.shift(); + + if (key && val) obj[key] = val; + return obj; + }, {}); +}; + +/** + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.parseLinks = function(str){ + return str.split(/ *, */).reduce(function(obj, str){ + var parts = str.split(/ *; */); + var url = parts[0].slice(1, -1); + var rel = parts[1].split(/ *= */)[1].slice(1, -1); + obj[rel] = url; + return obj; + }, {}); +}; + +/** + * Strip content related fields from `header`. + * + * @param {Object} header + * @return {Object} header + * @api private + */ + +exports.cleanHeader = function(header, shouldStripCookie){ + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header['host']; + if (shouldStripCookie) { + delete header['cookie']; + } + return header; +}; + +/***/ }), +/* 50 */ +/***/ (function(module, exports) { + +module.exports = __WEBPACK_EXTERNAL_MODULE_50__; + +/***/ }), +/* 51 */ +/***/ (function(module, exports) { + +/* (ignored) */ + +/***/ }) +/******/ ]); +}); +//# sourceMappingURL=av-rn.js.map \ No newline at end of file diff --git a/dist/av-rn.js.map b/dist/av-rn.js.map new file mode 100644 index 000000000..90f579905 --- /dev/null +++ b/dist/av-rn.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 77a21bff237eaad2029d","webpack:///./~/underscore/underscore.js","webpack:///./src/promise.js","webpack:///./src/request.js","webpack:///./src/error.js","webpack:///./src/utils/index.js","webpack:///./~/debug/src/browser.js","webpack:///./src/av.js","webpack:///./~/superagent/lib/client.js","webpack:///./~/superagent/lib/is-object.js","webpack:///./src/cache.js","webpack:///./src/localstorage.js","webpack:///./src/version.js","webpack:///./~/charenc/charenc.js","webpack:///(webpack)/buildin/global.js","webpack:///./src/acl.js","webpack:///./src/cloudfunction.js","webpack:///./src/event.js","webpack:///./src/file.js","webpack:///./src/geopoint.js","webpack:///./src/init.js","webpack:///./src/insight.js","webpack:///./src/object.js","webpack:///./src/op.js","webpack:///./src/push.js","webpack:///./src/query.js","webpack:///./src/relation.js","webpack:///./src/role.js","webpack:///./src/search.js","webpack:///./src/status.js","webpack:///./src/user.js","webpack:///./src/index.js","webpack:///./src/ua/comments-browser.js","webpack:///./src/ua/index.js","webpack:///./src/uploader/cos.js","webpack:///./src/uploader/qiniu-browser.js","webpack:///./src/uploader/s3.js","webpack:///./src/utils/localstorage-rn.js","webpack:///./src/utils/parse-base64-browser.js","webpack:///./~/component-emitter/index.js","webpack:///./~/crypt/crypt.js","webpack:///./~/debug/src/debug.js","webpack:///./~/es6-promise/dist/es6-promise.js","webpack:///./~/is-buffer/index.js","webpack:///./~/md5/md5.js","webpack:///./~/ms/index.js","webpack:///./~/superagent/lib/is-function.js","webpack:///./~/superagent/lib/request-base.js","webpack:///./~/superagent/lib/response-base.js","webpack:///./~/superagent/lib/should-retry.js","webpack:///./~/superagent/lib/utils.js","webpack:///external \"react-native\"","webpack:///vertx (ignored)"],"names":["_","require","Promise","_continueWhile","predicate","asyncFunction","then","resolve","module","exports","request","debug","md5","Cache","AVError","AV","getSessionToken","getServerURLPromise","API_HOST","cn","us","sign","key","isMasterKey","now","Date","getTime","signature","requestsCount","ajax","method","resourceUrl","data","headers","onprogress","count","reject","req","set","send","on","end","err","res","status","body","text","header","statusCode","responseText","response","setAppKey","signKey","applicationKey","setHeaders","authOptions","applicationId","useMasterKey","_useMasterKey","masterKey","console","warn","hookKey","_config","applicationProduction","String","userAgent","sessionToken","disableCurrentUser","User","currentAsync","currentUser","_sessionToken","createApiUrl","route","className","objectId","dataObject","serverURL","APIServerURL","apiURL","charAt","length","_fetchWhenSave","_where","encodeURIComponent","JSON","stringify","toLowerCase","indexOf","k","cacheServerURL","ttl","setAsync","handleError","error","api_server","location","catch","errorJSON","code","message","parse","e","setServerUrl","newRegion","findKey","item","region","refreshServerUrlByRouter","url","servers","setServerUrlByRegion","getAsync","AVRequest","Error","extend","OTHER_CAUSE","INTERNAL_SERVER_ERROR","CONNECTION_FAILED","OBJECT_NOT_FOUND","INVALID_QUERY","INVALID_CLASS_NAME","MISSING_OBJECT_ID","INVALID_KEY_NAME","INVALID_POINTER","INVALID_JSON","COMMAND_UNAVAILABLE","NOT_INITIALIZED","INCORRECT_TYPE","INVALID_CHANNEL_NAME","PUSH_MISCONFIGURED","OBJECT_TOO_LARGE","OPERATION_FORBIDDEN","CACHE_MISS","INVALID_NESTED_KEY","INVALID_FILE_NAME","INVALID_ACL","TIMEOUT","INVALID_EMAIL_ADDRESS","MISSING_CONTENT_TYPE","MISSING_CONTENT_LENGTH","INVALID_CONTENT_LENGTH","FILE_TOO_LARGE","FILE_SAVE_ERROR","FILE_DELETE_ERROR","DUPLICATE_VALUE","INVALID_ROLE_NAME","EXCEEDED_QUOTA","SCRIPT_FAILED","VALIDATION_ERROR","INVALID_IMAGE_DATA","UNSAVED_FILE_ERROR","INVALID_PUSH_TIME_ERROR","USERNAME_MISSING","PASSWORD_MISSING","USERNAME_TAKEN","EMAIL_TAKEN","EMAIL_MISSING","EMAIL_NOT_FOUND","SESSION_MISSING","MUST_CREATE_USER_THROUGH_SIGNUP","ACCOUNT_ALREADY_LINKED","LINKED_ID_MISSING","INVALID_LINKED_SESSION","UNSUPPORTED_SERVICE","X_DOMAIN_REQUEST","isNullOrUndefined","x","isNull","isUndefined","ensureArray","isArray","target","undefined","user","tap","interceptor","value","global","AVConfig","EmptyConstructor","inherits","parent","protoProps","staticProps","child","hasOwnProperty","constructor","apply","arguments","prototype","__super__","setProduction","production","_getAVPath","path","isString","substring","_installationId","_getInstallationId","localStorage","getItemAsync","hexOctet","Math","floor","random","toString","setItemAsync","_parseDate","iso8601","regexp","RegExp","match","exec","year","month","day","hour","minute","second","milli","UTC","_extend","classProps","_getValue","object","prop","isFunction","_encode","seenObjects","disallowObjects","Object","include","_hasData","_toPointer","dirty","concat","_toFullJSON","ACL","toJSON","isDate","GeoPoint","map","isRegExp","source","Relation","Op","File","id","isObject","mapObject","v","_decode","__op","__type","pointer","_create","keys","clone","_finishFetch","iso","latitude","longitude","relation","targetClassName","file","name","_encodeObjectOrArray","encodeAVObject","_arrayEach","each","_traverse","func","seen","push","attributes","index","newChild","_each","_objectEach","obj","callback","storage","removeAsync","removeItemAsync","bind","getCacheData","cacheData","expired","expiredAt","cache","syncApiNames","async","apiName","PUBLIC_KEY","arg1","self","permissionsById","setReadAccess","setWriteAccess","accessList","userId","allowed","permission","isBoolean","_setAccess","accessType","Role","getName","permissions","isEmpty","_getAccess","getReadAccess","getWriteAccess","setPublicReadAccess","getPublicReadAccess","setPublicWriteAccess","getPublicWriteAccess","getRoleReadAccess","role","getRoleWriteAccess","setRoleReadAccess","setRoleWriteAccess","Cloud","run","options","resp","result","rpc","getServerDate","requestSmsCode","mobilePhoneNumber","verifySmsCode","phone","params","eventSplitter","slice","Array","Events","events","context","calls","event","node","tail","list","split","_callbacks","shift","next","off","cb","ctx","trigger","args","all","rest","call","unbind","cos","qiniu","s3","parseBase64","avConfig","extname","b64Digit","number","fromCharCode","encodeBase64","array","chunks","ceil","times","i","b1","b2","b3","has2","has3","join","mimeType","metaData","base64","TypeError","size","_extName","_data","owner","current","withURL","type","__source","createWithoutData","json","val","_operations","has","getACL","_acl","setACL","acl","get","attrName","attr","thumbnailURL","width","height","quality","scaleToFit","fmt","mode","ownerId","destroy","_fileToken","extName","mime_type","_qiniu_key","save","_previousSave","uploadInfo","_token","token","blob","uri","Buffer","isBuffer","uploadPromise","provider","_callback","success","fetch","bucket","arg2","_validate","isNumber","__defineGetter__","__defineSetter__","_latitude","_longitude","navigator","geolocation","getCurrentPosition","coords","radiansTo","point","d2r","PI","lat1rad","long1rad","lat2rad","long2rad","deltaLat","deltaLong","sinDeltaLatDiv2","sin","sinDeltaLongDiv2","a","min","asin","sqrt","kilometersTo","milesTo","initialize","appId","appKey","process","env","LEANCLOUD_APP_HOOK_KEY","masterKeyWarn","init","Insight","startJob","jobConfig","sql","JobQuery","_skip","_limit","skip","n","limit","find","utils","RESERVED_KEYS","checkReservedKey","_mergeMagicFields","defaults","collection","_serverData","_opSetQueue","_flags","_hashedJSON","_escapedAttributes","cid","uniqueId","changed","_silent","_pending","silent","_previousAttributes","saveAll","_deepSaveAsync","fetchAll","objects","requests","forEach","fetchWhenSave","enable","getObjectId","getCreatedAt","createdAt","getUpdatedAt","updatedAt","_refreshCache","_refreshingCache","_resetCacheForKey","Set","currentChanges","last","_ensureParentAndKey","escape","html","escaped","attrs","model","specialFields","_startSave","_cancelSave","failedChanges","first","nextChanges","op","op1","op2","_mergeWithPrevious","_saving","_finishSave","serverData","fetchedObjects","savedChanges","_applyOpSet","fetched","_rebuildAllEstimatedData","hasData","opSet","change","_estimate","_UNSET","wasSet","_rebuildEstimatedDataForKey","previousAttributes","oldValue","newValue","unset","unused_value","Unset","dataToValidate","changes","prev","isRealChange","isEqual","increment","amount","Increment","add","Add","addUnique","AddUnique","remove","Remove","clear","keysToClear","_getSaveJSON","_canBeSerialized","_canBeSerializedAsValue","fetchOptions","arg3","saved","wait","setOptions","unsavedChildren","unsavedFiles","_findUnsavedChildren","_allPreviousSaves","query","queryJSON","where","makeRequest","_makeRequest","serverAttrs","triggerDestroy","output","isNew","changing","_changing","deleteChanged","hasChanged","changedAttributes","diff","old","diffVal","previous","isValid","validate","disableBeforeHook","ignoreHook","disableAfterHook","hookName","contains","trace","__ignore_hooks","destroyAll","objectsByClassNameAndFlags","groupBy","flags","ids","_getSubclass","ObjectClass","_classMap","noDefaultACL","NewClassObject","OldClassObject","_className","arg0","newArguments","toArray","defineProperty","_LCClassName","register","klass","children","files","canBeSerializedAsValue","filter","promise","uniq","remaining","batch","newRemaining","readyToStart","bathSavePromise","_initialize","_opDecoderMap","_registerDecoder","opName","decoder","ops","nextOp","_value","_amount","_objects","matchingObj","anObj","union","difference","other","adds","removes","_targetClassName","pointerToId","relationsToAdd","relationsToRemove","added","removed","idToPointer","pointers","newAdd","newRemove","newRelation","Installation","Push","cql","push_time","expiration_time","expiration_time_interval","requires","Query","objectClass","_include","_select","_extraOptions","or","queries","q","_orQuery","and","_andQuery","doCloudQuery","pvalues","results","_newObject","_processResult","errorObject","_order","order","_createRequest","_parseResponse","scan","orderedBy","batchSize","condition","scan_key","cursor","done","remainResults","equalTo","_addCondition","sizeEqualTo","notEqualTo","lessThan","greaterThan","lessThanOrEqualTo","greaterThanOrEqualTo","containedIn","values","notContainedIn","containsAll","exists","doesNotExist","matches","regex","modifiers","ignoreCase","multiline","matchesQuery","doesNotMatchQuery","matchesKeyInQuery","queryKey","doesNotMatchKeyInQuery","$or","$and","_quote","s","replace","startsWith","endsWith","ascending","addAscending","descending","addDescending","near","withinRadians","distance","withinMiles","withinKilometers","withinGeoBox","southwest","northeast","select","finished","callbacksDone","FriendShipQuery","_objectClass","_friendshipTag","reverseQuery","parentClass","relationKey","targetClass","redirectClassNameForKey","setName","defaultAcl","getUsers","getRoles","newName","test","SearchSortBuilder","_sortFields","_addField","missing","field","whereNear","geo","lat","lon","m","unit","build","SearchQuery","_sid","_hits","_queryString","_highlights","_sortBuilder","sid","queryString","highlights","sortBy","builder","hits","hasMore","_hitEnd","reset","_oldSid","appURL","clazz","sort","getUser","currUser","_fetchUserBySessionToken","getUserPointer","Status","imageUrl","inboxType","image","toObject","_getDataJSON","sendStatusToFollowers","messageId","sendPrivateStatus","userObjectId","countUnreadStatuses","resetUnreadCount","statusQuery","InboxQuery","_sinceId","_maxId","_inboxType","_owner","sinceId","maxId","inboxQuery","getWeappLoginCode","wx","login","errMsg","_isCurrentUser","_cleanupAuthData","isCurrent","authData","_synchronizeAllAuthData","_synchronizeAuthData","authType","_authProviders","getAuthType","restoreAuthentication","_unlinkFrom","_handleSaveResult","makeCurrent","password","_saveCurrentUser","_linkWith","authenticate","linkWithWeapp","_isLinked","logOut","_logOutWithAll","_logOutWith","deauthenticate","signUp","username","signUpOrlogInWithMobilePhone","smsCode","logIn","follow","unfollow","followerQuery","followeeQuery","updatePassword","oldPassword","newPassword","old_password","new_password","getUsername","getMobilePhoneNumber","setMobilePhoneNumber","setUsername","setPassword","getEmail","setEmail","email","authenticated","isAuthenticated","refreshSessionToken","_currentUser","_currentUserMatchesDisk","_CURRENT_USER_KEY","become","session_token","logInWithMobilePhoneSmsCode","mobilePhone","logInWithMobilePhone","signUpOrlogInWithAuthData","platform","_logInWith","loginWithWeapp","associateWithAuthData","userObj","requestPasswordReset","requestEmailVerify","requestMobilePhoneVerify","requestPasswordResetBySmsCode","resetPasswordBySmsCode","verifyMobilePhone","requestLoginSmsCode","userData","_id","getItem","_registerAuthenticationProvider","version","comments","upload","saveOptions","_bucket","uploadUrl","upload_url","uptoken","AVPromise","Storage","apiNames","AsyncStorage","dataURItoBlob","dataURI","byteString","atob","unescape","ia","Uint8Array","charCodeAt","Blob"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA,mDAA2C,cAAc;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;AAEA;AACA;;;;;;;AChEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,gBAAgB;AACzC;AACA;AACA;AACA,uBAAuB,OAAO;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,YAAY;AAClD;AACA;AACA,KAAK;AACL;AACA,uCAAuC,YAAY;AACnD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,8BAA8B;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,YAAY;AACtD;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,YAAY;AACtD;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B,gBAAgB;AAC7C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA,oDAAoD;AACpD,GAAG;;AAEH;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA,0CAA0C;AAC1C,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,4DAA4D,YAAY;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,YAAY;AAC1D;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,8CAA8C,YAAY;AAC1D;AACA;AACA,qBAAqB,gBAAgB;AACrC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,6CAA6C,YAAY;AACzD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,8BAA8B;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD;AACtD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,0BAA0B;AACpE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,qBAAqB,cAAc;AACnC;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,YAAY;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,OAAO,eAAe;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,qBAAqB,eAAe;AACpC;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,yBAAyB,gBAAgB;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB;AACnB;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,4CAA4C,mBAAmB;AAC/D;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,qDAAqD;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6EAA6E;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,qCAAqC;AACrC;AACA;AACA;;AAEA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,mBAAmB,OAAO;AAC1B;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe;AACf,cAAc;AACd,cAAc;AACd,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;;AAE5B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA,OAAO;AACP,qBAAqB;AACrB;;AAEA;AACA;AACA,KAAK;AACL,iBAAiB;;AAEjB;AACA,kDAAkD,EAAE,iBAAiB;;AAErE;AACA,wBAAwB,8BAA8B;AACtD,2BAA2B;;AAE3B;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,kD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AAP;AACD;AACD,SAAO,CAACA,MAAD,CAAP;AACD,CARD;;AAUA,IAAM7J,kBAAkB,SAAlBA,eAAkB,CAACuC,WAAD,EAAiB;AACvC,MAAIA,YAAYY,YAAhB,EAA8B;AAC5B,WAAOZ,YAAYY,YAAnB;AACD;AACD,MACEZ,YAAYwH,IAAZ,IAAoB,OAAOxH,YAAYwH,IAAZ,CAAiB/J,eAAxB,KAA4C,UADlE,EAEE;AACA,WAAOuC,YAAYwH,IAAZ,CAAiB/J,eAAjB,EAAP;AACD;AACF,CATD;;AAWA,IAAMgK,MAAM,SAANA,GAAM;AAAA,SAAe;AAAA,WAAWC,YAAYC,KAAZ,GAAoBA,KAA/B;AAAA,GAAf;AAAA,CAAZ;;AAEA1K,OAAOC,OAAP,GAAiB;AACf8J,sCADe;AAEfI,0BAFe;AAGf3J,kCAHe;AAIfgK;AAJe,CAAjB,C;;;;;;AC5BA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;;AAEA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BAAiB,sCAAsC;;AAEvD;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,qCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,cAAc;;AAEd,qCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C;AAC5C,wCAAwC;AACxC;AACA;AACA;AACA;AACA;AACA,iBAAiB,aAAa;AAC9B,8BAA8B;AAC9B;AACA;AACA;AACA;AACA;AACA,iBAAiB,aAAa,iBAAiB;AAC/C;AACA;AACA;AACA;AACA,0BAA0B,aAAa;AACvC,8BAA8B;AAC9B;AACA;AACA;AACA;AACA,0BAA0B,aAAa,iBAAiB;AACxD;AACA,WAAW,eAAe;AAC1B,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB;AACnB,oBAAoB;AACpB;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC;AACpC,OAAO;AACP;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,kBAAkB;AAClB;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA,kDAAkD;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,yDAAyD,iBAAiB;AAC1E;AACA,U;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,gBAAgB;AAC/B;AACA,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,wEAAwE,mBAAmB;AAC3F;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,UAAU;AACrB,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,SAAS,sBAAsB,WAAW,YAAY;;AAEtD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,4FAA4F;AAC5F;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,eAAe;AAC1B,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,eAAe;AAC1B,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,eAAe;AAC1B,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;A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ClB,WAAW,MAAM;AACjB,YAAY;AACZ;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,2CAA2C,SAAS;AACpD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;;;;;;AClKA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qBAAqB,cAAc;AACnC;AACA;AACA,KAAK;;AAEL;AACA;AACA,0BAA0B,OAAO;AACjC;AACA;AACA,KAAK;;AAEL;AACA;AACA,wCAAwC,kBAAkB;AAC1D;AACA;AACA,KAAK;;AAEL;AACA;AACA,iCAAiC,uBAAuB;AACxD;AACA;AACA,KAAK;;AAEL;AACA;AACA,+BAA+B,kBAAkB;AACjD;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA,iCAAiC,gBAAgB;AACjD;AACA;AACA,KAAK;;AAEL;AACA;AACA,kCAAkC,kBAAkB;AACpD;AACA,uBAAuB,OAAO;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;;AAEA,4CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,CAAC;;;;;;;;AC9FD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;;AAEA;AACA;AACA,cAAc;AACd;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB,iBAAiB;AACpC;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,iBAAiB,SAAS;AAC1B,4BAA4B;AAC5B;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA,yCAAyC,SAAS;AAClD;AACA;AACA;AACA;AACA,yCAAyC,SAAS;AAClD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,MAAM;AACjB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;;;;;;8CCzMA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC,qBAAqB;;AAEtB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,iFAAiF;;AAEjF;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,0BAA0B,sBAAsB;;AAEhD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,IAAI;AACd;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,iBAAiB,wBAAwB;AACzC;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,iBAAiB,uCAAuC;AACxD;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,OAAO;AACP;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,MAAM;AAChB,UAAU,OAAO;AACjB;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,UAAU,MAAM;AAChB;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA,qBAAqB,YAAY;AACjC;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,IAAI;AACd;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;AACH;;AAEA;AACA,UAAU,SAAS;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,KAAK;;AAEL;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,eAAe;AACf;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA,YAAY,SAAS;AACrB,YAAY,SAAS;AACrB;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA,YAAY,SAAS;AACrB;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA,CAAC;AACD;;;;;;;;ACroCA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;ACpBA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,mBAAmB,cAAc;AACjC;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,mBAAmB,cAAc;;AAEjC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,CAAC;;;;;;;AC/JD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,OAAO;AAClB,YAAY,MAAM;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpJA;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;;;;;;ACdA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc,QAAQ;AACjC,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB,YAAY;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC;AAClC,OAAO;AACP,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,oDAAoD;AACpE;AACA;AACA,WAAW,cAAc;AACzB,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,yBAAyB;AACtC;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,sCAAsC;AACjD,YAAY,QAAQ;AACpB;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B;AAC/B,+BAA+B;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA,kBAAkB,aAAa;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,aAAa;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;;;;;;;AC7kBA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2CAA2C;AAC3C;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpIA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrBA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA,uBAAuB;AACvB;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA,uBAAuB;AACvB;AACA;AACA;;AAEA;AACA;AACA,GAAG,IAAI;AACP;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA,8BAA8B;AAC9B;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;;;;;;ACnEA,gD;;;;;;ACAA,e","file":"av-rn.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"react-native\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([\"react-native\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"AV\"] = factory(require(\"react-native\"));\n\telse\n\t\troot[\"AV\"] = factory(root[\"react-native\"]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_50__) {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// identity function for calling harmony imports with the correct context\n \t__webpack_require__.i = function(value) { return value; };\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 30);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 77a21bff237eaad2029d","// Underscore.js 1.8.3\n// http://underscorejs.org\n// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n// Underscore may be freely distributed under the MIT license.\n\n(function() {\n\n // Baseline setup\n // --------------\n\n // Establish the root object, `window` in the browser, or `exports` on the server.\n var root = this;\n\n // Save the previous value of the `_` variable.\n var previousUnderscore = root._;\n\n // Save bytes in the minified (but not gzipped) version:\n var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;\n\n // Create quick reference variables for speed access to core prototypes.\n var\n push = ArrayProto.push,\n slice = ArrayProto.slice,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty;\n\n // All **ECMAScript 5** native function implementations that we hope to use\n // are declared here.\n var\n nativeIsArray = Array.isArray,\n nativeKeys = Object.keys,\n nativeBind = FuncProto.bind,\n nativeCreate = Object.create;\n\n // Naked function reference for surrogate-prototype-swapping.\n var Ctor = function(){};\n\n // Create a safe reference to the Underscore object for use below.\n var _ = function(obj) {\n if (obj instanceof _) return obj;\n if (!(this instanceof _)) return new _(obj);\n this._wrapped = obj;\n };\n\n // Export the Underscore object for **Node.js**, with\n // backwards-compatibility for the old `require()` API. If we're in\n // the browser, add `_` as a global object.\n if (typeof exports !== 'undefined') {\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = _;\n }\n exports._ = _;\n } else {\n root._ = _;\n }\n\n // Current version.\n _.VERSION = '1.8.3';\n\n // Internal function that returns an efficient (for current engines) version\n // of the passed-in callback, to be repeatedly applied in other Underscore\n // functions.\n var optimizeCb = function(func, context, argCount) {\n if (context === void 0) return func;\n switch (argCount == null ? 3 : argCount) {\n case 1: return function(value) {\n return func.call(context, value);\n };\n case 2: return function(value, other) {\n return func.call(context, value, other);\n };\n case 3: return function(value, index, collection) {\n return func.call(context, value, index, collection);\n };\n case 4: return function(accumulator, value, index, collection) {\n return func.call(context, accumulator, value, index, collection);\n };\n }\n return function() {\n return func.apply(context, arguments);\n };\n };\n\n // A mostly-internal function to generate callbacks that can be applied\n // to each element in a collection, returning the desired result — either\n // identity, an arbitrary callback, a property matcher, or a property accessor.\n var cb = function(value, context, argCount) {\n if (value == null) return _.identity;\n if (_.isFunction(value)) return optimizeCb(value, context, argCount);\n if (_.isObject(value)) return _.matcher(value);\n return _.property(value);\n };\n _.iteratee = function(value, context) {\n return cb(value, context, Infinity);\n };\n\n // An internal function for creating assigner functions.\n var createAssigner = function(keysFunc, undefinedOnly) {\n return function(obj) {\n var length = arguments.length;\n if (length < 2 || obj == null) return obj;\n for (var index = 1; index < length; index++) {\n var source = arguments[index],\n keys = keysFunc(source),\n l = keys.length;\n for (var i = 0; i < l; i++) {\n var key = keys[i];\n if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];\n }\n }\n return obj;\n };\n };\n\n // An internal function for creating a new object that inherits from another.\n var baseCreate = function(prototype) {\n if (!_.isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n };\n\n var property = function(key) {\n return function(obj) {\n return obj == null ? void 0 : obj[key];\n };\n };\n\n // Helper for collection methods to determine whether a collection\n // should be iterated as an array or as an object\n // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength\n // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094\n var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;\n var getLength = property('length');\n var isArrayLike = function(collection) {\n var length = getLength(collection);\n return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;\n };\n\n // Collection Functions\n // --------------------\n\n // The cornerstone, an `each` implementation, aka `forEach`.\n // Handles raw objects in addition to array-likes. Treats all\n // sparse array-likes as if they were dense.\n _.each = _.forEach = function(obj, iteratee, context) {\n iteratee = optimizeCb(iteratee, context);\n var i, length;\n if (isArrayLike(obj)) {\n for (i = 0, length = obj.length; i < length; i++) {\n iteratee(obj[i], i, obj);\n }\n } else {\n var keys = _.keys(obj);\n for (i = 0, length = keys.length; i < length; i++) {\n iteratee(obj[keys[i]], keys[i], obj);\n }\n }\n return obj;\n };\n\n // Return the results of applying the iteratee to each element.\n _.map = _.collect = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n results = Array(length);\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n results[index] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Create a reducing function iterating left or right.\n function createReduce(dir) {\n // Optimized iterator function as using arguments.length\n // in the main function will deoptimize the, see #1991.\n function iterator(obj, iteratee, memo, keys, index, length) {\n for (; index >= 0 && index < length; index += dir) {\n var currentKey = keys ? keys[index] : index;\n memo = iteratee(memo, obj[currentKey], currentKey, obj);\n }\n return memo;\n }\n\n return function(obj, iteratee, memo, context) {\n iteratee = optimizeCb(iteratee, context, 4);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n index = dir > 0 ? 0 : length - 1;\n // Determine the initial value if none is provided.\n if (arguments.length < 3) {\n memo = obj[keys ? keys[index] : index];\n index += dir;\n }\n return iterator(obj, iteratee, memo, keys, index, length);\n };\n }\n\n // **Reduce** builds up a single result from a list of values, aka `inject`,\n // or `foldl`.\n _.reduce = _.foldl = _.inject = createReduce(1);\n\n // The right-associative version of reduce, also known as `foldr`.\n _.reduceRight = _.foldr = createReduce(-1);\n\n // Return the first value which passes a truth test. Aliased as `detect`.\n _.find = _.detect = function(obj, predicate, context) {\n var key;\n if (isArrayLike(obj)) {\n key = _.findIndex(obj, predicate, context);\n } else {\n key = _.findKey(obj, predicate, context);\n }\n if (key !== void 0 && key !== -1) return obj[key];\n };\n\n // Return all the elements that pass a truth test.\n // Aliased as `select`.\n _.filter = _.select = function(obj, predicate, context) {\n var results = [];\n predicate = cb(predicate, context);\n _.each(obj, function(value, index, list) {\n if (predicate(value, index, list)) results.push(value);\n });\n return results;\n };\n\n // Return all the elements for which a truth test fails.\n _.reject = function(obj, predicate, context) {\n return _.filter(obj, _.negate(cb(predicate)), context);\n };\n\n // Determine whether all of the elements match a truth test.\n // Aliased as `all`.\n _.every = _.all = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (!predicate(obj[currentKey], currentKey, obj)) return false;\n }\n return true;\n };\n\n // Determine if at least one element in the object matches a truth test.\n // Aliased as `any`.\n _.some = _.any = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (predicate(obj[currentKey], currentKey, obj)) return true;\n }\n return false;\n };\n\n // Determine if the array or object contains a given item (using `===`).\n // Aliased as `includes` and `include`.\n _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n if (typeof fromIndex != 'number' || guard) fromIndex = 0;\n return _.indexOf(obj, item, fromIndex) >= 0;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n var isFunc = _.isFunction(method);\n return _.map(obj, function(value) {\n var func = isFunc ? method : value[method];\n return func == null ? func : func.apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, _.property(key));\n };\n\n // Convenience version of a common use case of `filter`: selecting only objects\n // containing specific `key:value` pairs.\n _.where = function(obj, attrs) {\n return _.filter(obj, _.matcher(attrs));\n };\n\n // Convenience version of a common use case of `find`: getting the first object\n // containing specific `key:value` pairs.\n _.findWhere = function(obj, attrs) {\n return _.find(obj, _.matcher(attrs));\n };\n\n // Return the maximum element (or element-based computation).\n _.max = function(obj, iteratee, context) {\n var result = -Infinity, lastComputed = -Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value > result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed > lastComputed || computed === -Infinity && result === -Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iteratee, context) {\n var result = Infinity, lastComputed = Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value < result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed < lastComputed || computed === Infinity && result === Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Shuffle a collection, using the modern version of the\n // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).\n _.shuffle = function(obj) {\n var set = isArrayLike(obj) ? obj : _.values(obj);\n var length = set.length;\n var shuffled = Array(length);\n for (var index = 0, rand; index < length; index++) {\n rand = _.random(0, index);\n if (rand !== index) shuffled[index] = shuffled[rand];\n shuffled[rand] = set[index];\n }\n return shuffled;\n };\n\n // Sample **n** random values from a collection.\n // If **n** is not specified, returns a single random element.\n // The internal `guard` argument allows it to work with `map`.\n _.sample = function(obj, n, guard) {\n if (n == null || guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n return obj[_.random(obj.length - 1)];\n }\n return _.shuffle(obj).slice(0, Math.max(0, n));\n };\n\n // Sort the object's values by a criterion produced by an iteratee.\n _.sortBy = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value: value,\n index: index,\n criteria: iteratee(value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria;\n var b = right.criteria;\n if (a !== b) {\n if (a > b || a === void 0) return 1;\n if (a < b || b === void 0) return -1;\n }\n return left.index - right.index;\n }), 'value');\n };\n\n // An internal function used for aggregate \"group by\" operations.\n var group = function(behavior) {\n return function(obj, iteratee, context) {\n var result = {};\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index) {\n var key = iteratee(value, index, obj);\n behavior(result, value, key);\n });\n return result;\n };\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key].push(value); else result[key] = [value];\n });\n\n // Indexes the object's values by a criterion, similar to `groupBy`, but for\n // when you know that your index values will be unique.\n _.indexBy = group(function(result, value, key) {\n result[key] = value;\n });\n\n // Counts instances of an object that group by a certain criterion. Pass\n // either a string attribute to count by, or a function that returns the\n // criterion.\n _.countBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key]++; else result[key] = 1;\n });\n\n // Safely create a real, live array from anything iterable.\n _.toArray = function(obj) {\n if (!obj) return [];\n if (_.isArray(obj)) return slice.call(obj);\n if (isArrayLike(obj)) return _.map(obj, _.identity);\n return _.values(obj);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n if (obj == null) return 0;\n return isArrayLike(obj) ? obj.length : _.keys(obj).length;\n };\n\n // Split a collection into two arrays: one whose elements all satisfy the given\n // predicate, and one whose elements all do not satisfy the predicate.\n _.partition = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var pass = [], fail = [];\n _.each(obj, function(value, key, obj) {\n (predicate(value, key, obj) ? pass : fail).push(value);\n });\n return [pass, fail];\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head` and `take`. The **guard** check\n // allows it to work with `_.map`.\n _.first = _.head = _.take = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[0];\n return _.initial(array, array.length - n);\n };\n\n // Returns everything but the last entry of the array. Especially useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array.\n _.last = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[array.length - 1];\n return _.rest(array, Math.max(0, array.length - n));\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.\n // Especially useful on the arguments object. Passing an **n** will return\n // the rest N values in the array.\n _.rest = _.tail = _.drop = function(array, n, guard) {\n return slice.call(array, n == null || guard ? 1 : n);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, _.identity);\n };\n\n // Internal implementation of a recursive `flatten` function.\n var flatten = function(input, shallow, strict, startIndex) {\n var output = [], idx = 0;\n for (var i = startIndex || 0, length = getLength(input); i < length; i++) {\n var value = input[i];\n if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {\n //flatten current level of array or arguments object\n if (!shallow) value = flatten(value, shallow, strict);\n var j = 0, len = value.length;\n output.length += len;\n while (j < len) {\n output[idx++] = value[j++];\n }\n } else if (!strict) {\n output[idx++] = value;\n }\n }\n return output;\n };\n\n // Flatten out an array, either recursively (by default), or just one level.\n _.flatten = function(array, shallow) {\n return flatten(array, shallow, false);\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iteratee, context) {\n if (!_.isBoolean(isSorted)) {\n context = iteratee;\n iteratee = isSorted;\n isSorted = false;\n }\n if (iteratee != null) iteratee = cb(iteratee, context);\n var result = [];\n var seen = [];\n for (var i = 0, length = getLength(array); i < length; i++) {\n var value = array[i],\n computed = iteratee ? iteratee(value, i, array) : value;\n if (isSorted) {\n if (!i || seen !== computed) result.push(value);\n seen = computed;\n } else if (iteratee) {\n if (!_.contains(seen, computed)) {\n seen.push(computed);\n result.push(value);\n }\n } else if (!_.contains(result, value)) {\n result.push(value);\n }\n }\n return result;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(flatten(arguments, true, true));\n };\n\n // Produce an array that contains every item shared between all the\n // passed-in arrays.\n _.intersection = function(array) {\n var result = [];\n var argsLength = arguments.length;\n for (var i = 0, length = getLength(array); i < length; i++) {\n var item = array[i];\n if (_.contains(result, item)) continue;\n for (var j = 1; j < argsLength; j++) {\n if (!_.contains(arguments[j], item)) break;\n }\n if (j === argsLength) result.push(item);\n }\n return result;\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = flatten(arguments, true, true, 1);\n return _.filter(array, function(value){\n return !_.contains(rest, value);\n });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function() {\n return _.unzip(arguments);\n };\n\n // Complement of _.zip. Unzip accepts an array of arrays and groups\n // each array's elements on shared indices\n _.unzip = function(array) {\n var length = array && _.max(array, getLength).length || 0;\n var result = Array(length);\n\n for (var index = 0; index < length; index++) {\n result[index] = _.pluck(array, index);\n }\n return result;\n };\n\n // Converts lists into objects. Pass either a single array of `[key, value]`\n // pairs, or two parallel arrays of the same length -- one of keys, and one of\n // the corresponding values.\n _.object = function(list, values) {\n var result = {};\n for (var i = 0, length = getLength(list); i < length; i++) {\n if (values) {\n result[list[i]] = values[i];\n } else {\n result[list[i][0]] = list[i][1];\n }\n }\n return result;\n };\n\n // Generator function to create the findIndex and findLastIndex functions\n function createPredicateIndexFinder(dir) {\n return function(array, predicate, context) {\n predicate = cb(predicate, context);\n var length = getLength(array);\n var index = dir > 0 ? 0 : length - 1;\n for (; index >= 0 && index < length; index += dir) {\n if (predicate(array[index], index, array)) return index;\n }\n return -1;\n };\n }\n\n // Returns the first index on an array-like that passes a predicate test\n _.findIndex = createPredicateIndexFinder(1);\n _.findLastIndex = createPredicateIndexFinder(-1);\n\n // Use a comparator function to figure out the smallest index at which\n // an object should be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iteratee, context) {\n iteratee = cb(iteratee, context, 1);\n var value = iteratee(obj);\n var low = 0, high = getLength(array);\n while (low < high) {\n var mid = Math.floor((low + high) / 2);\n if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;\n }\n return low;\n };\n\n // Generator function to create the indexOf and lastIndexOf functions\n function createIndexFinder(dir, predicateFind, sortedIndex) {\n return function(array, item, idx) {\n var i = 0, length = getLength(array);\n if (typeof idx == 'number') {\n if (dir > 0) {\n i = idx >= 0 ? idx : Math.max(idx + length, i);\n } else {\n length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;\n }\n } else if (sortedIndex && idx && length) {\n idx = sortedIndex(array, item);\n return array[idx] === item ? idx : -1;\n }\n if (item !== item) {\n idx = predicateFind(slice.call(array, i, length), _.isNaN);\n return idx >= 0 ? idx + i : -1;\n }\n for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {\n if (array[idx] === item) return idx;\n }\n return -1;\n };\n }\n\n // Return the position of the first occurrence of an item in an array,\n // or -1 if the item is not included in the array.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);\n _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (stop == null) {\n stop = start || 0;\n start = 0;\n }\n step = step || 1;\n\n var length = Math.max(Math.ceil((stop - start) / step), 0);\n var range = Array(length);\n\n for (var idx = 0; idx < length; idx++, start += step) {\n range[idx] = start;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Determines whether to execute a function as a constructor\n // or a normal function with the provided arguments\n var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {\n if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);\n var self = baseCreate(sourceFunc.prototype);\n var result = sourceFunc.apply(self, args);\n if (_.isObject(result)) return result;\n return self;\n };\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if\n // available.\n _.bind = function(func, context) {\n if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');\n var args = slice.call(arguments, 2);\n var bound = function() {\n return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));\n };\n return bound;\n };\n\n // Partially apply a function by creating a version that has had some of its\n // arguments pre-filled, without changing its dynamic `this` context. _ acts\n // as a placeholder, allowing any combination of arguments to be pre-filled.\n _.partial = function(func) {\n var boundArgs = slice.call(arguments, 1);\n var bound = function() {\n var position = 0, length = boundArgs.length;\n var args = Array(length);\n for (var i = 0; i < length; i++) {\n args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];\n }\n while (position < arguments.length) args.push(arguments[position++]);\n return executeBound(func, bound, this, this, args);\n };\n return bound;\n };\n\n // Bind a number of an object's methods to that object. Remaining arguments\n // are the method names to be bound. Useful for ensuring that all callbacks\n // defined on an object belong to it.\n _.bindAll = function(obj) {\n var i, length = arguments.length, key;\n if (length <= 1) throw new Error('bindAll must be passed function names');\n for (i = 1; i < length; i++) {\n key = arguments[i];\n obj[key] = _.bind(obj[key], obj);\n }\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memoize = function(key) {\n var cache = memoize.cache;\n var address = '' + (hasher ? hasher.apply(this, arguments) : key);\n if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);\n return cache[address];\n };\n memoize.cache = {};\n return memoize;\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){\n return func.apply(null, args);\n }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack has\n // cleared.\n _.defer = _.partial(_.delay, _, 1);\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time. Normally, the throttled function will run\n // as much as it can, without ever going more than once per `wait` duration;\n // but if you'd like to disable the execution on the leading edge, pass\n // `{leading: false}`. To disable execution on the trailing edge, ditto.\n _.throttle = function(func, wait, options) {\n var context, args, result;\n var timeout = null;\n var previous = 0;\n if (!options) options = {};\n var later = function() {\n previous = options.leading === false ? 0 : _.now();\n timeout = null;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n };\n return function() {\n var now = _.now();\n if (!previous && options.leading === false) previous = now;\n var remaining = wait - (now - previous);\n context = this;\n args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(later, remaining);\n }\n return result;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being called for\n // N milliseconds. If `immediate` is passed, trigger the function on the\n // leading edge, instead of the trailing.\n _.debounce = function(func, wait, immediate) {\n var timeout, args, context, timestamp, result;\n\n var later = function() {\n var last = _.now() - timestamp;\n\n if (last < wait && last >= 0) {\n timeout = setTimeout(later, wait - last);\n } else {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n }\n }\n };\n\n return function() {\n context = this;\n args = arguments;\n timestamp = _.now();\n var callNow = immediate && !timeout;\n if (!timeout) timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n context = args = null;\n }\n\n return result;\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return _.partial(wrapper, func);\n };\n\n // Returns a negated version of the passed-in predicate.\n _.negate = function(predicate) {\n return function() {\n return !predicate.apply(this, arguments);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var args = arguments;\n var start = args.length - 1;\n return function() {\n var i = start;\n var result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n };\n\n // Returns a function that will only be executed on and after the Nth call.\n _.after = function(times, func) {\n return function() {\n if (--times < 1) {\n return func.apply(this, arguments);\n }\n };\n };\n\n // Returns a function that will only be executed up to (but not including) the Nth call.\n _.before = function(times, func) {\n var memo;\n return function() {\n if (--times > 0) {\n memo = func.apply(this, arguments);\n }\n if (times <= 1) func = null;\n return memo;\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = _.partial(_.before, 2);\n\n // Object Functions\n // ----------------\n\n // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.\n var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n function collectNonEnumProps(obj, keys) {\n var nonEnumIdx = nonEnumerableProps.length;\n var constructor = obj.constructor;\n var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;\n\n // Constructor is a special case.\n var prop = 'constructor';\n if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);\n\n while (nonEnumIdx--) {\n prop = nonEnumerableProps[nonEnumIdx];\n if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {\n keys.push(prop);\n }\n }\n }\n\n // Retrieve the names of an object's own properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = function(obj) {\n if (!_.isObject(obj)) return [];\n if (nativeKeys) return nativeKeys(obj);\n var keys = [];\n for (var key in obj) if (_.has(obj, key)) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve all the property names of an object.\n _.allKeys = function(obj) {\n if (!_.isObject(obj)) return [];\n var keys = [];\n for (var key in obj) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var values = Array(length);\n for (var i = 0; i < length; i++) {\n values[i] = obj[keys[i]];\n }\n return values;\n };\n\n // Returns the results of applying the iteratee to each element of the object\n // In contrast to _.map it returns an object\n _.mapObject = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = _.keys(obj),\n length = keys.length,\n results = {},\n currentKey;\n for (var index = 0; index < length; index++) {\n currentKey = keys[index];\n results[currentKey] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Convert an object into a list of `[key, value]` pairs.\n _.pairs = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var pairs = Array(length);\n for (var i = 0; i < length; i++) {\n pairs[i] = [keys[i], obj[keys[i]]];\n }\n return pairs;\n };\n\n // Invert the keys and values of an object. The values must be serializable.\n _.invert = function(obj) {\n var result = {};\n var keys = _.keys(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n result[obj[keys[i]]] = keys[i];\n }\n return result;\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = createAssigner(_.allKeys);\n\n // Assigns a given object with all the own properties in the passed-in object(s)\n // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n _.extendOwn = _.assign = createAssigner(_.keys);\n\n // Returns the first key on an object that passes a predicate test\n _.findKey = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = _.keys(obj), key;\n for (var i = 0, length = keys.length; i < length; i++) {\n key = keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n };\n\n // Return a copy of the object only containing the whitelisted properties.\n _.pick = function(object, oiteratee, context) {\n var result = {}, obj = object, iteratee, keys;\n if (obj == null) return result;\n if (_.isFunction(oiteratee)) {\n keys = _.allKeys(obj);\n iteratee = optimizeCb(oiteratee, context);\n } else {\n keys = flatten(arguments, false, false, 1);\n iteratee = function(value, key, obj) { return key in obj; };\n obj = Object(obj);\n }\n for (var i = 0, length = keys.length; i < length; i++) {\n var key = keys[i];\n var value = obj[key];\n if (iteratee(value, key, obj)) result[key] = value;\n }\n return result;\n };\n\n // Return a copy of the object without the blacklisted properties.\n _.omit = function(obj, iteratee, context) {\n if (_.isFunction(iteratee)) {\n iteratee = _.negate(iteratee);\n } else {\n var keys = _.map(flatten(arguments, false, false, 1), String);\n iteratee = function(value, key) {\n return !_.contains(keys, key);\n };\n }\n return _.pick(obj, iteratee, context);\n };\n\n // Fill in a given object with default properties.\n _.defaults = createAssigner(_.allKeys, true);\n\n // Creates an object that inherits from the given prototype object.\n // If additional properties are provided then they will be added to the\n // created object.\n _.create = function(prototype, props) {\n var result = baseCreate(prototype);\n if (props) _.extendOwn(result, props);\n return result;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Returns whether an object has a given set of `key:value` pairs.\n _.isMatch = function(object, attrs) {\n var keys = _.keys(attrs), length = keys.length;\n if (object == null) return !length;\n var obj = Object(object);\n for (var i = 0; i < length; i++) {\n var key = keys[i];\n if (attrs[key] !== obj[key] || !(key in obj)) return false;\n }\n return true;\n };\n\n\n // Internal recursive comparison function for `isEqual`.\n var eq = function(a, b, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) return a !== 0 || 1 / a === 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwrap any wrapped objects.\n if (a instanceof _) a = a._wrapped;\n if (b instanceof _) b = b._wrapped;\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case '[object RegExp]':\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return '' + a === '' + b;\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN\n if (+a !== +a) return +b !== +b;\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case '[object Date]':\n case '[object Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n }\n\n var areArrays = className === '[object Array]';\n if (!areArrays) {\n if (typeof a != 'object' || typeof b != 'object') return false;\n\n // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n var aCtor = a.constructor, bCtor = b.constructor;\n if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&\n _.isFunction(bCtor) && bCtor instanceof bCtor)\n && ('constructor' in a && 'constructor' in b)) {\n return false;\n }\n }\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) return bStack[length] === b;\n }\n\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n\n // Recursively compare objects and arrays.\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n if (length !== b.length) return false;\n // Deep compare the contents, ignoring non-numeric properties.\n while (length--) {\n if (!eq(a[length], b[length], aStack, bStack)) return false;\n }\n } else {\n // Deep compare objects.\n var keys = _.keys(a), key;\n length = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n if (_.keys(b).length !== length) return false;\n while (length--) {\n // Deep compare each member\n key = keys[length];\n if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return true;\n };\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (obj == null) return true;\n if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;\n return _.keys(obj).length === 0;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj.nodeType === 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) === '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n var type = typeof obj;\n return type === 'function' || type === 'object' && !!obj;\n };\n\n // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.\n _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {\n _['is' + name] = function(obj) {\n return toString.call(obj) === '[object ' + name + ']';\n };\n });\n\n // Define a fallback version of the method in browsers (ahem, IE < 9), where\n // there isn't any inspectable \"Arguments\" type.\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return _.has(obj, 'callee');\n };\n }\n\n // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,\n // IE 11 (#1621), and in Safari 8 (#1929).\n if (typeof /./ != 'function' && typeof Int8Array != 'object') {\n _.isFunction = function(obj) {\n return typeof obj == 'function' || false;\n };\n }\n\n // Is a given object a finite number?\n _.isFinite = function(obj) {\n return isFinite(obj) && !isNaN(parseFloat(obj));\n };\n\n // Is the given value `NaN`? (NaN is the only number which does not equal itself).\n _.isNaN = function(obj) {\n return _.isNumber(obj) && obj !== +obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) === '[object Boolean]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Shortcut function for checking if an object has a given property directly\n // on itself (in other words, not on a prototype).\n _.has = function(obj, key) {\n return obj != null && hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning the `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iteratees.\n _.identity = function(value) {\n return value;\n };\n\n // Predicate-generating functions. Often useful outside of Underscore.\n _.constant = function(value) {\n return function() {\n return value;\n };\n };\n\n _.noop = function(){};\n\n _.property = property;\n\n // Generates a function for a given object that returns a given property.\n _.propertyOf = function(obj) {\n return obj == null ? function(){} : function(key) {\n return obj[key];\n };\n };\n\n // Returns a predicate for checking whether an object has a given set of\n // `key:value` pairs.\n _.matcher = _.matches = function(attrs) {\n attrs = _.extendOwn({}, attrs);\n return function(obj) {\n return _.isMatch(obj, attrs);\n };\n };\n\n // Run a function **n** times.\n _.times = function(n, iteratee, context) {\n var accum = Array(Math.max(0, n));\n iteratee = optimizeCb(iteratee, context, 1);\n for (var i = 0; i < n; i++) accum[i] = iteratee(i);\n return accum;\n };\n\n // Return a random integer between min and max (inclusive).\n _.random = function(min, max) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n };\n\n // A (possibly faster) way to get the current timestamp as an integer.\n _.now = Date.now || function() {\n return new Date().getTime();\n };\n\n // List of HTML entities for escaping.\n var escapeMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`'\n };\n var unescapeMap = _.invert(escapeMap);\n\n // Functions for escaping and unescaping strings to/from HTML interpolation.\n var createEscaper = function(map) {\n var escaper = function(match) {\n return map[match];\n };\n // Regexes for identifying a key that needs to be escaped\n var source = '(?:' + _.keys(map).join('|') + ')';\n var testRegexp = RegExp(source);\n var replaceRegexp = RegExp(source, 'g');\n return function(string) {\n string = string == null ? '' : '' + string;\n return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;\n };\n };\n _.escape = createEscaper(escapeMap);\n _.unescape = createEscaper(unescapeMap);\n\n // If the value of the named `property` is a function then invoke it with the\n // `object` as context; otherwise, return it.\n _.result = function(object, property, fallback) {\n var value = object == null ? void 0 : object[property];\n if (value === void 0) {\n value = fallback;\n }\n return _.isFunction(value) ? value.call(object) : value;\n };\n\n // Generate a unique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = ++idCounter + '';\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /(.)^/;\n\n // Certain characters need to be escaped so that they can be put into a\n // string literal.\n var escapes = {\n \"'\": \"'\",\n '\\\\': '\\\\',\n '\\r': 'r',\n '\\n': 'n',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n var escaper = /\\\\|'|\\r|\\n|\\u2028|\\u2029/g;\n\n var escapeChar = function(match) {\n return '\\\\' + escapes[match];\n };\n\n // JavaScript micro-templating, similar to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n // NB: `oldSettings` only exists for backwards compatibility.\n _.template = function(text, settings, oldSettings) {\n if (!settings && oldSettings) settings = oldSettings;\n settings = _.defaults({}, settings, _.templateSettings);\n\n // Combine delimiters into one regular expression via alternation.\n var matcher = RegExp([\n (settings.escape || noMatch).source,\n (settings.interpolate || noMatch).source,\n (settings.evaluate || noMatch).source\n ].join('|') + '|$', 'g');\n\n // Compile the template source, escaping string literals appropriately.\n var index = 0;\n var source = \"__p+='\";\n text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {\n source += text.slice(index, offset).replace(escaper, escapeChar);\n index = offset + match.length;\n\n if (escape) {\n source += \"'+\\n((__t=(\" + escape + \"))==null?'':_.escape(__t))+\\n'\";\n } else if (interpolate) {\n source += \"'+\\n((__t=(\" + interpolate + \"))==null?'':__t)+\\n'\";\n } else if (evaluate) {\n source += \"';\\n\" + evaluate + \"\\n__p+='\";\n }\n\n // Adobe VMs need the match returned to produce the correct offest.\n return match;\n });\n source += \"';\\n\";\n\n // If a variable is not specified, place data values in local scope.\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = \"var __t,__p='',__j=Array.prototype.join,\" +\n \"print=function(){__p+=__j.call(arguments,'');};\\n\" +\n source + 'return __p;\\n';\n\n try {\n var render = new Function(settings.variable || 'obj', '_', source);\n } catch (e) {\n e.source = source;\n throw e;\n }\n\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n // Provide the compiled source as a convenience for precompilation.\n var argument = settings.variable || 'obj';\n template.source = 'function(' + argument + '){\\n' + source + '}';\n\n return template;\n };\n\n // Add a \"chain\" function. Start chaining a wrapped Underscore object.\n _.chain = function(obj) {\n var instance = _(obj);\n instance._chain = true;\n return instance;\n };\n\n // OOP\n // ---------------\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n\n // Helper function to continue chaining intermediate results.\n var result = function(instance, obj) {\n return instance._chain ? _(obj).chain() : obj;\n };\n\n // Add your own custom functions to the Underscore object.\n _.mixin = function(obj) {\n _.each(_.functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return result(this, func.apply(_, args));\n };\n });\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n var obj = this._wrapped;\n method.apply(obj, arguments);\n if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];\n return result(this, obj);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n _.each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n return result(this, method.apply(this._wrapped, arguments));\n };\n });\n\n // Extracts the result from a wrapped and chained object.\n _.prototype.value = function() {\n return this._wrapped;\n };\n\n // Provide unwrapping proxy for some methods used in engine operations\n // such as arithmetic and JSON stringification.\n _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;\n\n _.prototype.toString = function() {\n return '' + this._wrapped;\n };\n\n // AMD registration happens at the end for compatibility with AMD loaders\n // that may not enforce next-turn semantics on modules. Even though general\n // practice for AMD registration is to be anonymous, underscore registers\n // as a named module because, like jQuery, it is a base library that is\n // popular enough to be bundled in a third party lib, but not be part of\n // an AMD load request. Those cases could generate an error when an\n // anonymous define() is called outside of a loader request.\n if (typeof define === 'function' && define.amd) {\n define('underscore', [], function() {\n return _;\n });\n }\n}.call(this));\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/underscore/underscore.js\n// module id = 0\n// module chunks = 0","var _ = require('underscore');\nvar Promise = require('es6-promise').Promise;\n\nPromise._continueWhile = function(predicate, asyncFunction) {\n if (predicate()) {\n return asyncFunction().then(function() {\n return Promise._continueWhile(predicate, asyncFunction);\n });\n }\n return Promise.resolve();\n};\n\nmodule.exports = Promise;\n\n\n\n// WEBPACK FOOTER //\n// ./src/promise.js","const request = require('superagent');\nconst debug = require('debug')('leancloud:request');\nconst md5 = require('md5');\nconst Promise = require('./promise');\nconst Cache = require('./cache');\nconst AVError = require('./error');\nconst AV = require('./av');\nconst _ = require('underscore');\nconst {\n getSessionToken,\n} = require('./utils');\n\nlet getServerURLPromise;\n\n// 服务器请求的节点 host\nconst API_HOST = {\n cn: 'https://api.leancloud.cn',\n us: 'https://us-api.leancloud.cn',\n};\n\n// 计算 X-LC-Sign 的签名方法\nconst sign = (key, isMasterKey) => {\n const now = new Date().getTime();\n const signature = md5(now + key);\n if (isMasterKey) {\n return `${signature},${now},master`;\n }\n return `${signature},${now}`;\n};\n\nlet requestsCount = 0;\n\nconst ajax = (method, resourceUrl, data, headers = {}, onprogress) => {\n const count = requestsCount++;\n\n debug(`request(${count})`, method, resourceUrl, data, headers);\n\n return new Promise((resolve, reject) => {\n const req = request(method, resourceUrl)\n .set(headers)\n .send(data);\n if (onprogress) {\n req.on('progress', onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(`response(${count})`, res.status, res.body || res.text, res.header);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n return resolve(res.body);\n });\n });\n};\n\nconst setAppKey = (headers, signKey) => {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.applicationKey);\n } else {\n headers['X-LC-Key'] = AV.applicationKey;\n }\n};\n\nconst setHeaders = (authOptions = {}, signKey) => {\n const headers = {\n 'X-LC-Id': AV.applicationId,\n 'Content-Type': 'application/json;charset=UTF-8',\n };\n let useMasterKey = false;\n if (typeof authOptions.useMasterKey === 'boolean') {\n useMasterKey = authOptions.useMasterKey;\n } else if (typeof AV._useMasterKey === 'boolean') {\n useMasterKey = AV._useMasterKey;\n }\n if (useMasterKey) {\n if (AV.masterKey) {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.masterKey, true);\n } else {\n headers['X-LC-Key'] = `${AV.masterKey},master`;\n }\n } else {\n console.warn('masterKey is not set, fall back to use appKey');\n setAppKey(headers, signKey);\n }\n } else {\n setAppKey(headers, signKey);\n }\n if (AV.hookKey) {\n headers['X-LC-Hook-Key'] = AV.hookKey;\n }\n if (AV._config.applicationProduction !== null) {\n headers['X-LC-Prod'] = String(AV._config.applicationProduction);\n }\n headers[!process.env.CLIENT_PLATFORM ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent;\n\n return Promise.resolve().then(() => {\n // Pass the session token\n const sessionToken = getSessionToken(authOptions);\n if (sessionToken) {\n headers['X-LC-Session'] = sessionToken;\n } else if (!AV._config.disableCurrentUser) {\n return AV.User.currentAsync().then((currentUser) => {\n if (currentUser && currentUser._sessionToken) {\n headers['X-LC-Session'] = currentUser._sessionToken;\n }\n return headers;\n });\n }\n return headers;\n });\n};\n\nconst createApiUrl = (route, className, objectId, method, dataObject) => {\n // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉\n if (AV.serverURL) {\n AV._config.APIServerURL = AV.serverURL;\n console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.');\n }\n\n let apiURL = AV._config.APIServerURL || API_HOST.cn;\n\n if (apiURL.charAt(apiURL.length - 1) !== '/') {\n apiURL += '/';\n }\n apiURL += `1.1/${route}`;\n if (className) {\n apiURL += `/${className}`;\n }\n if (objectId) {\n apiURL += `/${objectId}`;\n }\n if ((route === 'users' || route === 'classes') && dataObject) {\n apiURL += '?';\n if (dataObject._fetchWhenSave) {\n delete dataObject._fetchWhenSave;\n apiURL += '&new=true';\n }\n if (dataObject._where) {\n apiURL += `&where=${encodeURIComponent(JSON.stringify(dataObject._where))}`;\n delete dataObject._where;\n }\n }\n\n if (method.toLowerCase() === 'get') {\n if (apiURL.indexOf('?') === -1) {\n apiURL += '?';\n }\n for (const k in dataObject) {\n if (typeof dataObject[k] === 'object') {\n dataObject[k] = JSON.stringify(dataObject[k]);\n }\n apiURL += `&${k}=${encodeURIComponent(dataObject[k])}`;\n }\n }\n\n return apiURL;\n};\n\nconst cacheServerURL = (serverURL, ttl) => {\n if (typeof ttl !== 'number') {\n ttl = 3600;\n }\n return Cache.setAsync('APIServerURL', serverURL, ttl * 1000);\n};\n\n// handle AV._request Error\nconst handleError = (error) => {\n return new Promise((resolve, reject) => {\n /**\n When API request need to redirect to the right location,\n can't use browser redirect by http status 307, as the reason of CORS,\n so API server response http status 410 and the param \"location\" for this case.\n */\n if (error.statusCode === 410) {\n cacheServerURL(error.response.api_server, error.response.ttl).then(() => {\n resolve(error.response.location);\n }).catch(reject);\n } else {\n let errorJSON = {\n code: error.code || -1,\n error: error.message || error.responseText\n };\n if (error.response && error.response.code) {\n errorJSON = error.response;\n } else if (error.responseText) {\n try {\n errorJSON = JSON.parse(error.responseText);\n } catch (e) {\n // If we fail to parse the error text, that's okay.\n }\n }\n\n // Transform the error into an instance of AVError by trying to parse\n // the error string as JSON.\n reject(new AVError(errorJSON.code, errorJSON.error));\n }\n });\n};\n\nconst setServerUrl = (serverURL) => {\n AV._config.APIServerURL = `https://${serverURL}`;\n\n // 根据新 URL 重新设置区域\n const newRegion = _.findKey(API_HOST, item => item === AV._config.APIServerURL);\n if (newRegion) {\n AV._config.region = newRegion;\n }\n};\n\nconst refreshServerUrlByRouter = () => {\n const url = `https://app-router.leancloud.cn/1/route?appId=${AV.applicationId}`;\n return ajax('get', url).then(servers => {\n if (servers.api_server) {\n setServerUrl(servers.api_server);\n return cacheServerURL(servers.api_server, servers.ttl);\n }\n }, error => {\n // bypass all non-4XX errors\n if (error.statusCode >= 400 && error.statusCode < 500) {\n throw error;\n }\n });\n};\n\nconst setServerUrlByRegion = (region = 'cn') => {\n getServerURLPromise = new Promise((resolve, reject) => {\n // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router\n if (AV._config.APIServerURL) {\n resolve();\n return;\n }\n // if not china server region, do not use router\n if (region === 'cn') {\n return Cache.getAsync('APIServerURL').then((serverURL) => {\n if (serverURL) {\n setServerUrl(serverURL);\n } else {\n return refreshServerUrlByRouter();\n }\n }).then(() => {\n resolve();\n }).catch((error) => {\n reject(error);\n });\n } else {\n AV._config.region = region;\n AV._config.APIServerURL = API_HOST[region];\n resolve();\n }\n });\n};\n\n/**\n * route is classes, users, login, etc.\n * objectId is null if there is no associated objectId.\n * method is the http method for the REST API.\n * dataObject is the payload as an object, or null if there is none.\n * @ignore\n */\nconst AVRequest = (route, className, objectId, method, dataObject = {}, authOptions) => {\n if (!AV.applicationId) {\n throw new Error('You must specify your applicationId using AV.init()');\n }\n\n if (!AV.applicationKey && !AV.masterKey) {\n throw new Error('You must specify a AppKey using AV.init()');\n }\n\n if (!getServerURLPromise) {\n return Promise.reject(new Error('Not initialized'));\n }\n return getServerURLPromise.then(() => {\n const apiURL = createApiUrl(route, className, objectId, method, dataObject);\n return setHeaders(authOptions, route !== 'bigquery').then(\n headers => ajax(method, apiURL, dataObject, headers)\n .then(\n null,\n res => handleError(res)\n .then(location => ajax(method, location, dataObject, headers))\n )\n );\n });\n};\n\nmodule.exports = {\n ajax,\n request: AVRequest,\n setServerUrlByRegion,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/request.js","const _ = require('underscore');\n\n/**\n * @class AV.Error\n */\n\nfunction AVError(code, message) {\n const error = new Error(message);\n error.code = code;\n return error;\n}\n\n_.extend(AVError, /** @lends AV.Error */ {\n /**\n * Error code indicating some error other than those enumerated here.\n * @constant\n */\n OTHER_CAUSE: -1,\n\n /**\n * Error code indicating that something has gone wrong with the server.\n * If you get this error code, it is AV's fault. Contact us at\n * https://avoscloud.com/help\n * @constant\n */\n INTERNAL_SERVER_ERROR: 1,\n\n /**\n * Error code indicating the connection to the AV servers failed.\n * @constant\n */\n CONNECTION_FAILED: 100,\n\n /**\n * Error code indicating the specified object doesn't exist.\n * @constant\n */\n OBJECT_NOT_FOUND: 101,\n\n /**\n * Error code indicating you tried to query with a datatype that doesn't\n * support it, like exact matching an array or object.\n * @constant\n */\n INVALID_QUERY: 102,\n\n /**\n * Error code indicating a missing or invalid classname. Classnames are\n * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the\n * only valid characters.\n * @constant\n */\n INVALID_CLASS_NAME: 103,\n\n /**\n * Error code indicating an unspecified object id.\n * @constant\n */\n MISSING_OBJECT_ID: 104,\n\n /**\n * Error code indicating an invalid key name. Keys are case-sensitive. They\n * must start with a letter, and a-zA-Z0-9_ are the only valid characters.\n * @constant\n */\n INVALID_KEY_NAME: 105,\n\n /**\n * Error code indicating a malformed pointer. You should not see this unless\n * you have been mucking about changing internal AV code.\n * @constant\n */\n INVALID_POINTER: 106,\n\n /**\n * Error code indicating that badly formed JSON was received upstream. This\n * either indicates you have done something unusual with modifying how\n * things encode to JSON, or the network is failing badly.\n * @constant\n */\n INVALID_JSON: 107,\n\n /**\n * Error code indicating that the feature you tried to access is only\n * available internally for testing purposes.\n * @constant\n */\n COMMAND_UNAVAILABLE: 108,\n\n /**\n * You must call AV.initialize before using the AV library.\n * @constant\n */\n NOT_INITIALIZED: 109,\n\n /**\n * Error code indicating that a field was set to an inconsistent type.\n * @constant\n */\n INCORRECT_TYPE: 111,\n\n /**\n * Error code indicating an invalid channel name. A channel name is either\n * an empty string (the broadcast channel) or contains only a-zA-Z0-9_\n * characters.\n * @constant\n */\n INVALID_CHANNEL_NAME: 112,\n\n /**\n * Error code indicating that push is misconfigured.\n * @constant\n */\n PUSH_MISCONFIGURED: 115,\n\n /**\n * Error code indicating that the object is too large.\n * @constant\n */\n OBJECT_TOO_LARGE: 116,\n\n /**\n * Error code indicating that the operation isn't allowed for clients.\n * @constant\n */\n OPERATION_FORBIDDEN: 119,\n\n /**\n * Error code indicating the result was not found in the cache.\n * @constant\n */\n CACHE_MISS: 120,\n\n /**\n * Error code indicating that an invalid key was used in a nested\n * JSONObject.\n * @constant\n */\n INVALID_NESTED_KEY: 121,\n\n /**\n * Error code indicating that an invalid filename was used for AVFile.\n * A valid file name contains only a-zA-Z0-9_. characters and is between 1\n * and 128 characters.\n * @constant\n */\n INVALID_FILE_NAME: 122,\n\n /**\n * Error code indicating an invalid ACL was provided.\n * @constant\n */\n INVALID_ACL: 123,\n\n /**\n * Error code indicating that the request timed out on the server. Typically\n * this indicates that the request is too expensive to run.\n * @constant\n */\n TIMEOUT: 124,\n\n /**\n * Error code indicating that the email address was invalid.\n * @constant\n */\n INVALID_EMAIL_ADDRESS: 125,\n\n /**\n * Error code indicating a missing content type.\n * @constant\n */\n MISSING_CONTENT_TYPE: 126,\n\n /**\n * Error code indicating a missing content length.\n * @constant\n */\n MISSING_CONTENT_LENGTH: 127,\n\n /**\n * Error code indicating an invalid content length.\n * @constant\n */\n INVALID_CONTENT_LENGTH: 128,\n\n /**\n * Error code indicating a file that was too large.\n * @constant\n */\n FILE_TOO_LARGE: 129,\n\n /**\n * Error code indicating an error saving a file.\n * @constant\n */\n FILE_SAVE_ERROR: 130,\n\n /**\n * Error code indicating an error deleting a file.\n * @constant\n */\n FILE_DELETE_ERROR: 153,\n\n /**\n * Error code indicating that a unique field was given a value that is\n * already taken.\n * @constant\n */\n DUPLICATE_VALUE: 137,\n\n /**\n * Error code indicating that a role's name is invalid.\n * @constant\n */\n INVALID_ROLE_NAME: 139,\n\n /**\n * Error code indicating that an application quota was exceeded. Upgrade to\n * resolve.\n * @constant\n */\n EXCEEDED_QUOTA: 140,\n\n /**\n * Error code indicating that a Cloud Code script failed.\n * @constant\n */\n SCRIPT_FAILED: 141,\n\n /**\n * Error code indicating that a Cloud Code validation failed.\n * @constant\n */\n VALIDATION_ERROR: 142,\n\n /**\n * Error code indicating that invalid image data was provided.\n * @constant\n */\n INVALID_IMAGE_DATA: 150,\n\n /**\n * Error code indicating an unsaved file.\n * @constant\n */\n UNSAVED_FILE_ERROR: 151,\n\n /**\n * Error code indicating an invalid push time.\n */\n INVALID_PUSH_TIME_ERROR: 152,\n\n /**\n * Error code indicating that the username is missing or empty.\n * @constant\n */\n USERNAME_MISSING: 200,\n\n /**\n * Error code indicating that the password is missing or empty.\n * @constant\n */\n PASSWORD_MISSING: 201,\n\n /**\n * Error code indicating that the username has already been taken.\n * @constant\n */\n USERNAME_TAKEN: 202,\n\n /**\n * Error code indicating that the email has already been taken.\n * @constant\n */\n EMAIL_TAKEN: 203,\n\n /**\n * Error code indicating that the email is missing, but must be specified.\n * @constant\n */\n EMAIL_MISSING: 204,\n\n /**\n * Error code indicating that a user with the specified email was not found.\n * @constant\n */\n EMAIL_NOT_FOUND: 205,\n\n /**\n * Error code indicating that a user object without a valid session could\n * not be altered.\n * @constant\n */\n SESSION_MISSING: 206,\n\n /**\n * Error code indicating that a user can only be created through signup.\n * @constant\n */\n MUST_CREATE_USER_THROUGH_SIGNUP: 207,\n\n /**\n * Error code indicating that an an account being linked is already linked\n * to another user.\n * @constant\n */\n ACCOUNT_ALREADY_LINKED: 208,\n\n /**\n * Error code indicating that a user cannot be linked to an account because\n * that account's id could not be found.\n * @constant\n */\n LINKED_ID_MISSING: 250,\n\n /**\n * Error code indicating that a user with a linked (e.g. Facebook) account\n * has an invalid session.\n * @constant\n */\n INVALID_LINKED_SESSION: 251,\n\n /**\n * Error code indicating that a service being linked (e.g. Facebook or\n * Twitter) is unsupported.\n * @constant\n */\n UNSUPPORTED_SERVICE: 252,\n /**\n * Error code indicating a real error code is unavailable because\n * we had to use an XDomainRequest object to allow CORS requests in\n * Internet Explorer, which strips the body from HTTP responses that have\n * a non-2XX status code.\n * @constant\n */\n X_DOMAIN_REQUEST: 602,\n});\n\nmodule.exports = AVError;\n\n\n\n// WEBPACK FOOTER //\n// ./src/error.js","const _ = require('underscore');\n\n// Helper function to check null or undefined.\nconst isNullOrUndefined = (x) => _.isNull(x) || _.isUndefined(x);\n\nconst ensureArray = target => {\n if (_.isArray(target)) {\n return target;\n }\n if (target === undefined || target === null) {\n return [];\n }\n return [target];\n};\n\nconst getSessionToken = (authOptions) => {\n if (authOptions.sessionToken) {\n return authOptions.sessionToken;\n }\n if (\n authOptions.user && typeof authOptions.user.getSessionToken === 'function'\n ) {\n return authOptions.user.getSessionToken();\n }\n};\n\nconst tap = interceptor => value => ((interceptor(value), value));\n\nmodule.exports = {\n isNullOrUndefined,\n ensureArray,\n getSessionToken,\n tap,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/index.js","/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n 'lightseagreen',\n 'forestgreen',\n 'goldenrod',\n 'dodgerblue',\n 'darkorchid',\n 'crimson'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/browser.js\n// module id = 5\n// module chunks = 0","const _ = require('underscore');\nconst userAgent = require('./ua');\nconst {\n isNullOrUndefined,\n} = require('./utils');\n\nconst AV = global.AV || {};\n\n// All internal configuration items\nAV._config = AV._config || {};\nconst AVConfig = AV._config;\n\n_.extend(AVConfig, {\n\n // 服务器节点地区,默认中国大陆\n region: 'cn',\n\n // 服务器的 URL,默认初始化时被设置为大陆节点地址\n APIServerURL: AVConfig.APIServerURL || '',\n\n // 禁用 currentUser,通常用于多用户环境\n disableCurrentUser: false,\n\n // Internal config can modifie the UserAgent\n userAgent,\n\n // set production environment or test environment\n // 1: production environment, 0: test environment, null: default environment\n applicationProduction: null,\n});\n\n/**\n * Contains all AV API classes and functions.\n * @namespace AV\n */\n\n// Helpers\n// -------\n\n// Shared empty constructor function to aid in prototype-chain creation.\nvar EmptyConstructor = function() {};\n\n// Helper function to correctly set up the prototype chain, for subclasses.\n// Similar to `goog.inherits`, but uses a hash of prototype properties and\n// class properties to be extended.\nvar inherits = function(parent, protoProps, staticProps) {\n var child;\n\n // The constructor function for the new subclass is either defined by you\n // (the \"constructor\" property in your `extend` definition), or defaulted\n // by us to simply call the parent's constructor.\n if (protoProps && protoProps.hasOwnProperty('constructor')) {\n child = protoProps.constructor;\n } else {\n /** @ignore */\n child = function(){ parent.apply(this, arguments); };\n }\n\n // Inherit class (static) properties from parent.\n _.extend(child, parent);\n\n // Set the prototype chain to inherit from `parent`, without calling\n // `parent`'s constructor function.\n EmptyConstructor.prototype = parent.prototype;\n child.prototype = new EmptyConstructor();\n\n // Add prototype properties (instance properties) to the subclass,\n // if supplied.\n if (protoProps) {\n _.extend(child.prototype, protoProps);\n }\n\n // Add static properties to the constructor function, if supplied.\n if (staticProps) {\n _.extend(child, staticProps);\n }\n\n // Correctly set child's `prototype.constructor`.\n child.prototype.constructor = child;\n\n // Set a convenience property in case the parent's prototype is\n // needed later.\n child.__super__ = parent.prototype;\n\n return child;\n};\n\n/**\n * Call this method to set production environment variable.\n * @function AV.setProduction\n * @param {Boolean} production True is production environment,and\n * it's true by default.\n */\nAV.setProduction = (production) => {\n if (!isNullOrUndefined(production)) {\n AVConfig.applicationProduction = production ? 1 : 0;\n } else {\n // change to default value\n AVConfig.applicationProduction = null;\n }\n};\n\n/**\n * Returns prefix for localStorage keys used by this instance of AV.\n * @param {String} path The relative suffix to append to it.\n * null or undefined is treated as the empty string.\n * @return {String} The full key name.\n * @private\n */\nAV._getAVPath = function(path) {\n if (!AV.applicationId) {\n throw new Error(\"You need to call AV.initialize before using AV.\");\n }\n if (!path) {\n path = \"\";\n }\n if (!_.isString(path)) {\n throw new Error(\"Tried to get a localStorage path that wasn't a String.\");\n }\n if (path[0] === \"/\") {\n path = path.substring(1);\n }\n return \"AV/\" + AV.applicationId + \"/\" + path;\n};\n\n/**\n * Returns the unique string for this app on this machine.\n * Gets reset when localStorage is cleared.\n * @private\n */\nAV._installationId = null;\nAV._getInstallationId = function() {\n // See if it's cached in RAM.\n if (AV._installationId) {\n return AV.Promise.resolve(AV._installationId);\n }\n\n // Try to get it from localStorage.\n var path = AV._getAVPath(\"installationId\");\n return AV.localStorage.getItemAsync(path).then(function(_installationId){\n AV._installationId = _installationId;\n if (!AV._installationId) {\n // It wasn't in localStorage, so create a new one.\n var hexOctet = function() {\n return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);\n };\n AV._installationId = (\n hexOctet() + hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + hexOctet() + hexOctet());\n return AV.localStorage.setItemAsync(path, AV._installationId);\n }\n else {\n return _installationId;\n }\n });\n};\n\nAV._parseDate = function(iso8601) {\n var regexp = new RegExp(\n \"^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})\" + \"T\" +\n \"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\" +\n \"(.([0-9]+))?\" + \"Z$\");\n var match = regexp.exec(iso8601);\n if (!match) {\n return null;\n }\n\n var year = match[1] || 0;\n var month = (match[2] || 1) - 1;\n var day = match[3] || 0;\n var hour = match[4] || 0;\n var minute = match[5] || 0;\n var second = match[6] || 0;\n var milli = match[8] || 0;\n\n return new Date(Date.UTC(year, month, day, hour, minute, second, milli));\n};\n\n// A self-propagating extend function.\nAV._extend = function(protoProps, classProps) {\n var child = inherits(this, protoProps, classProps);\n child.extend = this.extend;\n return child;\n};\n\n// Helper function to get a value from a Backbone object as a property\n// or as a function.\nAV._getValue = function(object, prop) {\n if (!(object && object[prop])) {\n return null;\n }\n return _.isFunction(object[prop]) ? object[prop]() : object[prop];\n};\n\n/**\n * Converts a value in a AV Object into the appropriate representation.\n * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object)\n * if seenObjects is falsey. Otherwise any AV.Objects not in\n * seenObjects will be fully embedded rather than encoded\n * as a pointer. This array will be used to prevent going into an infinite\n * loop because we have circular references. If \n * is set, then none of the AV Objects that are serialized can be dirty.\n * @private\n */\nAV._encode = function(value, seenObjects, disallowObjects) {\n if (value instanceof AV.Object) {\n if (disallowObjects) {\n throw new Error(\"AV.Objects not allowed here\");\n }\n if (!seenObjects || _.include(seenObjects, value) || !value._hasData) {\n return value._toPointer();\n }\n if (!value.dirty()) {\n seenObjects = seenObjects.concat(value);\n return AV._encode(value._toFullJSON(seenObjects),\n seenObjects,\n disallowObjects);\n }\n throw new Error(\"Tried to save an object with a pointer to a new, unsaved object.\");\n }\n if (value instanceof AV.ACL) {\n return value.toJSON();\n }\n if (_.isDate(value)) {\n return { \"__type\": \"Date\", \"iso\": value.toJSON() };\n }\n if (value instanceof AV.GeoPoint) {\n return value.toJSON();\n }\n if (_.isArray(value)) {\n return _.map(value, function(x) {\n return AV._encode(x, seenObjects, disallowObjects);\n });\n }\n if (_.isRegExp(value)) {\n return value.source;\n }\n if (value instanceof AV.Relation) {\n return value.toJSON();\n }\n if (value instanceof AV.Op) {\n return value.toJSON();\n }\n if (value instanceof AV.File) {\n if (!value.url() && !value.id) {\n throw new Error(\"Tried to save an object containing an unsaved file.\");\n }\n return value._toFullJSON();\n }\n if (_.isObject(value)) {\n return _.mapObject(value, (v, k) => AV._encode(v, seenObjects, disallowObjects));\n }\n return value;\n};\n\n/**\n * The inverse function of AV._encode.\n * @private\n */\nAV._decode = function(value, key) {\n if (!_.isObject(value) || _.isDate(value)) {\n return value;\n }\n if (_.isArray(value)) {\n return _.map(value, v => AV._decode(v));\n }\n if (value instanceof AV.Object) {\n return value;\n }\n if (value instanceof AV.File) {\n return value;\n }\n if (value instanceof AV.Op) {\n return value;\n }\n if (value instanceof AV.GeoPoint) {\n return value;\n }\n if (value instanceof AV.ACL) {\n return value;\n }\n if (key === 'ACL') {\n return new AV.ACL(value);\n }\n if (value.__op) {\n return AV.Op._decode(value);\n }\n var className;\n if (value.__type === \"Pointer\") {\n className = value.className;\n var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n if(Object.keys(value).length > 3) {\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n pointer._finishFetch(v, true);\n }else{\n pointer._finishFetch({ objectId: value.objectId }, false);\n }\n return pointer;\n }\n if (value.__type === \"Object\") {\n // It's an Object included in a query result.\n className = value.className;\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n object._finishFetch(v, true);\n return object;\n }\n if (value.__type === \"Date\") {\n return AV._parseDate(value.iso);\n }\n if (value.__type === \"GeoPoint\") {\n return new AV.GeoPoint({\n latitude: value.latitude,\n longitude: value.longitude\n });\n }\n if (value.__type === \"Relation\") {\n if (!key) throw new Error('key missing decoding a Relation');\n var relation = new AV.Relation(null, key);\n relation.targetClassName = value.className;\n return relation;\n }\n if (value.__type === 'File') {\n var file = new AV.File(value.name);\n const v = _.clone(value);\n delete v.__type;\n file._finishFetch(v);\n return file;\n }\n return _.mapObject(value, AV._decode);\n};\n\nAV._encodeObjectOrArray = function(value) {\n var encodeAVObject = function(object) {\n if (object && object._toFullJSON){\n object = object._toFullJSON([]);\n }\n\n return _.mapObject(object, function(value) {\n return AV._encode(value, []);\n });\n };\n\n if (_.isArray(value)) {\n return value.map(function(object) {\n return encodeAVObject(object);\n });\n } else {\n return encodeAVObject(value);\n }\n};\n\nAV._arrayEach = _.each;\n\n/**\n * Does a deep traversal of every item in object, calling func on every one.\n * @param {Object} object The object or array to traverse deeply.\n * @param {Function} func The function to call for every item. It will\n * be passed the item as an argument. If it returns a truthy value, that\n * value will replace the item in its parent container.\n * @returns {} the result of calling func on the top-level object itself.\n * @private\n */\nAV._traverse = function(object, func, seen) {\n if (object instanceof AV.Object) {\n seen = seen || [];\n if (_.indexOf(seen, object) >= 0) {\n // We've already visited this object in this call.\n return;\n }\n seen.push(object);\n AV._traverse(object.attributes, func, seen);\n return func(object);\n }\n if (object instanceof AV.Relation || object instanceof AV.File) {\n // Nothing needs to be done, but we don't want to recurse into the\n // object's parent infinitely, so we catch this case.\n return func(object);\n }\n if (_.isArray(object)) {\n _.each(object, function(child, index) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[index] = newChild;\n }\n });\n return func(object);\n }\n if (_.isObject(object)) {\n AV._each(object, function(child, key) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[key] = newChild;\n }\n });\n return func(object);\n }\n return func(object);\n};\n\n/**\n * This is like _.each, except:\n * * it doesn't work for so-called array-like objects,\n * * it does work for dictionaries with a \"length\" attribute.\n * @private\n */\nAV._objectEach = AV._each = function(obj, callback) {\n if (_.isObject(obj)) {\n _.each(_.keys(obj), function(key) {\n callback(obj[key], key);\n });\n } else {\n _.each(obj, callback);\n }\n};\n\nmodule.exports = AV;\n\n\n\n// WEBPACK FOOTER //\n// ./src/av.js","/**\n * Root reference for iframes.\n */\n\nvar root;\nif (typeof window !== 'undefined') { // Browser window\n root = window;\n} else if (typeof self !== 'undefined') { // Web Worker\n root = self;\n} else { // Other environments\n console.warn(\"Using browser-only version of superagent in non-browser environment\");\n root = this;\n}\n\nvar Emitter = require('component-emitter');\nvar RequestBase = require('./request-base');\nvar isObject = require('./is-object');\nvar isFunction = require('./is-function');\nvar ResponseBase = require('./response-base');\nvar shouldRetry = require('./should-retry');\n\n/**\n * Noop.\n */\n\nfunction noop(){};\n\n/**\n * Expose `request`.\n */\n\nvar request = exports = module.exports = function(method, url) {\n // callback\n if ('function' == typeof url) {\n return new exports.Request('GET', method).end(url);\n }\n\n // url first\n if (1 == arguments.length) {\n return new exports.Request('GET', method);\n }\n\n return new exports.Request(method, url);\n}\n\nexports.Request = Request;\n\n/**\n * Determine XHR.\n */\n\nrequest.getXHR = function () {\n if (root.XMLHttpRequest\n && (!root.location || 'file:' != root.location.protocol\n || !root.ActiveXObject)) {\n return new XMLHttpRequest;\n } else {\n try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}\n }\n throw Error(\"Browser-only verison of superagent could not find XHR\");\n};\n\n/**\n * Removes leading and trailing whitespace, added to support IE.\n *\n * @param {String} s\n * @return {String}\n * @api private\n */\n\nvar trim = ''.trim\n ? function(s) { return s.trim(); }\n : function(s) { return s.replace(/(^\\s*|\\s*$)/g, ''); };\n\n/**\n * Serialize the given `obj`.\n *\n * @param {Object} obj\n * @return {String}\n * @api private\n */\n\nfunction serialize(obj) {\n if (!isObject(obj)) return obj;\n var pairs = [];\n for (var key in obj) {\n pushEncodedKeyValuePair(pairs, key, obj[key]);\n }\n return pairs.join('&');\n}\n\n/**\n * Helps 'serialize' with serializing arrays.\n * Mutates the pairs array.\n *\n * @param {Array} pairs\n * @param {String} key\n * @param {Mixed} val\n */\n\nfunction pushEncodedKeyValuePair(pairs, key, val) {\n if (val != null) {\n if (Array.isArray(val)) {\n val.forEach(function(v) {\n pushEncodedKeyValuePair(pairs, key, v);\n });\n } else if (isObject(val)) {\n for(var subkey in val) {\n pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);\n }\n } else {\n pairs.push(encodeURIComponent(key)\n + '=' + encodeURIComponent(val));\n }\n } else if (val === null) {\n pairs.push(encodeURIComponent(key));\n }\n}\n\n/**\n * Expose serialization method.\n */\n\n request.serializeObject = serialize;\n\n /**\n * Parse the given x-www-form-urlencoded `str`.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseString(str) {\n var obj = {};\n var pairs = str.split('&');\n var pair;\n var pos;\n\n for (var i = 0, len = pairs.length; i < len; ++i) {\n pair = pairs[i];\n pos = pair.indexOf('=');\n if (pos == -1) {\n obj[decodeURIComponent(pair)] = '';\n } else {\n obj[decodeURIComponent(pair.slice(0, pos))] =\n decodeURIComponent(pair.slice(pos + 1));\n }\n }\n\n return obj;\n}\n\n/**\n * Expose parser.\n */\n\nrequest.parseString = parseString;\n\n/**\n * Default MIME type map.\n *\n * superagent.types.xml = 'application/xml';\n *\n */\n\nrequest.types = {\n html: 'text/html',\n json: 'application/json',\n xml: 'application/xml',\n urlencoded: 'application/x-www-form-urlencoded',\n 'form': 'application/x-www-form-urlencoded',\n 'form-data': 'application/x-www-form-urlencoded'\n};\n\n/**\n * Default serialization map.\n *\n * superagent.serialize['application/xml'] = function(obj){\n * return 'generated xml here';\n * };\n *\n */\n\n request.serialize = {\n 'application/x-www-form-urlencoded': serialize,\n 'application/json': JSON.stringify\n };\n\n /**\n * Default parsers.\n *\n * superagent.parse['application/xml'] = function(str){\n * return { object parsed from str };\n * };\n *\n */\n\nrequest.parse = {\n 'application/x-www-form-urlencoded': parseString,\n 'application/json': JSON.parse\n};\n\n/**\n * Parse the given header `str` into\n * an object containing the mapped fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseHeader(str) {\n var lines = str.split(/\\r?\\n/);\n var fields = {};\n var index;\n var line;\n var field;\n var val;\n\n lines.pop(); // trailing CRLF\n\n for (var i = 0, len = lines.length; i < len; ++i) {\n line = lines[i];\n index = line.indexOf(':');\n field = line.slice(0, index).toLowerCase();\n val = trim(line.slice(index + 1));\n fields[field] = val;\n }\n\n return fields;\n}\n\n/**\n * Check if `mime` is json or has +json structured syntax suffix.\n *\n * @param {String} mime\n * @return {Boolean}\n * @api private\n */\n\nfunction isJSON(mime) {\n return /[\\/+]json\\b/.test(mime);\n}\n\n/**\n * Initialize a new `Response` with the given `xhr`.\n *\n * - set flags (.ok, .error, etc)\n * - parse header\n *\n * Examples:\n *\n * Aliasing `superagent` as `request` is nice:\n *\n * request = superagent;\n *\n * We can use the promise-like API, or pass callbacks:\n *\n * request.get('/').end(function(res){});\n * request.get('/', function(res){});\n *\n * Sending data can be chained:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' })\n * .end(function(res){});\n *\n * Or passed to `.send()`:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' }, function(res){});\n *\n * Or passed to `.post()`:\n *\n * request\n * .post('/user', { name: 'tj' })\n * .end(function(res){});\n *\n * Or further reduced to a single call for simple cases:\n *\n * request\n * .post('/user', { name: 'tj' }, function(res){});\n *\n * @param {XMLHTTPRequest} xhr\n * @param {Object} options\n * @api private\n */\n\nfunction Response(req) {\n this.req = req;\n this.xhr = this.req.xhr;\n // responseText is accessible only if responseType is '' or 'text' and on older browsers\n this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')\n ? this.xhr.responseText\n : null;\n this.statusText = this.req.xhr.statusText;\n var status = this.xhr.status;\n // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request\n if (status === 1223) {\n status = 204;\n }\n this._setStatusProperties(status);\n this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());\n // getAllResponseHeaders sometimes falsely returns \"\" for CORS requests, but\n // getResponseHeader still works. so we get content-type even if getting\n // other headers fails.\n this.header['content-type'] = this.xhr.getResponseHeader('content-type');\n this._setHeaderProperties(this.header);\n\n if (null === this.text && req._responseType) {\n this.body = this.xhr.response;\n } else {\n this.body = this.req.method != 'HEAD'\n ? this._parseBody(this.text ? this.text : this.xhr.response)\n : null;\n }\n}\n\nResponseBase(Response.prototype);\n\n/**\n * Parse the given body `str`.\n *\n * Used for auto-parsing of bodies. Parsers\n * are defined on the `superagent.parse` object.\n *\n * @param {String} str\n * @return {Mixed}\n * @api private\n */\n\nResponse.prototype._parseBody = function(str){\n var parse = request.parse[this.type];\n if(this.req._parser) {\n return this.req._parser(this, str);\n }\n if (!parse && isJSON(this.type)) {\n parse = request.parse['application/json'];\n }\n return parse && str && (str.length || str instanceof Object)\n ? parse(str)\n : null;\n};\n\n/**\n * Return an `Error` representative of this response.\n *\n * @return {Error}\n * @api public\n */\n\nResponse.prototype.toError = function(){\n var req = this.req;\n var method = req.method;\n var url = req.url;\n\n var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';\n var err = new Error(msg);\n err.status = this.status;\n err.method = method;\n err.url = url;\n\n return err;\n};\n\n/**\n * Expose `Response`.\n */\n\nrequest.Response = Response;\n\n/**\n * Initialize a new `Request` with the given `method` and `url`.\n *\n * @param {String} method\n * @param {String} url\n * @api public\n */\n\nfunction Request(method, url) {\n var self = this;\n this._query = this._query || [];\n this.method = method;\n this.url = url;\n this.header = {}; // preserves header name case\n this._header = {}; // coerces header names to lowercase\n this.on('end', function(){\n var err = null;\n var res = null;\n\n try {\n res = new Response(self);\n } catch(e) {\n err = new Error('Parser is unable to parse the response');\n err.parse = true;\n err.original = e;\n // issue #675: return the raw response if the response parsing fails\n if (self.xhr) {\n // ie9 doesn't have 'response' property\n err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;\n // issue #876: return the http status code if the response parsing fails\n err.status = self.xhr.status ? self.xhr.status : null;\n err.statusCode = err.status; // backwards-compat only\n } else {\n err.rawResponse = null;\n err.status = null;\n }\n\n return self.callback(err);\n }\n\n self.emit('response', res);\n\n var new_err;\n try {\n if (!self._isResponseOK(res)) {\n new_err = new Error(res.statusText || 'Unsuccessful HTTP response');\n new_err.original = err;\n new_err.response = res;\n new_err.status = res.status;\n }\n } catch(e) {\n new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android\n }\n\n // #1000 don't catch errors from the callback to avoid double calling it\n if (new_err) {\n self.callback(new_err, res);\n } else {\n self.callback(null, res);\n }\n });\n}\n\n/**\n * Mixin `Emitter` and `RequestBase`.\n */\n\nEmitter(Request.prototype);\nRequestBase(Request.prototype);\n\n/**\n * Set Content-Type to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.xml = 'application/xml';\n *\n * request.post('/')\n * .type('xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * request.post('/')\n * .type('application/xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * @param {String} type\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.type = function(type){\n this.set('Content-Type', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Accept to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.json = 'application/json';\n *\n * request.get('/agent')\n * .accept('json')\n * .end(callback);\n *\n * request.get('/agent')\n * .accept('application/json')\n * .end(callback);\n *\n * @param {String} accept\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.accept = function(type){\n this.set('Accept', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Authorization field value with `user` and `pass`.\n *\n * @param {String} user\n * @param {String} [pass] optional in case of using 'bearer' as type\n * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.auth = function(user, pass, options){\n if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options\n options = pass;\n }\n if (!options) {\n options = {\n type: 'function' === typeof btoa ? 'basic' : 'auto',\n }\n }\n\n switch (options.type) {\n case 'basic':\n this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));\n break;\n\n case 'auto':\n this.username = user;\n this.password = pass;\n break;\n \n case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })\n this.set('Authorization', 'Bearer ' + user);\n break; \n }\n return this;\n};\n\n/**\n * Add query-string `val`.\n *\n * Examples:\n *\n * request.get('/shoes')\n * .query('size=10')\n * .query({ color: 'blue' })\n *\n * @param {Object|String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.query = function(val){\n if ('string' != typeof val) val = serialize(val);\n if (val) this._query.push(val);\n return this;\n};\n\n/**\n * Queue the given `file` as an attachment to the specified `field`,\n * with optional `options` (or filename).\n *\n * ``` js\n * request.post('/upload')\n * .attach('content', new Blob(['hey!'], { type: \"text/html\"}))\n * .end(callback);\n * ```\n *\n * @param {String} field\n * @param {Blob|File} file\n * @param {String|Object} options\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.attach = function(field, file, options){\n if (file) {\n if (this._data) {\n throw Error(\"superagent can't mix .send() and .attach()\");\n }\n\n this._getFormData().append(field, file, options || file.name);\n }\n return this;\n};\n\nRequest.prototype._getFormData = function(){\n if (!this._formData) {\n this._formData = new root.FormData();\n }\n return this._formData;\n};\n\n/**\n * Invoke the callback with `err` and `res`\n * and handle arity check.\n *\n * @param {Error} err\n * @param {Response} res\n * @api private\n */\n\nRequest.prototype.callback = function(err, res){\n // console.log(this._retries, this._maxRetries)\n if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) {\n return this._retry();\n }\n\n var fn = this._callback;\n this.clearTimeout();\n\n if (err) {\n if (this._maxRetries) err.retries = this._retries - 1;\n this.emit('error', err);\n }\n\n fn(err, res);\n};\n\n/**\n * Invoke callback with x-domain error.\n *\n * @api private\n */\n\nRequest.prototype.crossDomainError = function(){\n var err = new Error('Request has been terminated\\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');\n err.crossDomain = true;\n\n err.status = this.status;\n err.method = this.method;\n err.url = this.url;\n\n this.callback(err);\n};\n\n// This only warns, because the request is still likely to work\nRequest.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){\n console.warn(\"This is not supported in browser version of superagent\");\n return this;\n};\n\n// This throws, because it can't send/receive data as expected\nRequest.prototype.pipe = Request.prototype.write = function(){\n throw Error(\"Streaming is not supported in browser version of superagent\");\n};\n\n/**\n * Compose querystring to append to req.url\n *\n * @api private\n */\n\nRequest.prototype._appendQueryString = function(){\n var query = this._query.join('&');\n if (query) {\n this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;\n }\n\n if (this._sort) {\n var index = this.url.indexOf('?');\n if (index >= 0) {\n var queryArr = this.url.substring(index + 1).split('&');\n if (isFunction(this._sort)) {\n queryArr.sort(this._sort);\n } else {\n queryArr.sort();\n }\n this.url = this.url.substring(0, index) + '?' + queryArr.join('&');\n }\n }\n};\n\n/**\n * Check if `obj` is a host object,\n * we don't want to serialize these :)\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\nRequest.prototype._isHost = function _isHost(obj) {\n // Native objects stringify to [object File], [object Blob], [object FormData], etc.\n return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';\n}\n\n/**\n * Initiate request, invoking callback `fn(res)`\n * with an instanceof `Response`.\n *\n * @param {Function} fn\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.end = function(fn){\n if (this._endCalled) {\n console.warn(\"Warning: .end() was called twice. This is not supported in superagent\");\n }\n this._endCalled = true;\n\n // store callback\n this._callback = fn || noop;\n\n // querystring\n this._appendQueryString();\n\n return this._end();\n};\n\nRequest.prototype._end = function() {\n var self = this;\n var xhr = this.xhr = request.getXHR();\n var data = this._formData || this._data;\n\n this._setTimeouts();\n\n // state change\n xhr.onreadystatechange = function(){\n var readyState = xhr.readyState;\n if (readyState >= 2 && self._responseTimeoutTimer) {\n clearTimeout(self._responseTimeoutTimer);\n }\n if (4 != readyState) {\n return;\n }\n\n // In IE9, reads to any property (e.g. status) off of an aborted XHR will\n // result in the error \"Could not complete the operation due to error c00c023f\"\n var status;\n try { status = xhr.status } catch(e) { status = 0; }\n\n if (!status) {\n if (self.timedout || self._aborted) return;\n return self.crossDomainError();\n }\n self.emit('end');\n };\n\n // progress\n var handleProgress = function(direction, e) {\n if (e.total > 0) {\n e.percent = e.loaded / e.total * 100;\n }\n e.direction = direction;\n self.emit('progress', e);\n }\n if (this.hasListeners('progress')) {\n try {\n xhr.onprogress = handleProgress.bind(null, 'download');\n if (xhr.upload) {\n xhr.upload.onprogress = handleProgress.bind(null, 'upload');\n }\n } catch(e) {\n // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.\n // Reported here:\n // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context\n }\n }\n\n // initiate request\n try {\n if (this.username && this.password) {\n xhr.open(this.method, this.url, true, this.username, this.password);\n } else {\n xhr.open(this.method, this.url, true);\n }\n } catch (err) {\n // see #1149\n return this.callback(err);\n }\n\n // CORS\n if (this._withCredentials) xhr.withCredentials = true;\n\n // body\n if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {\n // serialize stuff\n var contentType = this._header['content-type'];\n var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];\n if (!serialize && isJSON(contentType)) {\n serialize = request.serialize['application/json'];\n }\n if (serialize) data = serialize(data);\n }\n\n // set header fields\n for (var field in this.header) {\n if (null == this.header[field]) continue;\n\n if (this.header.hasOwnProperty(field))\n xhr.setRequestHeader(field, this.header[field]);\n }\n\n if (this._responseType) {\n xhr.responseType = this._responseType;\n }\n\n // send stuff\n this.emit('request', this);\n\n // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)\n // We need null here if data is undefined\n xhr.send(typeof data !== 'undefined' ? data : null);\n return this;\n};\n\n/**\n * GET `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.get = function(url, data, fn){\n var req = request('GET', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.query(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * HEAD `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.head = function(url, data, fn){\n var req = request('HEAD', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * OPTIONS query to `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.options = function(url, data, fn){\n var req = request('OPTIONS', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * DELETE `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nfunction del(url, data, fn){\n var req = request('DELETE', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\nrequest['del'] = del;\nrequest['delete'] = del;\n\n/**\n * PATCH `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.patch = function(url, data, fn){\n var req = request('PATCH', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * POST `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.post = function(url, data, fn){\n var req = request('POST', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * PUT `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.put = function(url, data, fn){\n var req = request('PUT', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/client.js\n// module id = 7\n// module chunks = 0","/**\n * Check if `obj` is an object.\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\n\nfunction isObject(obj) {\n return null !== obj && 'object' === typeof obj;\n}\n\nmodule.exports = isObject;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-object.js\n// module id = 8\n// module chunks = 0","const storage = require('./localstorage');\nconst AV = require('./av');\n\nconst removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage);\n\nconst getCacheData = (cacheData, key) => {\n try {\n cacheData = JSON.parse(cacheData);\n } catch (e) {\n return null;\n }\n if (cacheData) {\n const expired = cacheData.expiredAt && cacheData.expiredAt < Date.now();\n if (!expired) {\n return cacheData.value;\n }\n return removeAsync(key).then(() => null);\n }\n return null;\n};\n\nexports.getAsync = (key) => {\n key = `${AV.applicationId}/${key}`;\n return storage.getItemAsync(key)\n .then(cache => getCacheData(cache, key));\n};\n\nexports.setAsync = (key, value, ttl) => {\n const cache = { value };\n if (typeof ttl === 'number') {\n cache.expiredAt = Date.now() + ttl;\n }\n return storage.setItemAsync(\n `${AV.applicationId}/${key}`,\n JSON.stringify(cache)\n );\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cache.js","var _ = require('underscore');\nvar Promise = require('./promise');\nvar localStorage = require('./utils/localstorage');\n\nvar syncApiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nif (!localStorage.async) {\n // wrap sync apis with async ones.\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] === 'function') {\n localStorage[apiName + 'Async'] = function() {\n return Promise.resolve(localStorage[apiName].apply(localStorage, arguments));\n };\n }\n });\n} else {\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] !== 'function') {\n localStorage[apiName] = function() {\n const error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.');\n error.code = 'SYNC_API_NOT_AVAILABLE';\n throw error;\n };\n }\n });\n}\n\nmodule.exports = localStorage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/localstorage.js","module.exports = '2.1.4';\n\n\n\n// WEBPACK FOOTER //\n// ./src/version.js","var charenc = {\n // UTF-8 encoding\n utf8: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n }\n },\n\n // Binary encoding\n bin: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n for (var bytes = [], i = 0; i < str.length; i++)\n bytes.push(str.charCodeAt(i) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n for (var str = [], i = 0; i < bytes.length; i++)\n str.push(String.fromCharCode(bytes[i]));\n return str.join('');\n }\n }\n};\n\nmodule.exports = charenc;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/charenc/charenc.js\n// module id = 12\n// module chunks = 0","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/global.js\n// module id = 13\n// module chunks = 0","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var PUBLIC_KEY = \"*\";\n\n /**\n * Creates a new ACL.\n * If no argument is given, the ACL has no permissions for anyone.\n * If the argument is a AV.User, the ACL will have read and write\n * permission for only that user.\n * If the argument is any other JSON object, that object will be interpretted\n * as a serialized ACL created with toJSON().\n * @see AV.Object#setACL\n * @class\n *\n *

An ACL, or Access Control List can be added to any\n * AV.Object to restrict access to only a subset of users\n * of your application.

\n */\n AV.ACL = function(arg1) {\n var self = this;\n self.permissionsById = {};\n if (_.isObject(arg1)) {\n if (arg1 instanceof AV.User) {\n self.setReadAccess(arg1, true);\n self.setWriteAccess(arg1, true);\n } else {\n if (_.isFunction(arg1)) {\n throw new Error('AV.ACL() called with a function. Did you forget ()?');\n }\n AV._objectEach(arg1, function(accessList, userId) {\n if (!_.isString(userId)) {\n throw new Error('Tried to create an ACL with an invalid userId.');\n }\n self.permissionsById[userId] = {};\n AV._objectEach(accessList, function(allowed, permission) {\n if (permission !== \"read\" && permission !== \"write\") {\n throw new Error('Tried to create an ACL with an invalid permission type.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('Tried to create an ACL with an invalid permission value.');\n }\n self.permissionsById[userId][permission] = allowed;\n });\n });\n }\n }\n };\n\n /**\n * Returns a JSON-encoded version of the ACL.\n * @return {Object}\n */\n AV.ACL.prototype.toJSON = function() {\n return _.clone(this.permissionsById);\n };\n\n AV.ACL.prototype._setAccess = function(accessType, userId, allowed) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n if (!_.isString(userId)) {\n throw new Error('userId must be a string.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('allowed must be either true or false.');\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n if (!allowed) {\n // The user already doesn't have this permission, so no action needed.\n return;\n } else {\n permissions = {};\n this.permissionsById[userId] = permissions;\n }\n }\n\n if (allowed) {\n this.permissionsById[userId][accessType] = true;\n } else {\n delete permissions[accessType];\n if (_.isEmpty(permissions)) {\n delete this.permissionsById[userId];\n }\n }\n };\n\n AV.ACL.prototype._getAccess = function(accessType, userId) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n return false;\n }\n return permissions[accessType] ? true : false;\n };\n\n /**\n * Set whether the given user is allowed to read this object.\n * @param userId An instance of AV.User or its objectId.\n * @param {Boolean} allowed Whether that user should have read access.\n */\n AV.ACL.prototype.setReadAccess = function(userId, allowed) {\n this._setAccess(\"read\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to read this object.\n * Even if this returns false, the user may still be able to access it if\n * getPublicReadAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getReadAccess = function(userId) {\n return this._getAccess(\"read\", userId);\n };\n\n /**\n * Set whether the given user id is allowed to write this object.\n * @param userId An instance of AV.User or its objectId, or a AV.Role..\n * @param {Boolean} allowed Whether that user should have write access.\n */\n AV.ACL.prototype.setWriteAccess = function(userId, allowed) {\n this._setAccess(\"write\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to write this object.\n * Even if this returns false, the user may still be able to write it if\n * getPublicWriteAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getWriteAccess = function(userId) {\n return this._getAccess(\"write\", userId);\n };\n\n /**\n * Set whether the public is allowed to read this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicReadAccess = function(allowed) {\n this.setReadAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to read this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicReadAccess = function() {\n return this.getReadAccess(PUBLIC_KEY);\n };\n\n /**\n * Set whether the public is allowed to write this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicWriteAccess = function(allowed) {\n this.setWriteAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to write this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicWriteAccess = function() {\n return this.getWriteAccess(PUBLIC_KEY);\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to read this object. Even if this returns false, the role may\n * still be able to write it if a parent role has read access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has read access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleReadAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getReadAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to write this object. Even if this returns false, the role may\n * still be able to write it if a parent role has write access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has write access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleWriteAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getWriteAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to read this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can read this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleReadAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setReadAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to write this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can write this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleWriteAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setWriteAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/acl.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * Contains functions for calling and declaring\n *

\n * Some functions are only available from Cloud Code.\n *

\n *\n * @namespace\n */\n AV.Cloud = AV.Cloud || {};\n\n _.extend(AV.Cloud, /** @lends AV.Cloud */ {\n /**\n * Makes a call to a cloud function.\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n run: function(name, data, options) {\n var request = AVRequest('functions', name, null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response\n * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object}\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result of the function.\n */\n rpc: function(name, data, options) {\n if (_.isArray(data)) {\n return Promise.reject(new Error('Can\\'t pass Array as the param of rpc function in JavaScript SDK.'));\n }\n\n return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Make a call to request server date time.\n * @return {Promise.} A promise that will be resolved with the result\n * of the function.\n * @since 0.5.9\n */\n getServerDate: function() {\n var request = AVRequest(\"date\", null, null, 'GET');\n\n return request.then(function(resp) {\n return AV._decode(resp);\n });\n },\n\n /**\n * Makes a call to request a sms code for operation verification.\n * @param {Object} data The mobile phone number string or a JSON\n * object that contains mobilePhoneNumber,template,op,ttl,name etc.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n requestSmsCode: function(data){\n if(_.isString(data)) {\n data = { mobilePhoneNumber: data };\n }\n if(!data.mobilePhoneNumber) {\n throw new Error('Missing mobilePhoneNumber.');\n }\n var request = AVRequest(\"requestSmsCode\", null, null, 'POST',\n data);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode\n * @param {String} code The sms code sent by AV.Cloud.requestSmsCode\n * @param {phone} phone The mobile phoner number(optional).\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifySmsCode: function(code, phone){\n if(!code)\n throw new Error('Missing sms code.');\n var params = {};\n if(_.isString(phone)) {\n params['mobilePhoneNumber'] = phone;\n }\n\n var request = AVRequest(\"verifySmsCode\", code, null, 'POST',\n params);\n return request;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cloudfunction.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var eventSplitter = /\\s+/;\n var slice = Array.prototype.slice;\n\n /**\n * @class\n *\n *

AV.Events is a fork of Backbone's Events module, provided for your\n * convenience.

\n *\n *

A module that can be mixed in to any object in order to provide\n * it with custom events. You may bind callback functions to an event\n * with `on`, or remove these functions with `off`.\n * Triggering an event fires all callbacks in the order that `on` was\n * called.\n *\n * @private\n * @example\n * var object = {};\n * _.extend(object, AV.Events);\n * object.on('expand', function(){ alert('expanded'); });\n * object.trigger('expand');

\n *\n */\n AV.Events = {\n /**\n * Bind one or more space separated events, `events`, to a `callback`\n * function. Passing `\"all\"` will bind the callback to all events fired.\n */\n on: function(events, callback, context) {\n\n var calls, event, node, tail, list;\n if (!callback) {\n return this;\n }\n events = events.split(eventSplitter);\n calls = this._callbacks || (this._callbacks = {});\n\n // Create an immutable callback list, allowing traversal during\n // modification. The tail is an empty object that will always be used\n // as the next node.\n event = events.shift();\n while (event) {\n list = calls[event];\n node = list ? list.tail : {};\n node.next = tail = {};\n node.context = context;\n node.callback = callback;\n calls[event] = {tail: tail, next: list ? list.next : node};\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Remove one or many callbacks. If `context` is null, removes all callbacks\n * with that function. If `callback` is null, removes all callbacks for the\n * event. If `events` is null, removes all bound callbacks for all events.\n */\n off: function(events, callback, context) {\n var event, calls, node, tail, cb, ctx;\n\n // No events, or removing *all* events.\n if (!(calls = this._callbacks)) {\n return;\n }\n if (!(events || callback || context)) {\n delete this._callbacks;\n return this;\n }\n\n // Loop through the listed events and contexts, splicing them out of the\n // linked list of callbacks if appropriate.\n events = events ? events.split(eventSplitter) : _.keys(calls);\n event = events.shift();\n while (event) {\n node = calls[event];\n delete calls[event];\n if (!node || !(callback || context)) {\n continue;\n }\n // Create a new list, omitting the indicated callbacks.\n tail = node.tail;\n node = node.next;\n while (node !== tail) {\n cb = node.callback;\n ctx = node.context;\n if ((callback && cb !== callback) || (context && ctx !== context)) {\n this.on(event, cb, ctx);\n }\n node = node.next;\n }\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Trigger one or many events, firing all bound callbacks. Callbacks are\n * passed the same arguments as `trigger` is, apart from the event name\n * (unless you're listening on `\"all\"`, which will cause your callback to\n * receive the true name of the event as the first argument).\n */\n trigger: function(events) {\n var event, node, calls, tail, args, all, rest;\n if (!(calls = this._callbacks)) {\n return this;\n }\n all = calls.all;\n events = events.split(eventSplitter);\n rest = slice.call(arguments, 1);\n\n // For each event, walk through the linked list of callbacks twice,\n // first to trigger the event, then to trigger any `\"all\"` callbacks.\n event = events.shift();\n while (event) {\n node = calls[event];\n if (node) {\n tail = node.tail;\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, rest);\n }\n }\n node = all;\n if (node) {\n tail = node.tail;\n args = [event].concat(rest);\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, args);\n }\n }\n event = events.shift();\n }\n\n return this;\n }\n };\n\n /**\n * @function\n */\n AV.Events.bind = AV.Events.on;\n\n /**\n * @function\n */\n AV.Events.unbind = AV.Events.off;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/event.js","const _ = require('underscore');\nconst cos = require('./uploader/cos');\nconst qiniu = require('./uploader/qiniu');\nconst s3 = require('./uploader/s3');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\nconst { tap } = require('./utils');\nconst debug = require('debug')('leancloud:file');\nconst parseBase64 = require('./utils/parse-base64');\n\nmodule.exports = function(AV) {\n\n // 挂载一些配置\n let avConfig = AV._config;\n\n const hexOctet = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);\n\n // port from browserify path module\n // since react-native packager won't shim node modules.\n const extname = (path) => {\n return path.match(/^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/)[4];\n };\n\n const b64Digit = (number) => {\n if (number < 26) {\n return String.fromCharCode(65 + number);\n }\n if (number < 52) {\n return String.fromCharCode(97 + (number - 26));\n }\n if (number < 62) {\n return String.fromCharCode(48 + (number - 52));\n }\n if (number === 62) {\n return '+';\n }\n if (number === 63) {\n return '/';\n }\n throw new Error('Tried to encode large digit ' + number + ' in base64.');\n };\n\n var encodeBase64 = function(array) {\n var chunks = [];\n chunks.length = Math.ceil(array.length / 3);\n _.times(chunks.length, function(i) {\n var b1 = array[i * 3];\n var b2 = array[i * 3 + 1] || 0;\n var b3 = array[i * 3 + 2] || 0;\n\n var has2 = (i * 3 + 1) < array.length;\n var has3 = (i * 3 + 2) < array.length;\n\n chunks[i] = [\n b64Digit((b1 >> 2) & 0x3F),\n b64Digit(((b1 << 4) & 0x30) | ((b2 >> 4) & 0x0F)),\n has2 ? b64Digit(((b2 << 2) & 0x3C) | ((b3 >> 6) & 0x03)) : \"=\",\n has3 ? b64Digit(b3 & 0x3F) : \"=\"\n ].join(\"\");\n });\n return chunks.join(\"\");\n };\n\n /**\n * An AV.File is a local representation of a file that is saved to the AV\n * cloud.\n * @param name {String} The file's name. This will change to a unique value\n * once the file has finished saving.\n * @param data {Array} The data for the file, as either:\n * 1. an Array of byte value Numbers, or\n * 2. an Object like { base64: \"...\" } with a base64-encoded String.\n * 3. a File object selected with a file upload control. (3) only works\n * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.\n * 4.a Buffer object in Node.js runtime.\n *\n * For example:
\n   * var fileUploadControl = $(\"#profilePhotoFileUpload\")[0];\n   * if (fileUploadControl.files.length > 0) {\n   *   var file = fileUploadControl.files[0];\n   *   var name = \"photo.jpg\";\n   *   var file = new AV.File(name, file);\n   *   file.save().then(function() {\n   *     // The file has been saved to AV.\n   *   }, function(error) {\n   *     // The file either could not be read, or could not be saved to AV.\n   *   });\n   * }
\n *\n * @class\n * @param [mimeType] {String} Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n */\n AV.File = function(name, data, mimeType) {\n\n this.attributes = {\n name,\n url: '',\n metaData: {},\n // 用来存储转换后要上传的 base64 String\n base64: '',\n };\n\n if (_.isString(data)) {\n throw new TypeError(\"Creating an AV.File from a String is not yet supported.\");\n }\n if (_.isArray(data)) {\n this.attributes.metaData.size = data.length;\n data = { base64: encodeBase64(data) };\n }\n\n this._extName = '';\n this._data = data;\n\n let owner;\n if (data && data.owner) {\n owner = data.owner;\n } else if (!AV._config.disableCurrentUser) {\n try {\n owner = AV.User.current();\n } catch (error) {\n if ('SYNC_API_NOT_AVAILABLE' === error.code) {\n console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().');\n } else {\n throw error;\n }\n }\n }\n \n this.attributes.metaData.owner = owner ? owner.id : 'unknown';\n\n this.set('mime_type', mimeType);\n };\n\n /**\n * Creates a fresh AV.File object with exists url for saving to AVOS Cloud.\n * @param {String} name the file name\n * @param {String} url the file url.\n * @param {Object} [metaData] the file metadata object.\n * @param {String} [type] Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n * @return {AV.File} the file object\n */\n AV.File.withURL = function(name, url, metaData, type) {\n if (!name || !url){\n throw new Error(\"Please provide file name and url\");\n }\n var file = new AV.File(name, null, type);\n //copy metaData properties to file.\n if (metaData){\n for(var prop in metaData){\n if (!file.attributes.metaData[prop])\n file.attributes.metaData[prop] = metaData[prop];\n }\n }\n file.attributes.url = url;\n //Mark the file is from external source.\n file.attributes.metaData.__source = 'external';\n return file;\n };\n\n /**\n * Creates a file object with exists objectId.\n * @param {String} objectId The objectId string\n * @return {AV.File} the file object\n */\n AV.File.createWithoutData = function(objectId) {\n var file = new AV.File();\n file.id = objectId;\n return file;\n };\n\n AV.File.prototype = {\n className: '_File',\n\n _toFullJSON(seenObjects) {\n var json = _.clone(this.attributes);\n AV._objectEach(json, function(val, key) {\n json[key] = AV._encode(val, seenObjects);\n });\n AV._objectEach(this._operations, function(val, key) {\n json[key] = val;\n });\n\n if (_.has(this, \"id\")) {\n json.objectId = this.id;\n }\n _(['createdAt', 'updatedAt']).each((key) => {\n if (_.has(this, key)) {\n const val = this[key];\n json[key] = _.isDate(val) ? val.toJSON() : val;\n }\n });\n json.__type = \"File\";\n return json;\n },\n\n toJSON() {\n const json = this._toFullJSON();\n // add id and keep __type for backward compatible\n if (_.has(this, 'id')) {\n json.id = this.id;\n }\n return json;\n },\n\n /**\n * Returns the ACL for this file.\n * @returns {AV.ACL} An instance of AV.ACL.\n */\n getACL: function() {\n return this._acl;\n },\n\n /**\n * Sets the ACL to be used for this file.\n * @param {AV.ACL} acl An instance of AV.ACL.\n */\n setACL: function(acl) {\n if (!(acl instanceof AV.ACL)) {\n return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.');\n }\n this._acl = acl;\n },\n\n /**\n * Gets the name of the file. Before save is called, this is the filename\n * given by the user. After save is called, that name gets prefixed with a\n * unique identifier.\n */\n name: function() {\n return this.get('name');\n },\n\n /**\n * Gets the url of the file. It is only available after you save the file or\n * after you get the file from a AV.Object.\n * @return {String}\n */\n url: function() {\n return this.get('url');\n },\n\n /**\n * Gets the attributs of the file object.\n * @param {String} The attribute name which want to get.\n * @returns {Any}\n */\n get: function(attrName) {\n switch (attrName) {\n case 'objectId':\n return this.id;\n case 'url':\n case 'name':\n case 'mime_type':\n case 'metaData':\n case 'createdAt':\n case 'updatedAt':\n return this.attributes[attrName];\n default:\n return this.attributes.metaData[attrName];\n }\n },\n\n /**\n * Set the metaData of the file object.\n * @param {Object} Object is an key value Object for setting metaData.\n * @param {String} attr is an optional metadata key.\n * @param {Object} value is an optional metadata value.\n * @returns {String|Number|Array|Object}\n */\n set: function(...args) {\n const set = (attrName, value) => {\n switch (attrName) {\n case 'name':\n case 'url':\n case 'mime_type':\n case 'base64':\n case 'metaData':\n this.attributes[attrName] = value;\n break;\n default:\n // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面\n this.attributes.metaData[attrName] = value;\n break;\n }\n };\n\n switch (args.length) {\n case 1:\n // 传入一个 Object\n for (var k in args[0]) {\n set(k, args[0][k]);\n }\n break;\n case 2:\n set(args[0], args[1]);\n break;\n }\n },\n\n /**\n *

Returns the file's metadata JSON object if no arguments is given.Returns the\n * metadata value if a key is given.Set metadata value if key and value are both given.

\n *

\n    *  var metadata = file.metaData(); //Get metadata JSON object.\n    *  var size = file.metaData('size');  // Get the size metadata value.\n    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.\n    *

\n * @return {Object} The file's metadata JSON object.\n * @param {String} attr an optional metadata key.\n * @param {Object} value an optional metadata value.\n **/\n metaData: function(attr, value) {\n if (attr && value) {\n this.attributes.metaData[attr] = value;\n return this;\n } else if (attr && !value) {\n return this.attributes.metaData[attr];\n } else {\n return this.attributes.metaData;\n }\n },\n\n /**\n * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。\n * @return {String} 缩略图URL\n * @param {Number} width 宽度,单位:像素\n * @param {Number} heigth 高度,单位:像素\n * @param {Number} quality 质量,1-100的数字,默认100\n * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。\n * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。\n */\n\n thumbnailURL: function(width, height, quality, scaleToFit, fmt) {\n const url = this.attributes.url;\n if (!url) {\n throw new Error('Invalid url.');\n }\n if (!width || !height || width <= 0 || height <= 0 ) {\n throw new Error('Invalid width or height value.');\n }\n quality = quality || 100;\n scaleToFit = !scaleToFit ? true : scaleToFit;\n if (quality <= 0 || quality > 100) {\n throw new Error('Invalid quality value.');\n }\n fmt = fmt || 'png';\n const mode = scaleToFit ? 2: 1;\n return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt;\n },\n\n /**\n * Returns the file's size.\n * @return {Number} The file's size in bytes.\n **/\n size: function() {\n return this.metaData().size;\n },\n\n /**\n * Returns the file's owner.\n * @return {String} The file's owner id.\n */\n ownerId: function() {\n return this.metaData().owner;\n },\n\n /**\n * Destroy the file.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n if (!this.id) {\n return Promise.reject(new Error('The file id is not eixsts.'));\n }\n var request = AVRequest(\"files\", null, this.id, 'DELETE', null, options);\n return request;\n },\n\n /**\n * Request Qiniu upload token\n * @param {string} type\n * @return {Promise} Resolved with the response\n * @private\n */\n _fileToken(type, route = 'fileTokens') {\n let name = this.attributes.name;\n\n let extName = extname(name);\n if (!extName && this._extName) {\n name += this._extName;\n extName = this._extName;\n }\n // Create 16-bits uuid as qiniu key.\n const key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName;\n const data = {\n key,\n name,\n ACL: this._acl,\n mime_type: type,\n metaData: this.attributes.metaData,\n };\n this._qiniu_key = key;\n return AVRequest(route, null, null, 'POST', data);\n },\n\n /**\n * @callback UploadProgressCallback\n * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes\n */\n /**\n * Saves the file to the AV cloud.\n * @param {Object} [options]\n * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。\n * @return {Promise} Promise that is resolved when the save finishes.\n */\n save(options) {\n if (this.id) {\n throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.');\n }\n if (!this._previousSave) {\n if (this._data) {\n let mimeType = this.get('mime_type');\n this._previousSave = this._fileToken(mimeType).then(uploadInfo => {\n if (uploadInfo.mime_type) {\n mimeType = uploadInfo.mime_type;\n this.set('mime_type', mimeType);\n }\n this._token = uploadInfo.token;\n return Promise.resolve().then(() => {\n const data = this._data;\n if (data && data.base64) {\n return parseBase64(data.base64, mimeType);\n }\n if (data && data.blob) {\n if (!data.blob.type && mimeType) {\n data.blob.type = mimeType;\n }\n if (!data.blob.name) {\n data.blob.name = this.get('name');\n }\n if (process.env.CLIENT_PLATFORM === 'ReactNative' || process.env.CLIENT_PLATFORM === 'Weapp') {\n this._extName = extname(data.blob.uri);\n }\n return data.blob;\n }\n if (typeof File !== \"undefined\" && data instanceof File) {\n if (data.size) {\n this.attributes.metaData.size = data.size;\n }\n if (data.name) {\n this._extName = extname(data.name);\n }\n return data;\n }\n if (typeof Buffer !== \"undefined\" && Buffer.isBuffer(data)) {\n this.attributes.metaData.size = data.length;\n return data;\n }\n throw new TypeError('malformed file data');\n }).then(data => {\n let uploadPromise;\n switch (uploadInfo.provider) {\n case 's3':\n uploadPromise = s3(uploadInfo, data, this, options);\n break;\n case 'qcloud':\n uploadPromise = cos(uploadInfo, data, this, options);\n break;\n case 'qiniu':\n default:\n uploadPromise = qiniu(uploadInfo, data, this, options);\n break;\n }\n return uploadPromise.then(\n tap(() => this._callback(true)),\n (error) => {\n this._callback(false);\n throw error;\n }\n );\n });\n });\n } else if (this.attributes.url && this.attributes.metaData.__source === 'external') {\n // external link file.\n const data = {\n name: this.attributes.name,\n ACL: this._acl,\n metaData: this.attributes.metaData,\n mime_type: this.mimeType,\n url: this.attributes.url,\n };\n this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then((response) => {\n this.attributes.name = response.name;\n this.attributes.url = response.url;\n this.id = response.objectId;\n if (response.size) {\n this.attributes.metaData.size = response.size;\n }\n return this;\n });\n }\n }\n return this._previousSave;\n },\n\n _callback(success) {\n AVRequest('fileCallback', null, null, 'post', {\n token: this._token,\n result: success,\n }).catch(debug);\n delete this._token;\n delete this._data;\n },\n\n /**\n * fetch the file from server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option.\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(options) {\n var options = null;\n\n var request = AVRequest('files', null, this.id, 'GET', options);\n return request.then(this._finishFetch.bind(this));\n },\n _finishFetch: function(response) {\n var value = AV.Object.prototype.parse(response);\n value.attributes = {\n name: value.name,\n url: value.url,\n mime_type: value.mime_type,\n bucket: value.bucket,\n };\n value.attributes.metaData = value.metaData || {};\n value.id = value.objectId;\n // clean\n delete value.objectId;\n delete value.metaData;\n delete value.url;\n delete value.name;\n delete value.mime_type;\n delete value.bucket;\n _.extend(this, value);\n return this;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/file.js","var _ = require('underscore');\n\n/*global navigator: false */\nmodule.exports = function(AV) {\n /**\n * Creates a new GeoPoint with any of the following forms:
\n * @example\n * new GeoPoint(otherGeoPoint)\n * new GeoPoint(30, 30)\n * new GeoPoint([30, 30])\n * new GeoPoint({latitude: 30, longitude: 30})\n * new GeoPoint() // defaults to (0, 0)\n * @class\n *\n *

Represents a latitude / longitude point that may be associated\n * with a key in a AVObject or used as a reference point for geo queries.\n * This allows proximity-based queries on the key.

\n *\n *

Only one key in a class may contain a GeoPoint.

\n *\n *

Example:

\n   *   var point = new AV.GeoPoint(30.0, -20.0);\n   *   var object = new AV.Object(\"PlaceObject\");\n   *   object.set(\"location\", point);\n   *   object.save();

\n */\n AV.GeoPoint = function(arg1, arg2) {\n if (_.isArray(arg1)) {\n AV.GeoPoint._validate(arg1[0], arg1[1]);\n this.latitude = arg1[0];\n this.longitude = arg1[1];\n } else if (_.isObject(arg1)) {\n AV.GeoPoint._validate(arg1.latitude, arg1.longitude);\n this.latitude = arg1.latitude;\n this.longitude = arg1.longitude;\n } else if (_.isNumber(arg1) && _.isNumber(arg2)) {\n AV.GeoPoint._validate(arg1, arg2);\n this.latitude = arg1;\n this.longitude = arg2;\n } else {\n this.latitude = 0;\n this.longitude = 0;\n }\n\n // Add properties so that anyone using Webkit or Mozilla will get an error\n // if they try to set values that are out of bounds.\n var self = this;\n if (this.__defineGetter__ && this.__defineSetter__) {\n // Use _latitude and _longitude to actually store the values, and add\n // getters and setters for latitude and longitude.\n this._latitude = this.latitude;\n this._longitude = this.longitude;\n this.__defineGetter__(\"latitude\", function() {\n return self._latitude;\n });\n this.__defineGetter__(\"longitude\", function() {\n return self._longitude;\n });\n this.__defineSetter__(\"latitude\", function(val) {\n AV.GeoPoint._validate(val, self.longitude);\n self._latitude = val;\n });\n this.__defineSetter__(\"longitude\", function(val) {\n AV.GeoPoint._validate(self.latitude, val);\n self._longitude = val;\n });\n }\n };\n\n /**\n * @lends AV.GeoPoint.prototype\n * @property {float} latitude North-south portion of the coordinate, in range\n * [-90, 90]. Throws an exception if set out of range in a modern browser.\n * @property {float} longitude East-west portion of the coordinate, in range\n * [-180, 180]. Throws if set out of range in a modern browser.\n */\n\n /**\n * Throws an exception if the given lat-long is out of bounds.\n * @private\n */\n AV.GeoPoint._validate = function(latitude, longitude) {\n if (latitude < -90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" < -90.0.\");\n }\n if (latitude > 90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" > 90.0.\");\n }\n if (longitude < -180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" < -180.0.\");\n }\n if (longitude > 180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" > 180.0.\");\n }\n };\n\n /**\n * Creates a GeoPoint with the user's current location, if available.\n * @return {Promise.}\n */\n AV.GeoPoint.current = () => new AV.Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(function(location) {\n resolve(new AV.GeoPoint({\n latitude: location.coords.latitude,\n longitude: location.coords.longitude\n }));\n }, reject);\n });\n\n AV.GeoPoint.prototype = {\n /**\n * Returns a JSON representation of the GeoPoint, suitable for AV.\n * @return {Object}\n */\n toJSON: function() {\n AV.GeoPoint._validate(this.latitude, this.longitude);\n return {\n \"__type\": \"GeoPoint\",\n latitude: this.latitude,\n longitude: this.longitude\n };\n },\n\n /**\n * Returns the distance from this GeoPoint to another in radians.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n radiansTo: function(point) {\n var d2r = Math.PI / 180.0;\n var lat1rad = this.latitude * d2r;\n var long1rad = this.longitude * d2r;\n var lat2rad = point.latitude * d2r;\n var long2rad = point.longitude * d2r;\n var deltaLat = lat1rad - lat2rad;\n var deltaLong = long1rad - long2rad;\n var sinDeltaLatDiv2 = Math.sin(deltaLat / 2);\n var sinDeltaLongDiv2 = Math.sin(deltaLong / 2);\n // Square of half the straight line chord distance between both points.\n var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) +\n (Math.cos(lat1rad) * Math.cos(lat2rad) *\n sinDeltaLongDiv2 * sinDeltaLongDiv2));\n a = Math.min(1.0, a);\n return 2 * Math.asin(Math.sqrt(a));\n },\n\n /**\n * Returns the distance from this GeoPoint to another in kilometers.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n kilometersTo: function(point) {\n return this.radiansTo(point) * 6371.0;\n },\n\n /**\n * Returns the distance from this GeoPoint to another in miles.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n milesTo: function(point) {\n return this.radiansTo(point) * 3958.8;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/geopoint.js","const AV = require('./av');\nconst request = require('./request');\n\nconst initialize = (appId, appKey, masterKey, hookKey) => {\n if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) {\n console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.');\n }\n AV.applicationId = appId;\n AV.applicationKey = appKey;\n AV.masterKey = masterKey;\n if (!process.env.CLIENT_PLATFORM) {\n AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY;\n }\n AV._useMasterKey = false;\n};\n\nconst masterKeyWarn = () => {\n console.warn('MasterKey is not supposed to be used in browser.');\n};\n\n/**\n * Call this method first to set up your authentication tokens for AV.\n * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .\n * @function AV.init\n * @param {Object} options\n * @param {String} options.appId application id\n * @param {String} options.appKey application key\n * @param {String} options.masterKey application master key\n*/\n\nAV.init = (...args) => {\n if (args.length === 1) {\n const options = args[0];\n if (typeof options === 'object') {\n if (process.env.CLIENT_PLATFORM && options.masterKey) {\n masterKeyWarn();\n }\n initialize(options.appId, options.appKey, options.masterKey, options.hookKey);\n request.setServerUrlByRegion(options.region);\n } else {\n throw new Error('AV.init(): Parameter is not correct.');\n }\n } else {\n // 兼容旧版本的初始化方法\n if (process.env.CLIENT_PLATFORM && args[3]) {\n masterKeyWarn();\n }\n initialize(...args);\n request.setServerUrlByRegion('cn');\n }\n};\n\n// If we're running in node.js, allow using the master key.\nif (!process.env.CLIENT_PLATFORM) {\n AV.Cloud = AV.Cloud || {};\n /**\n * Switches the LeanCloud SDK to using the Master key. The Master key grants\n * priveleged access to the data in LeanCloud and can be used to bypass ACLs and\n * other restrictions that are applied to the client SDKs.\n *

Available in Cloud Code and Node.js only.\n *

\n */\n AV.Cloud.useMasterKey = function() {\n AV._useMasterKey = true;\n };\n}\n\n// 兼容老版本的初始化方法\nAV.initialize = AV.init;\n\n\n\n// WEBPACK FOOTER //\n// ./src/init.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * 包含了使用了 LeanCloud\n * 离线数据分析功能的函数。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @namespace\n */\n AV.Insight = AV.Insight || {};\n\n _.extend(AV.Insight, /** @lends AV.Insight */ {\n\n /**\n * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用\n * AV.Insight.JobQuery 查询任务状态和结果。\n * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
\n     *                   { \"sql\" : \"select count(*) as c,gender from _User group by gender\",\n     *                     \"saveAs\": {\n     *                         \"className\" : \"UserGender\",\n     *                         \"limit\": 1\n     *                      }\n     *                   }\n     *                  
\n * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n startJob: function(jobConfig, options) {\n if(!jobConfig || !jobConfig.sql) {\n throw new Error('Please provide the sql to run the job.');\n }\n var data = {\n jobConfig: jobConfig,\n appId: AV.applicationId\n };\n var request = AVRequest(\"bigquery\", 'jobs', null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).id;\n });\n },\n\n /**\n * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成\n * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息,\n * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。\n *\n */\n on: function(event, cb) {\n }\n });\n\n /**\n * 创建一个对象,用于查询 Insight 任务状态和结果。\n * @class\n * @param {String} id 任务 id\n * @since 0.5.5\n */\n AV.Insight.JobQuery = function(id, className) {\n if(!id) {\n throw new Error('Please provide the job id.');\n }\n this.id = id;\n this.className = className;\n this._skip = 0;\n this._limit = 100;\n };\n\n AV.Insight.JobQuery.prototype = {\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n this._limit = n;\n return this;\n },\n\n /**\n * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数,\n * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间\n * startTime、endTime 等信息。\n *\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n *\n */\n find: function(options) {\n var params = {\n skip: this._skip,\n limit: this._limit\n };\n\n var request = AVRequest(\"bigquery\", 'jobs', this.id, \"GET\",\n params, options);\n var self = this;\n return request.then(function(response) {\n if(response.error) {\n return AV.Promise.reject(new AVError(response.code, response.error));\n }\n return AV.Promise.resolve(response);\n });\n }\n\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/insight.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst utils = require('./utils');\n\nconst RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt'];\nconst checkReservedKey = key => {\n if (RESERVED_KEYS.indexOf(key) !== -1) {\n throw new Error(`key[${key}] is reserved`);\n }\n};\n\n// AV.Object is analogous to the Java AVObject.\n// It also implements the same interface as a Backbone model.\n\nmodule.exports = function(AV) {\n /**\n * Creates a new model with defined attributes. A client id (cid) is\n * automatically generated and assigned for you.\n *\n *

You won't normally call this method directly. It is recommended that\n * you use a subclass of AV.Object instead, created by calling\n * extend.

\n *\n *

However, if you don't want to use a subclass, or aren't sure which\n * subclass is appropriate, you can use this form:

\n   *     var object = new AV.Object(\"ClassName\");\n   * 
\n * That is basically equivalent to:
\n   *     var MyClass = AV.Object.extend(\"ClassName\");\n   *     var object = new MyClass();\n   * 

\n *\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @see AV.Object.extend\n *\n * @class\n *\n *

The fundamental unit of AV data, which implements the Backbone Model\n * interface.

\n */\n AV.Object = function(attributes, options) {\n // Allow new AV.Object(\"ClassName\") as a shortcut to _create.\n if (_.isString(attributes)) {\n return AV.Object._create.apply(this, arguments);\n }\n\n attributes = attributes || {};\n if (options && options.parse) {\n attributes = this.parse(attributes);\n attributes = this._mergeMagicFields(attributes);\n }\n var defaults = AV._getValue(this, 'defaults');\n if (defaults) {\n attributes = _.extend({}, defaults, attributes);\n }\n if (options && options.collection) {\n this.collection = options.collection;\n }\n\n this._serverData = {}; // The last known data for this object from cloud.\n this._opSetQueue = [{}]; // List of sets of changes to the data.\n this._flags = {};\n this.attributes = {}; // The best estimate of this's current data.\n\n this._hashedJSON = {}; // Hash of values of containers at last save.\n this._escapedAttributes = {};\n this.cid = _.uniqueId('c');\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this.set(attributes, { silent: true });\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this._hasData = true;\n this._previousAttributes = _.clone(this.attributes);\n this.initialize.apply(this, arguments);\n };\n\n /**\n * @lends AV.Object.prototype\n * @property {String} id The objectId of the AV Object.\n */\n\n /**\n * Saves the given list of AV.Object.\n * If any error is encountered, stops and calls the error handler.\n *\n *
\n   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {\n   *     // All the objects were saved.\n   *   }, function(error) {\n   *     // An error occurred while saving one of the objects.\n   *   });\n   *\n   * @param {Array} list A list of AV.Object.\n   */\n  AV.Object.saveAll = function(list, options) {\n    return AV.Object._deepSaveAsync(list, null, options);\n  };\n\n  /**\n   * Fetch the given list of AV.Object.\n   *\n   * @param {AV.Object[]} objects A list of AV.Object\n   * @param {AuthOptions} options\n   * @return {Promise.} The given list of AV.Object, updated\n   */\n\n  AV.Object.fetchAll = (objects, options) =>\n    AV.Promise.resolve().then(() =>\n      AVRequest('batch', null, null, 'POST', {\n        requests: _.map(objects, object => {\n          if (!object.className) throw new Error('object must have className to fetch');\n          if (!object.id) throw new Error('object must have id to fetch');\n          if (object.dirty()) throw new Error('object is modified but not saved');\n          return {\n            method: 'GET',\n            path: `/1.1/classes/${object.className}/${object.id}`,\n          };\n        }),\n      }, options)\n    ).then(function(response) {\n      _.forEach(objects, function(object, i) {\n        if (response[i].success) {\n          object._finishFetch(\n            object.parse(response[i].success));\n        } else {\n          const error = new Error(response[i].error.error);\n          error.code = response[i].error.code;\n          throw error;\n        }\n      });\n      return objects;\n    });\n\n  // Attach all inheritable methods to the AV.Object prototype.\n  _.extend(AV.Object.prototype, AV.Events,\n           /** @lends AV.Object.prototype */ {\n    _fetchWhenSave: false,\n\n    /**\n     * Initialize is an empty function by default. Override it with your own\n     * initialization logic.\n     */\n    initialize: function(){},\n\n   /**\n     * Set whether to enable fetchWhenSave option when updating object.\n     * When set true, SDK would fetch the latest object after saving.\n     * Default is false.\n     *\n     * @deprecated use AV.Object#save with options.fetchWhenSave instead\n     * @param {boolean} enable  true to enable fetchWhenSave option.\n     */\n    fetchWhenSave: function(enable){\n      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');\n      if (!_.isBoolean(enable)) {\n        throw new Error('Expect boolean value for fetchWhenSave');\n      }\n      this._fetchWhenSave = enable;\n    },\n\n   /**\n    * Returns the object's objectId.\n    * @return {String} the objectId.\n    */\n    getObjectId: function() {\n      return this.id;\n    },\n\n   /**\n    * Returns the object's createdAt attribute.\n    * @return {Date}\n    */\n    getCreatedAt: function() {\n      return this.createdAt || this.get('createdAt');\n    },\n\n   /**\n    * Returns the object's updatedAt attribute.\n    * @return {Date}\n    */\n    getUpdatedAt: function() {\n      return this.updatedAt || this.get('updatedAt');\n    },\n\n    /**\n     * Returns a JSON version of the object suitable for saving to AV.\n     * @return {Object}\n     */\n    toJSON: function() {\n      var json = this._toFullJSON();\n      AV._arrayEach([\"__type\", \"className\"],\n                       function(key) { delete json[key]; });\n      return json;\n    },\n\n    _toFullJSON: function(seenObjects) {\n      var json = _.clone(this.attributes);\n      AV._objectEach(json, function(val, key) {\n        json[key] = AV._encode(val, seenObjects);\n      });\n      AV._objectEach(this._operations, function(val, key) {\n        json[key] = val;\n      });\n\n      if (_.has(this, \"id\")) {\n        json.objectId = this.id;\n      }\n      _(['createdAt', 'updatedAt']).each((key) => {\n        if (_.has(this, key)) {\n          const val = this[key];\n          json[key] = _.isDate(val) ? val.toJSON() : val;\n        }\n      });\n      json.__type = \"Object\";\n      json.className = this.className;\n      return json;\n    },\n\n    /**\n     * Updates _hashedJSON to reflect the current state of this object.\n     * Adds any changed hash values to the set of pending changes.\n     * @private\n     */\n    _refreshCache: function() {\n      var self = this;\n      if (self._refreshingCache) {\n        return;\n      }\n      self._refreshingCache = true;\n      AV._objectEach(this.attributes, function(value, key) {\n        if (value instanceof AV.Object) {\n          value._refreshCache();\n        } else if (_.isObject(value)) {\n          if (self._resetCacheForKey(key)) {\n            self.set(key, new AV.Op.Set(value), { silent: true });\n          }\n        }\n      });\n      delete self._refreshingCache;\n    },\n\n    /**\n     * Returns true if this object has been modified since its last\n     * save/refresh.  If an attribute is specified, it returns true only if that\n     * particular attribute has been modified since the last save/refresh.\n     * @param {String} attr An attribute name (optional).\n     * @return {Boolean}\n     */\n    dirty: function(attr) {\n      this._refreshCache();\n\n      var currentChanges = _.last(this._opSetQueue);\n\n      if (attr) {\n        return (currentChanges[attr] ? true : false);\n      }\n      if (!this.id) {\n        return true;\n      }\n      if (_.keys(currentChanges).length > 0) {\n        return true;\n      }\n      return false;\n    },\n\n    /**\n     * Gets a Pointer referencing this Object.\n     * @private\n     */\n    _toPointer: function() {\n      // if (!this.id) {\n      //   throw new Error(\"Can't serialize an unsaved AV.Object\");\n      // }\n      return { __type: \"Pointer\",\n               className: this.className,\n               objectId: this.id };\n    },\n\n    /**\n     * Gets the value of an attribute.\n     * @param {String} attr The string name of an attribute.\n     */\n    get: function(attr) {\n      switch (attr) {\n        case 'objectId':\n          return this.id;\n        case 'createdAt':\n        case 'updatedAt':\n          return this[attr];\n        default:\n          return this.attributes[attr];\n      }\n    },\n\n    /**\n     * Gets a relation on the given class for the attribute.\n     * @param {String} attr The attribute to get the relation for.\n     * @return {AV.Relation}\n     */\n    relation: function(attr) {\n      var value = this.get(attr);\n      if (value) {\n        if (!(value instanceof AV.Relation)) {\n          throw new Error(\"Called relation() on non-relation field \" + attr);\n        }\n        value._ensureParentAndKey(this, attr);\n        return value;\n      } else {\n        return new AV.Relation(this, attr);\n      }\n    },\n\n    /**\n     * Gets the HTML-escaped value of an attribute.\n     */\n    escape: function(attr) {\n      var html = this._escapedAttributes[attr];\n      if (html) {\n        return html;\n      }\n      var val = this.attributes[attr];\n      var escaped;\n      if (utils.isNullOrUndefined(val)) {\n        escaped = '';\n      } else {\n        escaped = _.escape(val.toString());\n      }\n      this._escapedAttributes[attr] = escaped;\n      return escaped;\n    },\n\n    /**\n     * Returns true if the attribute contains a value that is not\n     * null or undefined.\n     * @param {String} attr The string name of the attribute.\n     * @return {Boolean}\n     */\n    has: function(attr) {\n      return !utils.isNullOrUndefined(this.attributes[attr]);\n    },\n\n    /**\n     * Pulls \"special\" fields like objectId, createdAt, etc. out of attrs\n     * and puts them on \"this\" directly.  Removes them from attrs.\n     * @param attrs - A dictionary with the data for this AV.Object.\n     * @private\n     */\n    _mergeMagicFields: function(attrs) {\n      // Check for changes of magic fields.\n      var model = this;\n      var specialFields = [\"objectId\", \"createdAt\", \"updatedAt\"];\n      AV._arrayEach(specialFields, function(attr) {\n        if (attrs[attr]) {\n          if (attr === \"objectId\") {\n            model.id = attrs[attr];\n          } else if ((attr === \"createdAt\" || attr === \"updatedAt\") &&\n                     !_.isDate(attrs[attr])) {\n            model[attr] = AV._parseDate(attrs[attr]);\n          } else { \n            model[attr] = attrs[attr]; \n          }\n          delete attrs[attr];\n        }\n      });\n      return attrs;\n    },\n\n    /**\n     * Returns the json to be sent to the server.\n     * @private\n     */\n    _startSave: function() {\n      this._opSetQueue.push({});\n    },\n\n    /**\n     * Called when a save fails because of an error. Any changes that were part\n     * of the save need to be merged with changes made after the save. This\n     * might throw an exception is you do conflicting operations. For example,\n     * if you do:\n     *   object.set(\"foo\", \"bar\");\n     *   object.set(\"invalid field name\", \"baz\");\n     *   object.save();\n     *   object.increment(\"foo\");\n     * then this will throw when the save fails and the client tries to merge\n     * \"bar\" with the +1.\n     * @private\n     */\n    _cancelSave: function() {\n      var self = this;\n      var failedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      var nextChanges = _.first(this._opSetQueue);\n      AV._objectEach(failedChanges, function(op, key) {\n        var op1 = failedChanges[key];\n        var op2 = nextChanges[key];\n        if (op1 && op2) {\n          nextChanges[key] = op2._mergeWithPrevious(op1);\n        } else if (op1) {\n          nextChanges[key] = op1;\n        }\n      });\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a save completes successfully. This merges the changes that\n     * were saved into the known server data, and overrides it with any data\n     * sent directly from the server.\n     * @private\n     */\n    _finishSave: function(serverData) {\n      // Grab a copy of any object referenced by this object. These instances\n      // may have already been fetched, and we don't want to lose their data.\n      // Note that doing it like this means we will unify separate copies of the\n      // same object, but that's a risk we have to take.\n      var fetchedObjects = {};\n      AV._traverse(this.attributes, function(object) {\n        if (object instanceof AV.Object && object.id && object._hasData) {\n          fetchedObjects[object.id] = object;\n        }\n      });\n\n      var savedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      this._applyOpSet(savedChanges, this._serverData);\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n\n        // Look for any objects that might have become unfetched and fix them\n        // by replacing their values with the previously observed values.\n        var fetched = AV._traverse(self._serverData[key], function(object) {\n          if (object instanceof AV.Object && fetchedObjects[object.id]) {\n            return fetchedObjects[object.id];\n          }\n        });\n        if (fetched) {\n          self._serverData[key] = fetched;\n        }\n      });\n      this._rebuildAllEstimatedData();\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a fetch or login is complete to set the known server data to\n     * the given object.\n     * @private\n     */\n    _finishFetch: function(serverData, hasData) {\n      // Clear out any changes the user might have made previously.\n      this._opSetQueue = [{}];\n\n      // Bring in all the new server data.\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n      });\n\n      // Refresh the attributes.\n      this._rebuildAllEstimatedData();\n\n      // Clear out the cache of mutable containers.\n      this._refreshCache();\n      this._opSetQueue = [{}];\n\n      this._hasData = hasData;\n    },\n\n    /**\n     * Applies the set of AV.Op in opSet to the object target.\n     * @private\n     */\n    _applyOpSet: function(opSet, target) {\n      var self = this;\n      AV._objectEach(opSet, function(change, key) {\n        target[key] = change._estimate(target[key], self, key);\n        if (target[key] === AV.Op._UNSET) {\n          delete target[key];\n        }\n      });\n    },\n\n    /**\n     * Replaces the cached value for key with the current value.\n     * Returns true if the new value is different than the old value.\n     * @private\n     */\n    _resetCacheForKey: function(key) {\n      var value = this.attributes[key];\n      if (_.isObject(value) &&\n          !(value instanceof AV.Object) &&\n          !(value instanceof AV.File)) {\n\n        value = value.toJSON ? value.toJSON() : value;\n        var json = JSON.stringify(value);\n        if (this._hashedJSON[key] !== json) {\n          var wasSet = !! this._hashedJSON[key];\n          this._hashedJSON[key] = json;\n          return wasSet;\n        }\n      }\n      return false;\n    },\n\n    /**\n     * Populates attributes[key] by starting with the last known data from the\n     * server, and applying all of the local changes that have been made to that\n     * key since then.\n     * @private\n     */\n    _rebuildEstimatedDataForKey: function(key) {\n      var self = this;\n      delete this.attributes[key];\n      if (this._serverData[key]) {\n        this.attributes[key] = this._serverData[key];\n      }\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        var op = opSet[key];\n        if (op) {\n          self.attributes[key] = op._estimate(self.attributes[key], self, key);\n          if (self.attributes[key] === AV.Op._UNSET) {\n            delete self.attributes[key];\n          } else {\n            self._resetCacheForKey(key);\n          }\n        }\n      });\n    },\n\n    /**\n     * Populates attributes by starting with the last known data from the\n     * server, and applying all of the local changes that have been made since\n     * then.\n     * @private\n     */\n    _rebuildAllEstimatedData: function() {\n      var self = this;\n\n      var previousAttributes = _.clone(this.attributes);\n\n      this.attributes = _.clone(this._serverData);\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        self._applyOpSet(opSet, self.attributes);\n        AV._objectEach(opSet, function(op, key) {\n          self._resetCacheForKey(key);\n        });\n      });\n\n      // Trigger change events for anything that changed because of the fetch.\n      AV._objectEach(previousAttributes, function(oldValue, key) {\n        if (self.attributes[key] !== oldValue) {\n          self.trigger('change:' + key, self, self.attributes[key], {});\n        }\n      });\n      AV._objectEach(this.attributes, function(newValue, key) {\n        if (!_.has(previousAttributes, key)) {\n          self.trigger('change:' + key, self, newValue, {});\n        }\n      });\n    },\n\n    /**\n     * Sets a hash of model attributes on the object, firing\n     * \"change\" unless you choose to silence it.\n     *\n     * 

You can call it with an object containing keys and values, or with one\n * key and value. For example:

\n     *   gameTurn.set({\n     *     player: player1,\n     *     diceRoll: 2\n     *   }, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"currentPlayer\", player2, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"finished\", true);

\n *\n * @param {String} key The key to set.\n * @param {Any} value The value to give it.\n * @param {Object} [options]\n * @param {Boolean} [options.silent]\n * @return {AV.Object} self if succeeded, throws if the value is not valid.\n * @see AV.Object#validate\n */\n set: function(key, value, options) {\n var attrs;\n if (_.isObject(key) || utils.isNullOrUndefined(key)) {\n attrs = _.mapObject(key, function(v, k) {\n checkReservedKey(k);\n return AV._decode(v, k);\n });\n options = value;\n } else {\n attrs = {};\n checkReservedKey(key);\n attrs[key] = AV._decode(value, key);\n }\n\n // Extract attributes and options.\n options = options || {};\n if (!attrs) {\n return this;\n }\n if (attrs instanceof AV.Object) {\n attrs = attrs.attributes;\n }\n\n // If the unset option is used, every attribute should be a Unset.\n if (options.unset) {\n AV._objectEach(attrs, function(unused_value, key) {\n attrs[key] = new AV.Op.Unset();\n });\n }\n\n // Apply all the attributes to get the estimated values.\n var dataToValidate = _.clone(attrs);\n var self = this;\n AV._objectEach(dataToValidate, function(value, key) {\n if (value instanceof AV.Op) {\n dataToValidate[key] = value._estimate(self.attributes[key],\n self, key);\n if (dataToValidate[key] === AV.Op._UNSET) {\n delete dataToValidate[key];\n }\n }\n });\n\n // Run validation.\n this._validate(attrs, options);\n\n options.changes = {};\n var escaped = this._escapedAttributes;\n var prev = this._previousAttributes || {};\n\n // Update attributes.\n AV._arrayEach(_.keys(attrs), function(attr) {\n var val = attrs[attr];\n\n // If this is a relation object we need to set the parent correctly,\n // since the location where it was parsed does not have access to\n // this object.\n if (val instanceof AV.Relation) {\n val.parent = self;\n }\n\n if (!(val instanceof AV.Op)) {\n val = new AV.Op.Set(val);\n }\n\n // See if this change will actually have any effect.\n var isRealChange = true;\n if (val instanceof AV.Op.Set &&\n _.isEqual(self.attributes[attr], val.value)) {\n isRealChange = false;\n }\n\n if (isRealChange) {\n delete escaped[attr];\n if (options.silent) {\n self._silent[attr] = true;\n } else {\n options.changes[attr] = true;\n }\n }\n\n var currentChanges = _.last(self._opSetQueue);\n currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]);\n self._rebuildEstimatedDataForKey(attr);\n\n if (isRealChange) {\n self.changed[attr] = self.attributes[attr];\n if (!options.silent) {\n self._pending[attr] = true;\n }\n } else {\n delete self.changed[attr];\n delete self._pending[attr];\n }\n });\n\n if (!options.silent) {\n this.change(options);\n }\n return this;\n },\n\n /**\n * Remove an attribute from the model, firing \"change\" unless\n * you choose to silence it. This is a noop if the attribute doesn't\n * exist.\n */\n unset: function(attr, options) {\n options = options || {};\n options.unset = true;\n return this.set(attr, null, options);\n },\n\n /**\n * Atomically increments the value of the given attribute the next time the\n * object is saved. If no amount is specified, 1 is used by default.\n *\n * @param attr {String} The key.\n * @param amount {Number} The amount to increment by.\n */\n increment: function(attr, amount) {\n if (_.isUndefined(amount) || _.isNull(amount)) {\n amount = 1;\n }\n return this.set(attr, new AV.Op.Increment(amount));\n },\n\n /**\n * Atomically add an object to the end of the array associated with a given\n * key.\n * @param attr {String} The key.\n * @param item {} The item to add.\n */\n add: function(attr, item) {\n return this.set(attr, new AV.Op.Add(utils.ensureArray(item)));\n },\n\n /**\n * Atomically add an object to the array associated with a given key, only\n * if it is not already present in the array. The position of the insert is\n * not guaranteed.\n *\n * @param attr {String} The key.\n * @param item {} The object to add.\n */\n addUnique: function(attr, item) {\n return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item)));\n },\n\n /**\n * Atomically remove all instances of an object from the array associated\n * with a given key.\n *\n * @param attr {String} The key.\n * @param item {} The object to remove.\n */\n remove: function(attr, item) {\n return this.set(attr, new AV.Op.Remove(utils.ensureArray(item)));\n },\n\n /**\n * Returns an instance of a subclass of AV.Op describing what kind of\n * modification has been performed on this field since the last time it was\n * saved. For example, after calling object.increment(\"x\"), calling\n * object.op(\"x\") would return an instance of AV.Op.Increment.\n *\n * @param attr {String} The key.\n * @returns {AV.Op} The operation, or undefined if none.\n */\n op: function(attr) {\n return _.last(this._opSetQueue)[attr];\n },\n\n /**\n * Clear all attributes on the model, firing \"change\" unless\n * you choose to silence it.\n */\n clear: function(options) {\n options = options || {};\n options.unset = true;\n var keysToClear = _.extend(this.attributes, this._operations);\n return this.set(keysToClear, options);\n },\n\n /**\n * Returns a JSON-encoded set of operations to be sent with the next save\n * request.\n * @private\n */\n _getSaveJSON: function() {\n var json = _.clone(_.first(this._opSetQueue));\n AV._objectEach(json, function(op, key) {\n json[key] = op.toJSON();\n });\n return json;\n },\n\n /**\n * Returns true if this object can be serialized for saving.\n * @private\n */\n _canBeSerialized: function() {\n return AV.Object._canBeSerializedAsValue(this.attributes);\n },\n\n /**\n * Fetch the model from the server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * triggering a \"change\" event.\n * @param {Object} fetchOptions Optional options to set 'keys' and\n * 'include' option.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(fetchOptions = {}, options) {\n if (_.isArray(fetchOptions.keys)) {\n fetchOptions.keys = fetchOptions.keys.join(',');\n }\n if (_.isArray(fetchOptions.include)) {\n fetchOptions.include = fetchOptions.include.join(',');\n }\n\n var self = this;\n var request = AVRequest('classes', this.className, this.id, 'GET',\n fetchOptions, options);\n return request.then(function(response) {\n self._finishFetch(self.parse(response), true);\n return self;\n });\n },\n\n /**\n * Set a hash of model attributes, and save the model to the server.\n * updatedAt will be updated when the request returns.\n * You can either call it as:
\n     *   object.save();
\n * or
\n     *   object.save(null, options);
\n * or
\n     *   object.save(attrs, options);
\n * or
\n     *   object.save(key, value, options);
\n *\n * For example,
\n     *   gameTurn.save({\n     *     player: \"Jake Cutter\",\n     *     diceRoll: 2\n     *   }).then(function(gameTurnAgain) {\n     *     // The save was successful.\n     *   }, function(error) {\n     *     // The save failed.  Error is an instance of AVError.\n     *   });
\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded\n * @param {AV.Query} options.query Save object only when it matches the query\n * @return {AV.Promise} A promise that is fulfilled when the save\n * completes.\n * @see AVError\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n\n options = _.clone(options) || {};\n if (options.wait) {\n current = _.clone(this.attributes);\n }\n\n var setOptions = _.clone(options) || {};\n if (setOptions.wait) {\n setOptions.silent = true;\n }\n if (attrs) {\n this.set(attrs, setOptions);\n }\n\n var model = this;\n\n // If there is any unsaved child, save it first.\n model._refreshCache();\n\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(model.attributes,\n unsavedChildren,\n unsavedFiles);\n if (unsavedChildren.length + unsavedFiles.length > 0) {\n return AV.Object._deepSaveAsync(this.attributes, model, options).then(function() {\n return model.save(null, options);\n });\n }\n\n this._startSave();\n this._saving = (this._saving || 0) + 1;\n\n this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve();\n this._allPreviousSaves = this._allPreviousSaves.catch(e => {}).then(function() {\n var method = model.id ? 'PUT' : 'POST';\n\n var json = model._getSaveJSON();\n\n if(model._fetchWhenSave){\n //Sepcial-case fetchWhenSave when updating object.\n json._fetchWhenSave = true;\n }\n\n if (options.fetchWhenSave) {\n json._fetchWhenSave = true;\n }\n if (options.query) {\n var queryJSON;\n if (typeof options.query.toJSON === 'function') {\n queryJSON = options.query.toJSON();\n if (queryJSON) {\n json._where = queryJSON.where;\n }\n }\n if (!json._where) {\n var error = new Error('options.query is not an AV.Query');\n throw error;\n }\n }\n\n _.extend(json, model._flags);\n\n var route = \"classes\";\n var className = model.className;\n if (model.className === \"_User\" && !model.id) {\n // Special-case user sign-up.\n route = \"users\";\n className = null;\n }\n //hook makeRequest in options.\n var makeRequest = options._makeRequest || AVRequest;\n var request = makeRequest(route, className, model.id, method, json, options);\n\n request = request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n if (options.wait) {\n serverAttrs = _.extend(attrs || {}, serverAttrs);\n }\n model._finishSave(serverAttrs);\n if (options.wait) {\n model.set(current, setOptions);\n }\n return model;\n\n }, function(error) {\n model._cancelSave();\n throw error;\n });\n\n return request;\n });\n return this._allPreviousSaves;\n },\n\n /**\n * Destroy this model on the server if it was already persisted.\n * Optimistically removes the model from its collection, if it has one.\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} [options.wait] wait for the server to respond\n * before removal.\n *\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n options = options || {};\n var model = this;\n\n var triggerDestroy = function() {\n model.trigger('destroy', model, model.collection, options);\n };\n\n if (!this.id) {\n return triggerDestroy();\n }\n\n if (!options.wait) {\n triggerDestroy();\n }\n\n var request =\n AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options);\n return request.then(function() {\n if (options.wait) {\n triggerDestroy();\n }\n return model;\n });\n },\n\n /**\n * Converts a response into the hash of attributes to be set on the model.\n * @ignore\n */\n parse: function(resp) {\n var output = _.clone(resp);\n _([\"createdAt\", \"updatedAt\"]).each(function(key) {\n if (output[key]) {\n output[key] = AV._parseDate(output[key]);\n }\n });\n if (!output.updatedAt) {\n output.updatedAt = output.createdAt;\n }\n return output;\n },\n\n /**\n * Creates a new model with identical attributes to this one.\n * @return {AV.Object}\n */\n clone: function() {\n return new this.constructor(this.attributes);\n },\n\n /**\n * Returns true if this object has never been saved to AV.\n * @return {Boolean}\n */\n isNew: function() {\n return !this.id;\n },\n\n /**\n * Call this method to manually fire a `\"change\"` event for this model and\n * a `\"change:attribute\"` event for each changed attribute.\n * Calling this will cause all objects observing the model to update.\n */\n change: function(options) {\n options = options || {};\n var changing = this._changing;\n this._changing = true;\n\n // Silent changes become pending changes.\n var self = this;\n AV._objectEach(this._silent, function(attr) {\n self._pending[attr] = true;\n });\n\n // Silent changes are triggered.\n var changes = _.extend({}, options.changes, this._silent);\n this._silent = {};\n AV._objectEach(changes, function(unused_value, attr) {\n self.trigger('change:' + attr, self, self.get(attr), options);\n });\n if (changing) {\n return this;\n }\n\n // This is to get around lint not letting us make a function in a loop.\n var deleteChanged = function(value, attr) {\n if (!self._pending[attr] && !self._silent[attr]) {\n delete self.changed[attr];\n }\n };\n\n // Continue firing `\"change\"` events while there are pending changes.\n while (!_.isEmpty(this._pending)) {\n this._pending = {};\n this.trigger('change', this, options);\n // Pending and silent changes still remain.\n AV._objectEach(this.changed, deleteChanged);\n self._previousAttributes = _.clone(this.attributes);\n }\n\n this._changing = false;\n return this;\n },\n\n /**\n * Determine if the model has changed since the last \"change\"\n * event. If you specify an attribute name, determine if that attribute\n * has changed.\n * @param {String} attr Optional attribute name\n * @return {Boolean}\n */\n hasChanged: function(attr) {\n if (!arguments.length) {\n return !_.isEmpty(this.changed);\n }\n return this.changed && _.has(this.changed, attr);\n },\n\n /**\n * Returns an object containing all the attributes that have changed, or\n * false if there are no changed attributes. Useful for determining what\n * parts of a view need to be updated and/or what attributes need to be\n * persisted to the server. Unset attributes will be set to undefined.\n * You can also pass an attributes object to diff against the model,\n * determining if there *would be* a change.\n */\n changedAttributes: function(diff) {\n if (!diff) {\n return this.hasChanged() ? _.clone(this.changed) : false;\n }\n var changed = {};\n var old = this._previousAttributes;\n AV._objectEach(diff, function(diffVal, attr) {\n if (!_.isEqual(old[attr], diffVal)) {\n changed[attr] = diffVal;\n }\n });\n return changed;\n },\n\n /**\n * Gets the previous value of an attribute, recorded at the time the last\n * \"change\" event was fired.\n * @param {String} attr Name of the attribute to get.\n */\n previous: function(attr) {\n if (!arguments.length || !this._previousAttributes) {\n return null;\n }\n return this._previousAttributes[attr];\n },\n\n /**\n * Gets all of the attributes of the model at the time of the previous\n * \"change\" event.\n * @return {Object}\n */\n previousAttributes: function() {\n return _.clone(this._previousAttributes);\n },\n\n /**\n * Checks if the model is currently in a valid state. It's only possible to\n * get into an *invalid* state if you're using silent changes.\n * @return {Boolean}\n */\n isValid: function() {\n try {\n this.validate(this.attributes);\n } catch (error) {\n return false;\n }\n return true;\n },\n\n /**\n * You should not call this function directly unless you subclass\n * AV.Object, in which case you can override this method\n * to provide additional validation on set and\n * save. Your implementation should throw an Error if\n * the attrs is invalid\n *\n * @param {Object} attrs The current data to validate.\n * @see AV.Object#set\n */\n validate: function(attrs) {\n if (_.has(attrs, \"ACL\") && !(attrs.ACL instanceof AV.ACL)) {\n throw new AVError(AVError.OTHER_CAUSE,\n \"ACL must be a AV.ACL.\");\n }\n },\n\n /**\n * Run validation against a set of incoming attributes, returning `true`\n * if all is well. If a specific `error` callback has been passed,\n * call that instead of firing the general `\"error\"` event.\n * @private\n */\n _validate: function(attrs, options) {\n if (options.silent || !this.validate) {\n return;\n }\n attrs = _.extend({}, this.attributes, attrs);\n this.validate(attrs);\n },\n\n /**\n * Returns the ACL for this object.\n * @returns {AV.ACL} An instance of AV.ACL.\n * @see AV.Object#get\n */\n getACL: function() {\n return this.get(\"ACL\");\n },\n\n /**\n * Sets the ACL to be used for this object.\n * @param {AV.ACL} acl An instance of AV.ACL.\n * @param {Object} options Optional Backbone-like options object to be\n * passed in to set.\n * @return {Boolean} Whether the set passed validation.\n * @see AV.Object#set\n */\n setACL: function(acl, options) {\n return this.set(\"ACL\", acl, options);\n },\n\n disableBeforeHook: function() {\n this.ignoreHook('beforeSave');\n this.ignoreHook('beforeUpdate');\n this.ignoreHook('beforeDelete');\n },\n\n disableAfterHook: function() {\n this.ignoreHook('afterSave');\n this.ignoreHook('afterUpdate');\n this.ignoreHook('afterDelete');\n },\n\n ignoreHook: function(hookName) {\n if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) {\n console.trace('Unsupported hookName: ' + hookName);\n }\n\n if (!AV.hookKey) {\n console.trace('ignoreHook required hookKey');\n }\n\n if (!this._flags.__ignore_hooks) {\n this._flags.__ignore_hooks = [];\n }\n\n this._flags.__ignore_hooks.push(hookName);\n }\n });\n\n /**\n * Creates an instance of a subclass of AV.Object for the give classname\n * and id.\n * @param {String} className The name of the AV class backing this model.\n * @param {String} id The object id of this model.\n * @return {AV.Object} A new subclass instance of AV.Object.\n */\n AV.Object.createWithoutData = function(className, id, hasData){\n var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n result.id = id;\n result._hasData = hasData;\n return result;\n };\n /**\n * Delete objects in batch.\n * @param {AV.Object[]} objects The AV.Object array to be deleted.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n AV.Object.destroyAll = function(objects, options = {}){\n if (!objects || objects.length === 0){\n\t\t return AV.Promise.resolve();\n }\n const objectsByClassNameAndFlags = _.groupBy(objects, object => JSON.stringify({\n className: object.className,\n flags: object._flags\n }));\n const body = {\n requests: _.map(objectsByClassNameAndFlags, objects => {\n const ids = _.map(objects, 'id').join(',');\n return {\n method: 'DELETE',\n path: `/1.1/classes/${objects[0].className}/${ids}`,\n body: objects[0]._flags\n }\n })\n };\n return AVRequest('batch', null, null, 'POST', body, options);\n };\n\n /**\n * Returns the appropriate subclass for making new instances of the given\n * className string.\n * @private\n */\n AV.Object._getSubclass = function(className) {\n if (!_.isString(className)) {\n throw new Error('AV.Object._getSubclass requires a string argument.');\n }\n var ObjectClass = AV.Object._classMap[className];\n if (!ObjectClass) {\n ObjectClass = AV.Object.extend(className);\n AV.Object._classMap[className] = ObjectClass;\n }\n return ObjectClass;\n };\n\n /**\n * Creates an instance of a subclass of AV.Object for the given classname.\n * @private\n */\n AV.Object._create = function(className, attributes, options, noDefaultACL) {\n var ObjectClass = AV.Object._getSubclass(className);\n return new ObjectClass(attributes, options, noDefaultACL);\n };\n\n // Set up a map of className to class so that we can create new instances of\n // AV Objects from JSON automatically.\n AV.Object._classMap = {};\n\n AV.Object._extend = AV._extend;\n\n /**\n * Creates a new model with defined attributes,\n * It's the same with\n *
\n   *   new AV.Object(attributes, options);\n   *  
\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @return {AV.Object}\n * @since v0.4.4\n * @see AV.Object\n * @see AV.Object.extend\n */\n AV.Object['new'] = function(attributes, options){\n return new AV.Object(attributes, options);\n };\n\n /**\n * Creates a new subclass of AV.Object for the given AV class name.\n *\n *

Every extension of a AV class will inherit from the most recent\n * previous extension of that class. When a AV.Object is automatically\n * created by parsing JSON, it will use the most recent extension of that\n * class.

\n *\n *

You should call either:

\n   *     var MyClass = AV.Object.extend(\"MyClass\", {\n   *         Instance properties\n   *     }, {\n   *         Class properties\n   *     });
\n * or, for Backbone compatibility:
\n   *     var MyClass = AV.Object.extend({\n   *         className: \"MyClass\",\n   *         Other instance properties\n   *     }, {\n   *         Class properties\n   *     });

\n *\n * @param {String} className The name of the AV class backing this model.\n * @param {Object} protoProps Instance properties to add to instances of the\n * class returned from this method.\n * @param {Object} classProps Class properties to add the class returned from\n * this method.\n * @return {Class} A new subclass of AV.Object.\n */\n AV.Object.extend = function(className, protoProps, classProps) {\n // Handle the case with only two args.\n if (!_.isString(className)) {\n if (className && _.has(className, \"className\")) {\n return AV.Object.extend(className.className, className, protoProps);\n } else {\n throw new Error(\n \"AV.Object.extend's first argument should be the className.\");\n }\n }\n\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n className = \"_User\";\n }\n\n var NewClassObject = null;\n if (_.has(AV.Object._classMap, className)) {\n var OldClassObject = AV.Object._classMap[className];\n // This new subclass has been told to extend both from \"this\" and from\n // OldClassObject. This is multiple inheritance, which isn't supported.\n // For now, let's just pick one.\n if (protoProps || classProps) {\n NewClassObject = OldClassObject._extend(protoProps, classProps);\n } else {\n return OldClassObject;\n }\n } else {\n protoProps = protoProps || {};\n protoProps._className = className;\n NewClassObject = this._extend(protoProps, classProps);\n }\n // Extending a subclass should reuse the classname automatically.\n NewClassObject.extend = function(arg0) {\n if (_.isString(arg0) || (arg0 && _.has(arg0, \"className\"))) {\n return AV.Object.extend.apply(NewClassObject, arguments);\n }\n var newArguments = [className].concat(_.toArray(arguments));\n return AV.Object.extend.apply(NewClassObject, newArguments);\n };\n NewClassObject['new'] = function(attributes, options){\n return new NewClassObject(attributes, options);\n };\n AV.Object._classMap[className] = NewClassObject;\n return NewClassObject;\n };\n\n // ES6 class syntax support\n Object.defineProperty(AV.Object.prototype, 'className', {\n get: function(){\n const className = this._className || this.constructor._LCClassName || this.constructor.name;\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n return \"_User\";\n }\n return className;\n },\n });\n\n /**\n * Register a class.\n * If a subclass of AV.Object is defined with your own implement\n * rather then AV.Object.extend, the subclass must be registered.\n * @param {Function} klass A subclass of AV.Object\n * @param {String} [name] Specify the name of the class. Useful when the class might be uglified.\n * @example\n * class Person extend AV.Object {}\n * AV.Object.register(Person);\n */\n AV.Object.register = (klass, name) => {\n if (!(klass.prototype instanceof AV.Object)) {\n throw new Error('registered class is not a subclass of AV.Object');\n }\n const className = name || klass.name;\n if (!className.length) {\n throw new Error('registered class must be named');\n }\n if (name) {\n klass._LCClassName = name;\n }\n AV.Object._classMap[className] = klass;\n };\n\n AV.Object._findUnsavedChildren = function(object, children, files) {\n AV._traverse(object, function(object) {\n if (object instanceof AV.Object) {\n object._refreshCache();\n if (object.dirty()) {\n children.push(object);\n }\n return;\n }\n\n if (object instanceof AV.File) {\n if (!object.url() && !object.id) {\n files.push(object);\n }\n return;\n }\n });\n };\n\n AV.Object._canBeSerializedAsValue = function(object) {\n var canBeSerializedAsValue = true;\n\n if (object instanceof AV.Object || object instanceof AV.File) {\n canBeSerializedAsValue = !!object.id;\n\n } else if (_.isArray(object)) {\n AV._arrayEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n\n } else if (_.isObject(object)) {\n AV._objectEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n }\n\n return canBeSerializedAsValue;\n };\n\n AV.Object._deepSaveAsync = function(object, model, options) {\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles);\n if(model) {\n unsavedChildren = _.filter(unsavedChildren, function(object) {\n return object != model;\n });\n }\n\n var promise = AV.Promise.resolve();\n _.each(unsavedFiles, function(file) {\n promise = promise.then(function() {\n return file.save();\n });\n });\n\n var objects = _.uniq(unsavedChildren);\n var remaining = _.uniq(objects);\n\n return promise.then(function() {\n return AV.Promise._continueWhile(function() {\n return remaining.length > 0;\n }, function() {\n\n // Gather up all the objects that can be saved in this batch.\n var batch = [];\n var newRemaining = [];\n AV._arrayEach(remaining, function(object) {\n // Limit batches to 20 objects.\n if (batch.length > 20) {\n newRemaining.push(object);\n return;\n }\n\n if (object._canBeSerialized()) {\n batch.push(object);\n } else {\n newRemaining.push(object);\n }\n });\n remaining = newRemaining;\n\n // If we can't save any objects, there must be a circular reference.\n if (batch.length === 0) {\n return AV.Promise.reject(\n new AVError(AVError.OTHER_CAUSE,\n \"Tried to save a batch with a cycle.\"));\n }\n\n // Reserve a spot in every object's save queue.\n var readyToStart = AV.Promise.resolve(_.map(batch, function(object) {\n return object._allPreviousSaves || AV.Promise.resolve();\n }));\n\n // Save a single batch, whether previous saves succeeded or failed.\n const bathSavePromise = readyToStart.then(() =>\n AVRequest(\"batch\", null, null, \"POST\", {\n requests: _.map(batch, function(object) {\n var json = object._getSaveJSON();\n _.extend(json, object._flags);\n var method = \"POST\";\n\n var path = \"/1.1/classes/\" + object.className;\n if (object.id) {\n path = path + \"/\" + object.id;\n method = \"PUT\";\n }\n\n object._startSave();\n\n return {\n method: method,\n path: path,\n body: json\n };\n })\n\n }, options).then(function(response) {\n var error;\n AV._arrayEach(batch, function(object, i) {\n if (response[i].success) {\n object._finishSave(\n object.parse(response[i].success));\n } else {\n error = error || response[i].error;\n object._cancelSave();\n }\n });\n if (error) {\n return AV.Promise.reject(\n new AVError(error.code, error.error));\n }\n\n })\n );\n AV._arrayEach(batch, function(object) {\n object._allPreviousSaves = bathSavePromise;\n });\n return bathSavePromise;\n });\n }).then(function() {\n return object;\n });\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/object.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n\n /**\n * @private\n * @class\n * A AV.Op is an atomic operation that can be applied to a field in a\n * AV.Object. For example, calling object.set(\"foo\", \"bar\")\n * is an example of a AV.Op.Set. Calling object.unset(\"foo\")\n * is a AV.Op.Unset. These operations are stored in a AV.Object and\n * sent to the server as part of object.save() operations.\n * Instances of AV.Op should be immutable.\n *\n * You should not create subclasses of AV.Op or instantiate AV.Op\n * directly.\n */\n AV.Op = function() {\n this._initialize.apply(this, arguments);\n };\n\n AV.Op.prototype = {\n _initialize: function() {}\n };\n\n _.extend(AV.Op, {\n /**\n * To create a new Op, call AV.Op._extend();\n * @private\n */\n _extend: AV._extend,\n\n // A map of __op string to decoder function.\n _opDecoderMap: {},\n\n /**\n * Registers a function to convert a json object with an __op field into an\n * instance of a subclass of AV.Op.\n * @private\n */\n _registerDecoder: function(opName, decoder) {\n AV.Op._opDecoderMap[opName] = decoder;\n },\n\n /**\n * Converts a json object into an instance of a subclass of AV.Op.\n * @private\n */\n _decode: function(json) {\n var decoder = AV.Op._opDecoderMap[json.__op];\n if (decoder) {\n return decoder(json);\n } else {\n return undefined;\n }\n }\n });\n\n /*\n * Add a handler for Batch ops.\n */\n AV.Op._registerDecoder(\"Batch\", function(json) {\n var op = null;\n AV._arrayEach(json.ops, function(nextOp) {\n nextOp = AV.Op._decode(nextOp);\n op = nextOp._mergeWithPrevious(op);\n });\n return op;\n });\n\n /**\n * @private\n * @class\n * A Set operation indicates that either the field was changed using\n * AV.Object.set, or it is a mutable container that was detected as being\n * changed.\n */\n AV.Op.Set = AV.Op._extend(/** @lends AV.Op.Set.prototype */ {\n _initialize: function(value) {\n this._value = value;\n },\n\n /**\n * Returns the new value of this field after the set.\n */\n value: function() {\n return this._value;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return AV._encode(this.value());\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return this.value();\n }\n });\n\n /**\n * A sentinel value that is returned by AV.Op.Unset._estimate to\n * indicate the field should be deleted. Basically, if you find _UNSET as a\n * value in your object, you should remove that key.\n */\n AV.Op._UNSET = {};\n\n /**\n * @private\n * @class\n * An Unset operation indicates that this field has been deleted from the\n * object.\n */\n AV.Op.Unset = AV.Op._extend(/** @lends AV.Op.Unset.prototype */ {\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Delete\" };\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return AV.Op._UNSET;\n }\n });\n\n AV.Op._registerDecoder(\"Delete\", function(json) {\n return new AV.Op.Unset();\n });\n\n /**\n * @private\n * @class\n * An Increment is an atomic operation where the numeric value for the field\n * will be increased by a given amount.\n */\n AV.Op.Increment = AV.Op._extend(\n /** @lends AV.Op.Increment.prototype */ {\n\n _initialize: function(amount) {\n this._amount = amount;\n },\n\n /**\n * Returns the amount to increment by.\n * @return {Number} the amount to increment by.\n */\n amount: function() {\n return this._amount;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Increment\", amount: this._amount };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.amount());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(previous.value() + this.amount());\n } else if (previous instanceof AV.Op.Increment) {\n return new AV.Op.Increment(this.amount() + previous.amount());\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return this.amount();\n }\n return oldValue + this.amount();\n }\n });\n\n AV.Op._registerDecoder(\"Increment\", function(json) {\n return new AV.Op.Increment(json.amount);\n });\n\n /**\n * @private\n * @class\n * Add is an atomic operation where the given objects will be appended to the\n * array that is stored in this field.\n */\n AV.Op.Add = AV.Op._extend(/** @lends AV.Op.Add.prototype */ {\n _initialize: function(objects) {\n this._objects = objects;\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Add\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Add) {\n return new AV.Op.Add(previous.objects().concat(this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n return oldValue.concat(this.objects());\n }\n }\n });\n\n AV.Op._registerDecoder(\"Add\", function(json) {\n return new AV.Op.Add(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * AddUnique is an atomic operation where the given items will be appended to\n * the array that is stored in this field only if they were not already\n * present in the array.\n */\n AV.Op.AddUnique = AV.Op._extend(\n /** @lends AV.Op.AddUnique.prototype */ {\n\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"AddUnique\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.AddUnique) {\n return new AV.Op.AddUnique(this._estimate(previous.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n // We can't just take the _.uniq(_.union(...)) of oldValue and\n // this.objects, because the uniqueness may not apply to oldValue\n // (especially if the oldValue was set via .set())\n var newValue = _.clone(oldValue);\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n var matchingObj = _.find(newValue, function(anObj) {\n return (anObj instanceof AV.Object) && (anObj.id === obj.id);\n });\n if (!matchingObj) {\n newValue.push(obj);\n } else {\n var index = _.indexOf(newValue, matchingObj);\n newValue[index] = obj;\n }\n } else if (!_.contains(newValue, obj)) {\n newValue.push(obj);\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddUnique\", function(json) {\n return new AV.Op.AddUnique(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * Remove is an atomic operation where the given objects will be removed from\n * the array that is stored in this field.\n */\n AV.Op.Remove = AV.Op._extend(/** @lends AV.Op.Remove.prototype */ {\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be removed from the array.\n * @return {Array} The objects to be removed from the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Remove\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return previous;\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Remove) {\n return new AV.Op.Remove(_.union(previous.objects(), this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return [];\n } else {\n var newValue = _.difference(oldValue, this.objects());\n // If there are saved AV Objects being removed, also remove them.\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n newValue = _.reject(newValue, function(other) {\n return (other instanceof AV.Object) && (other.id === obj.id);\n });\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"Remove\", function(json) {\n return new AV.Op.Remove(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * A Relation operation indicates that the field is an instance of\n * AV.Relation, and objects are being added to, or removed from, that\n * relation.\n */\n AV.Op.Relation = AV.Op._extend(\n /** @lends AV.Op.Relation.prototype */ {\n\n _initialize: function(adds, removes) {\n this._targetClassName = null;\n\n var self = this;\n\n var pointerToId = function(object) {\n if (object instanceof AV.Object) {\n if (!object.id) {\n throw new Error('You can\\'t add an unsaved AV.Object to a relation.');\n }\n if (!self._targetClassName) {\n self._targetClassName = object.className;\n }\n if (self._targetClassName !== object.className) {\n throw new Error(\"Tried to create a AV.Relation with 2 different types: \" +\n self._targetClassName + \" and \" + object.className + \".\");\n }\n return object.id;\n }\n return object;\n };\n\n this.relationsToAdd = _.uniq(_.map(adds, pointerToId));\n this.relationsToRemove = _.uniq(_.map(removes, pointerToId));\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being added to the\n * relation.\n * @return {Array}\n */\n added: function() {\n var self = this;\n return _.map(this.relationsToAdd, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being removed from\n * the relation.\n * @return {Array}\n */\n removed: function() {\n var self = this;\n return _.map(this.relationsToRemove, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n var adds = null;\n var removes = null;\n var self = this;\n var idToPointer = function(id) {\n return { __type: 'Pointer',\n className: self._targetClassName,\n objectId: id };\n };\n var pointers = null;\n if (this.relationsToAdd.length > 0) {\n pointers = _.map(this.relationsToAdd, idToPointer);\n adds = { \"__op\": \"AddRelation\", \"objects\": pointers };\n }\n\n if (this.relationsToRemove.length > 0) {\n pointers = _.map(this.relationsToRemove, idToPointer);\n removes = { \"__op\": \"RemoveRelation\", \"objects\": pointers };\n }\n\n if (adds && removes) {\n return { \"__op\": \"Batch\", \"ops\": [adds, removes]};\n }\n\n return adds || removes || {};\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n throw new Error('You can\\'t modify a relation after deleting it.');\n } else if (previous instanceof AV.Op.Relation) {\n if (previous._targetClassName &&\n previous._targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be of class \" + previous._targetClassName +\n \", but \" + this._targetClassName + \" was passed in.\");\n }\n var newAdd = _.union(_.difference(previous.relationsToAdd,\n this.relationsToRemove),\n this.relationsToAdd);\n var newRemove = _.union(_.difference(previous.relationsToRemove,\n this.relationsToAdd),\n this.relationsToRemove);\n\n var newRelation = new AV.Op.Relation(newAdd, newRemove);\n newRelation._targetClassName = this._targetClassName;\n return newRelation;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue, object, key) {\n if (!oldValue) {\n var relation = new AV.Relation(object, key);\n relation.targetClassName = this._targetClassName;\n } else if (oldValue instanceof AV.Relation) {\n if (this._targetClassName) {\n if (oldValue.targetClassName) {\n if (oldValue.targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be a \" + oldValue.targetClassName +\n \", but a \" + this._targetClassName + \" was passed in.\");\n }\n } else {\n oldValue.targetClassName = this._targetClassName;\n }\n }\n return oldValue;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddRelation\", function(json) {\n return new AV.Op.Relation(AV._decode(json.objects), []);\n });\n AV.Op._registerDecoder(\"RemoveRelation\", function(json) {\n return new AV.Op.Relation([], AV._decode(json.objects));\n });\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/op.js","const AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n AV.Installation = AV.Object.extend(\"_Installation\");\n\n /**\n * @namespace\n */\n AV.Push = AV.Push || {};\n\n /**\n * Sends a push notification.\n * @param {Object} data The data of the push notification.\n * @param {String[]} [data.channels] An Array of channels to push to.\n * @param {Date} [data.push_time] A Date object for when to send the push.\n * @param {Date} [data.expiration_time] A Date object for when to expire\n * the push.\n * @param {Number} [data.expiration_interval] The seconds from now to expire the push.\n * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {Date} data.data The data to send as part of the push\n * @param {AuthOptions} [options]\n * @return {Promise}\n */\n AV.Push.send = function(data, options) {\n if (data.where) {\n data.where = data.where.toJSON().where;\n }\n\n if(data.where && data.cql){\n throw new Error(\"Both where and cql can't be set\");\n }\n\n if (data.push_time) {\n data.push_time = data.push_time.toJSON();\n }\n\n if (data.expiration_time) {\n data.expiration_time = data.expiration_time.toJSON();\n }\n\n if (data.expiration_time && data.expiration_time_interval) {\n throw new Error(\"Both expiration_time and expiration_time_interval can't be set\");\n }\n\n var request = AVRequest('push', null, null, 'POST', data, options);\n return request;\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/push.js","const _ = require('underscore');\nconst debug = require('debug')('leancloud:query');\nconst Promise = require('./promise');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst { ensureArray } = require('./utils');\n\nconst requires = (value, message) => {\n if (value === undefined) {\n throw new Error(message);\n }\n};\n\n// AV.Query is a way to create a list of AV.Objects.\nmodule.exports = function(AV) {\n /**\n * Creates a new AV.Query for the given AV.Object subclass.\n * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string.\n * @class\n *\n *

AV.Query defines a query that is used to fetch AV.Objects. The\n * most common use case is finding all objects that match a query through the\n * find method. For example, this sample code fetches all objects\n * of class MyClass. It calls a different function depending on\n * whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.find().then(function(results) {\n   *   // results is an array of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to retrieve a single object whose id is\n * known, through the get method. For example, this sample code fetches an\n * object of class MyClass and id myId. It calls a\n * different function depending on whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.get(myId).then(function(object) {\n   *   // object is an instance of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to count the number of objects that match\n * the query without retrieving all of those objects. For example, this\n * sample code counts the number of objects of the class MyClass\n *

\n   * var query = new AV.Query(MyClass);\n   * query.count().then(function(number) {\n   *   // There are number instances of MyClass.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n */\n AV.Query = function(objectClass) {\n if (_.isString(objectClass)) {\n objectClass = AV.Object._getSubclass(objectClass);\n }\n\n this.objectClass = objectClass;\n\n this.className = objectClass.prototype.className;\n\n this._where = {};\n this._include = [];\n this._select = [];\n this._limit = -1; // negative limit means, do not send a limit\n this._skip = 0;\n this._extraOptions = {};\n };\n\n /**\n * Constructs a AV.Query that is the OR of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.or(query1, query2, query3);
\n *\n * will create a compoundQuery that is an or of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to OR.\n * @return {AV.Query} The query that is the OR of the passed in queries.\n */\n AV.Query.or = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._orQuery(queries);\n return query;\n };\n\n /**\n * Constructs a AV.Query that is the AND of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.and(query1, query2, query3);
\n *\n * will create a compoundQuery that is an 'and' of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to AND.\n * @return {AV.Query} The query that is the AND of the passed in queries.\n */\n AV.Query.and = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._andQuery(queries);\n return query;\n };\n\n /**\n * Retrieves a list of AVObjects that satisfy the CQL.\n * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n *\n * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n * @param {Array} pvalues An array contains placeholder values.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n AV.Query.doCloudQuery = function(cql, pvalues, options) {\n var params = { cql: cql };\n if(_.isArray(pvalues)){\n params.pvalues = pvalues;\n } else {\n options = pvalues;\n }\n\n var request = AVRequest('cloudQuery', null, null, 'GET', params, options);\n return request.then(function(response) {\n //query to process results.\n var query = new AV.Query(response.className);\n var results = _.map(response.results, function(json) {\n var obj = query._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(query._processResult(json), true);\n }\n return obj;\n });\n return {\n results: results,\n count: response.count,\n className: response.className\n };\n });\n };\n\n AV.Query._extend = AV._extend;\n\n AV.Query.prototype = {\n //hook to iterate result. Added by dennis.\n _processResult: function(obj){\n return obj;\n },\n\n /**\n * Constructs an AV.Object whose id is already known by fetching data from\n * the server.\n *\n * @param {String} objectId The id of the object to be fetched.\n * @param {AuthOptions} options\n * @return {Promise.}\n */\n get: function(objectId, options) {\n if(!objectId) {\n var errorObject = new AVError(AVError.OBJECT_NOT_FOUND,\n \"Object not found.\");\n throw errorObject;\n }\n\n var self = this;\n\n var obj = self._newObject();\n obj.id = objectId;\n\n var queryJSON = self.toJSON();\n var fetchOptions = {};\n\n if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;\n if (queryJSON.include) fetchOptions.include = queryJSON.include;\n\n return obj.fetch(fetchOptions, options);\n },\n\n /**\n * Returns a JSON representation of this query.\n * @return {Object}\n */\n toJSON: function() {\n var params = {\n where: this._where\n };\n\n if (this._include.length > 0) {\n params.include = this._include.join(\",\");\n }\n if (this._select.length > 0) {\n params.keys = this._select.join(\",\");\n }\n if (this._limit >= 0) {\n params.limit = this._limit;\n }\n if (this._skip > 0) {\n params.skip = this._skip;\n }\n if (this._order !== undefined) {\n params.order = this._order;\n }\n\n AV._objectEach(this._extraOptions, function(v, k) {\n params[k] = v;\n });\n\n return params;\n },\n\n _newObject: function(response){\n var obj;\n if (response && response.className) {\n obj = new AV.Object(response.className);\n } else {\n obj = new this.objectClass();\n }\n return obj;\n },\n _createRequest(params = this.toJSON(), options) {\n if (JSON.stringify(params).length > 2000) {\n const body = {\n requests: [{\n method: 'GET',\n path: `/1.1/classes/${this.className}`,\n params,\n }],\n };\n return AVRequest('batch', null, null, 'POST', body, options)\n .then(response => {\n const result = response[0];\n if (result.success) {\n return result.success;\n }\n const error = new Error(result.error.error || 'Unknown batch error');\n error.code = result.error.code;\n throw error;\n });\n }\n return AVRequest('classes', this.className, null, \"GET\", params, options);\n },\n\n _parseResponse(response) {\n return _.map(response.results, (json) => {\n var obj = this._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(this._processResult(json), true);\n }\n return obj;\n });\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find(options) {\n const request = this._createRequest(undefined, options);\n return request.then(this._parseResponse.bind(this));\n },\n\n /**\n * scan a Query. masterKey required.\n *\n * @since 2.1.0\n * @param {object} [options]\n * @param {string} [options.orderedBy] specify the key to sort\n * @param {number} [options.batchSize] specify the batch size for each request\n * @param {AuthOptions} [authOptions]\n * @return {AsyncIterator.}\n * @example const scan = new AV.Query(TestClass).scan({\n * orderedBy: 'objectId',\n * batchSize: 10,\n * }, {\n * useMasterKey: true,\n * });\n * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next()));\n * getTen().then(results => {\n * // results are fisrt 10 instances of TestClass\n * return getTen();\n * }).then(results => {\n * // 11 - 20\n * });\n */\n scan({\n orderedBy,\n batchSize,\n } = {}, authOptions) {\n const condition = this.toJSON();\n debug('scan %O', condition);\n if (condition.order) {\n console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.');\n delete condition.order;\n }\n if (condition.skip) {\n console.warn('The skip option of the query is ignored for Query#scan.');\n delete condition.skip;\n }\n if (condition.limit) {\n console.warn('The limit option of the query is ignored for Query#scan.');\n delete condition.limit;\n }\n if (orderedBy) condition.scan_key = orderedBy;\n if (batchSize) condition.limit = batchSize;\n let promise = Promise.resolve([]);\n let cursor;\n let done = false;\n return {\n next: () => {\n promise = promise.then((remainResults) => {\n if (done) return [];\n if (remainResults.length > 1) return remainResults;\n // no cursor means we have reached the end\n // except for the first time\n if (!cursor && remainResults.length !== 0) {\n done = true;\n return remainResults;\n }\n // when only 1 item left in queue\n // start the next request to see if it is the last one\n return AVRequest(\n 'scan/classes',\n this.className,\n null,\n 'GET',\n cursor ? _.extend({}, condition, { cursor }) : condition,\n authOptions\n ).then(response => {\n cursor = response.cursor;\n return this._parseResponse(response);\n }).then(results => {\n if (!results.length) done = true;\n return remainResults.concat(results);\n });\n });\n return promise\n .then(remainResults => remainResults.shift())\n .then(result => ({\n value: result,\n done,\n }));\n },\n };\n },\n\n /**\n * Delete objects retrieved by this query.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n destroyAll: function(options){\n var self = this;\n return self.find(options).then(function(objects){\n return AV.Object.destroyAll(objects, options);\n });\n },\n\n /**\n * Counts the number of objects that match this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the count when\n * the query completes.\n */\n count: function(options) {\n var params = this.toJSON();\n params.limit = 0;\n params.count = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return response.count;\n });\n },\n\n /**\n * Retrieves at most one AV.Object that satisfies this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the object when\n * the query completes.\n */\n first: function(options) {\n var self = this;\n\n var params = this.toJSON();\n params.limit = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return _.map(response.results, function(json) {\n var obj = self._newObject();\n if (obj._finishFetch) {\n obj._finishFetch(self._processResult(json), true);\n }\n return obj;\n })[0];\n });\n },\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n requires(n, 'undefined is not a valid skip value');\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n requires(n, 'undefined is not a valid limit value');\n this._limit = n;\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that the AV.Object must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n equalTo: function(key, value) {\n requires(key, 'undefined is not a valid key');\n requires(value, 'undefined is not a valid value');\n this._where[key] = AV._encode(value);\n return this;\n },\n\n /**\n * Helper for condition queries\n * @private\n */\n _addCondition: function(key, condition, value) {\n requires(key, 'undefined is not a valid condition key');\n requires(condition, 'undefined is not a valid condition');\n requires(value, 'undefined is not a valid condition value');\n\n // Check if we already have a condition\n if (!this._where[key]) {\n this._where[key] = {};\n }\n this._where[key][condition] = AV._encode(value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular\n * array key's length to be equal to the provided value.\n * @param {String} key The array key to check.\n * @param value The length value.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n sizeEqualTo: function(key, value) {\n this._addCondition(key, \"$size\", value);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be not equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that must not be equalled.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notEqualTo: function(key, value) {\n this._addCondition(key, \"$ne\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThan: function(key, value) {\n this._addCondition(key, \"$lt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThan: function(key, value) {\n this._addCondition(key, \"$gt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$lte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$gte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containedIn: function(key, values) {\n this._addCondition(key, \"$in\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * not be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notContainedIn: function(key, values) {\n this._addCondition(key, \"$nin\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * contain each one of the provided list of values.\n * @param {String} key The key to check. This key's value must be an array.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containsAll: function(key, values) {\n this._addCondition(key, \"$all\", values);\n return this;\n },\n\n\n /**\n * Add a constraint for finding objects that contain the given key.\n * @param {String} key The key that should exist.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n exists: function(key) {\n this._addCondition(key, \"$exists\", true);\n return this;\n },\n\n /**\n * Add a constraint for finding objects that do not contain a given key.\n * @param {String} key The key that should not exist\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotExist: function(key) {\n this._addCondition(key, \"$exists\", false);\n return this;\n },\n\n /**\n * Add a regular expression constraint for finding string values that match\n * the provided regular expression.\n * This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {RegExp} regex The regular expression pattern to match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matches: function(key, regex, modifiers) {\n this._addCondition(key, \"$regex\", regex);\n if (!modifiers) { modifiers = \"\"; }\n // Javascript regex options support mig as inline options but store them\n // as properties of the object. We support mi & should migrate them to\n // modifiers\n if (regex.ignoreCase) { modifiers += 'i'; }\n if (regex.multiline) { modifiers += 'm'; }\n\n if (modifiers && modifiers.length) {\n this._addCondition(key, \"$options\", modifiers);\n }\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value matches a AV.Query\n * constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$inQuery\", queryJSON);\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not matches a\n * AV.Query constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$notInQuery\", queryJSON);\n return this;\n },\n\n\n /**\n * Add a constraint that requires that a key's value matches a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * matched.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$select\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not match a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * excluded.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$dontSelect\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add constraint that at least one of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _orQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$or = queryJSON;\n return this;\n },\n\n /**\n * Add constraint that both of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _andQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$and = queryJSON;\n return this;\n },\n\n\n /**\n * Converts a string into a regex that matches it.\n * Surrounding with \\Q .. \\E does this, we just need to escape \\E's in\n * the text separately.\n * @private\n */\n _quote: function(s) {\n return \"\\\\Q\" + s.replace(\"\\\\E\", \"\\\\E\\\\\\\\E\\\\Q\") + \"\\\\E\";\n },\n\n /**\n * Add a constraint for finding string values that contain a provided\n * string. This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} substring The substring that the value must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n contains: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that start with a provided\n * string. This query will use the backend index, so it will be fast even\n * for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} prefix The substring that the value must start with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n startsWith: function(key, value) {\n this._addCondition(key, \"$regex\", \"^\" + this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that end with a provided\n * string. This will be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} suffix The substring that the value must end with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n endsWith: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value) + \"$\");\n return this;\n },\n\n /**\n * Sorts the results in ascending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n ascending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = key;\n return this;\n },\n\n /**\n * Also sorts the results in ascending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addAscending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',' + key;\n else\n this._order = key;\n return this;\n },\n\n /**\n * Sorts the results in descending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n descending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = \"-\" + key;\n return this;\n },\n\n /**\n * Also sorts the results in descending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addDescending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',-' + key;\n else\n this._order = '-' + key;\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n near: function(key, point) {\n if (!(point instanceof AV.GeoPoint)) {\n // Try to cast it to a GeoPoint, so that near(\"loc\", [20,30]) works.\n point = new AV.GeoPoint(point);\n }\n this._addCondition(key, \"$nearSphere\", point);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param maxDistance Maximum distance (in radians) of results to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinRadians: function(key, point, distance) {\n this.near(key, point);\n this._addCondition(key, \"$maxDistance\", distance);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 3958.8 miles.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in miles) of results to\n * return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinMiles: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 3958.8);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 6371.0 kilometers.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in kilometers) of results\n * to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinKilometers: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 6371.0);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's\n * coordinates be contained within a given rectangular geographic bounding\n * box.\n * @param {String} key The key to be constrained.\n * @param {AV.GeoPoint} southwest\n * The lower-left inclusive corner of the box.\n * @param {AV.GeoPoint} northeast\n * The upper-right inclusive corner of the box.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinGeoBox: function(key, southwest, northeast) {\n if (!(southwest instanceof AV.GeoPoint)) {\n southwest = new AV.GeoPoint(southwest);\n }\n if (!(northeast instanceof AV.GeoPoint)) {\n northeast = new AV.GeoPoint(northeast);\n }\n this._addCondition(key, '$within', { '$box': [southwest, northeast] });\n return this;\n },\n\n /**\n * Include nested AV.Objects for the provided key. You can use dot\n * notation to specify which fields in the included object are also fetch.\n * @param {String[]} keys The name of the key to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n include: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._include = this._include.concat(ensureArray(keys))\n });\n return this;\n },\n\n /**\n * Restrict the fields of the returned AV.Objects to include only the\n * provided keys. If this is called multiple times, then all of the keys\n * specified in each of the calls will be included.\n * @param {String[]} keys The names of the keys to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n select: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._select = this._select.concat(ensureArray(keys));\n });\n return this;\n },\n\n /**\n * Iterates over each result of a query, calling a callback for each one. If\n * the callback returns a promise, the iteration will not continue until\n * that promise has been fulfilled. If the callback returns a rejected\n * promise, then iteration will stop with that error. The items are\n * processed in an unspecified order. The query may not have any sort order,\n * and may not use limit or skip.\n * @param callback {Function} Callback that will be called with each result\n * of the query.\n * @return {Promise} A promise that will be fulfilled once the\n * iteration has completed.\n */\n each: function(callback, options = {}) {\n\n if (this._order || this._skip || (this._limit >= 0)) {\n var error =\n new Error(\"Cannot iterate on a query with sort, skip, or limit.\");\n return AV.Promise.reject(error);\n }\n\n var query = new AV.Query(this.objectClass);\n // We can override the batch size from the options.\n // This is undocumented, but useful for testing.\n query._limit = options.batchSize || 100;\n query._where = _.clone(this._where);\n query._include = _.clone(this._include);\n\n query.ascending('objectId');\n\n var finished = false;\n return AV.Promise._continueWhile(function() {\n return !finished;\n\n }, function() {\n return query.find(options).then(function(results) {\n var callbacksDone = AV.Promise.resolve();\n _.each(results, function(result) {\n callbacksDone = callbacksDone.then(function() {\n return callback(result);\n });\n });\n\n return callbacksDone.then(function() {\n if (results.length >= query._limit) {\n query.greaterThan(\"objectId\", results[results.length - 1].id);\n } else {\n finished = true;\n }\n });\n });\n });\n }\n };\n\n AV.FriendShipQuery = AV.Query._extend({\n _objectClass: AV.User,\n _newObject: function(){\n return new AV.User();\n },\n _processResult: function(json){\n if(json && json[this._friendshipTag]) {\n var user = json[this._friendshipTag];\n if(user.__type === 'Pointer' && user.className === '_User'){\n delete user.__type;\n delete user.className;\n }\n return user;\n } else {\n return null;\n }\n },\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/query.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n /**\n * Creates a new Relation for the given parent object and key. This\n * constructor should rarely be used directly, but rather created by\n * {@link AV.Object#relation}.\n * @param {AV.Object} parent The parent of this relation.\n * @param {String} key The key for this relation on the parent.\n * @see AV.Object#relation\n * @class\n *\n *

\n * A class that is used to access all of the children of a many-to-many\n * relationship. Each instance of AV.Relation is associated with a\n * particular parent object and key.\n *

\n */\n AV.Relation = function(parent, key) {\n if (! _.isString(key)) {\n throw new TypeError('key must be a string');\n }\n this.parent = parent;\n this.key = key;\n this.targetClassName = null;\n };\n\n /**\n * Creates a query that can be used to query the parent objects in this relation.\n * @param {String} parentClass The parent class or name.\n * @param {String} relationKey The relation field key in parent.\n * @param {AV.Object} child The child object.\n * @return {AV.Query}\n */\n AV.Relation.reverseQuery = function(parentClass, relationKey, child){\n var query = new AV.Query(parentClass);\n query.equalTo(relationKey, child._toPointer());\n return query;\n };\n\n AV.Relation.prototype = {\n /**\n * Makes sure that this relation has the right parent and key.\n * @private\n */\n _ensureParentAndKey: function(parent, key) {\n this.parent = this.parent || parent;\n this.key = this.key || key;\n if (this.parent !== parent) {\n throw new Error(\"Internal Error. Relation retrieved from two different Objects.\");\n }\n if (this.key !== key) {\n throw new Error(\"Internal Error. Relation retrieved from two different keys.\");\n }\n },\n\n /**\n * Adds a AV.Object or an array of AV.Objects to the relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to add.\n */\n add: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation(objects, []);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Removes a AV.Object or an array of AV.Objects from this relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to remove.\n */\n remove: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation([], objects);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Returns a JSON version of the object suitable for saving to disk.\n * @return {Object}\n */\n toJSON: function() {\n return { \"__type\": \"Relation\", \"className\": this.targetClassName };\n },\n\n /**\n * Returns a AV.Query that is limited to objects in this\n * relation.\n * @return {AV.Query}\n */\n query: function() {\n var targetClass;\n var query;\n if (!this.targetClassName) {\n targetClass = AV.Object._getSubclass(this.parent.className);\n query = new AV.Query(targetClass);\n query._extraOptions.redirectClassNameForKey = this.key;\n } else {\n targetClass = AV.Object._getSubclass(this.targetClassName);\n query = new AV.Query(targetClass);\n }\n query._addCondition(\"$relatedTo\", \"object\", this.parent._toPointer());\n query._addCondition(\"$relatedTo\", \"key\", this.key);\n\n return query;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/relation.js","const _ = require('underscore');\nconst AVError = require('./error');\n\nmodule.exports = function(AV) {\n AV.Role = AV.Object.extend(\"_Role\", /** @lends AV.Role.prototype */ {\n // Instance Methods\n\n /**\n * Represents a Role on the AV server. Roles represent groupings of\n * Users for the purposes of granting permissions (e.g. specifying an ACL\n * for an Object). Roles are specified by their sets of child users and\n * child roles, all of which are granted any permissions that the parent\n * role has.\n *\n *

Roles must have a name (which cannot be changed after creation of the\n * role), and must specify an ACL.

\n * An AV.Role is a local representation of a role persisted to the AV\n * cloud.\n * @class AV.Role\n * @param {String} name The name of the Role to create.\n * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL\n * `{'*': { read: true }}` will be used.\n */\n constructor: function(name, acl, noDefaultACL) {\n if (_.isString(name)) {\n AV.Object.prototype.constructor.call(this, null, null);\n this.setName(name);\n } else {\n AV.Object.prototype.constructor.call(this, name, acl);\n }\n if (acl === undefined) {\n if (!noDefaultACL) {\n if(!this.getACL()) {\n console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.');\n var defaultAcl = new AV.ACL();\n defaultAcl.setPublicReadAccess(true); \n this.setACL(defaultAcl);\n }\n }\n } else if (!(acl instanceof AV.ACL)) {\n throw new TypeError('acl must be an instance of AV.ACL');\n } else {\n this.setACL(acl);\n }\n },\n\n /**\n * Gets the name of the role. You can alternatively call role.get(\"name\")\n *\n * @return {String} the name of the role.\n */\n getName: function() {\n return this.get(\"name\");\n },\n\n /**\n * Sets the name for a role. This value must be set before the role has\n * been saved to the server, and cannot be set once the role has been\n * saved.\n *\n *

\n * A role's name can only contain alphanumeric characters, _, -, and\n * spaces.\n *

\n *\n *

This is equivalent to calling role.set(\"name\", name)

\n *\n * @param {String} name The name of the role.\n */\n setName: function(name, options) {\n return this.set(\"name\", name, options);\n },\n\n /**\n * Gets the AV.Relation for the AV.Users that are direct\n * children of this role. These users are granted any privileges that this\n * role has been granted (e.g. read or write access through ACLs). You can\n * add or remove users from the role through this relation.\n *\n *

This is equivalent to calling role.relation(\"users\")

\n *\n * @return {AV.Relation} the relation for the users belonging to this\n * role.\n */\n getUsers: function() {\n return this.relation(\"users\");\n },\n\n /**\n * Gets the AV.Relation for the AV.Roles that are direct\n * children of this role. These roles' users are granted any privileges that\n * this role has been granted (e.g. read or write access through ACLs). You\n * can add or remove child roles from this role through this relation.\n *\n *

This is equivalent to calling role.relation(\"roles\")

\n *\n * @return {AV.Relation} the relation for the roles belonging to this\n * role.\n */\n getRoles: function() {\n return this.relation(\"roles\");\n },\n\n /**\n * @ignore\n */\n validate: function(attrs, options) {\n if (\"name\" in attrs && attrs.name !== this.getName()) {\n var newName = attrs.name;\n if (this.id && this.id !== attrs.objectId) {\n // Check to see if the objectId being set matches this.id.\n // This happens during a fetch -- the id is set before calling fetch.\n // Let the name be set in this case.\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only be set before it has been saved.\");\n }\n if (!_.isString(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name must be a String.\");\n }\n if (!(/^[0-9a-zA-Z\\-_ ]+$/).test(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only contain alphanumeric characters, _,\" +\n \" -, and spaces.\");\n }\n }\n if (AV.Object.prototype.validate) {\n return AV.Object.prototype.validate.call(this, attrs, options);\n }\n return false;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/role.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * A builder to generate sort string for app searching.For example:\n * @class\n * @since 0.5.1\n * @example\n * var builder = new AV.SearchSortBuilder();\n * builder.ascending('key1').descending('key2','max');\n * var query = new AV.SearchQuery('Player');\n * query.sortBy(builder);\n * query.find().then();\n */\n AV.SearchSortBuilder = function() {\n this._sortFields = [];\n };\n\n AV.SearchSortBuilder.prototype = {\n _addField: function(key, order, mode, missing) {\n var field = {};\n field[key] = {\n order: order || 'asc',\n mode: mode ||'avg',\n missing: '_' + (missing || 'last')\n };\n this._sortFields.push(field);\n return this;\n },\n\n\n /**\n * Sorts the results in ascending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n ascending: function(key, mode, missing) {\n return this._addField(key, 'asc', mode, missing);\n },\n\n /**\n * Sorts the results in descending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n descending: function(key, mode, missing) {\n return this._addField(key, 'desc', mode, missing);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Object} options The other options such as mode,order, unit etc.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n whereNear: function(key, point, options) {\n options = options || {};\n var field = {};\n var geo = {\n lat: point.latitude,\n lon: point.longitude\n };\n var m = {\n order: options.order || 'asc',\n mode: options.mode || 'avg',\n unit: options.unit || 'km'\n };\n m[key] = geo;\n field['_geo_distance'] = m;\n\n this._sortFields.push(field);\n return this;\n },\n\n /**\n * Build a sort string by configuration.\n * @return {String} the sort string.\n */\n build: function() {\n return JSON.stringify(AV._encode(this._sortFields));\n }\n };\n\n /**\n * App searching query.Use just like AV.Query:\n *\n * Visit App Searching Guide\n * for more details.\n * @class\n * @since 0.5.1\n * @example\n * var query = new AV.SearchQuery('Player');\n * query.queryString('*');\n * query.find().then(function(results) {\n * console.log('Found %d objects', query.hits());\n * //Process results\n * });\n */\n AV.SearchQuery = AV.Query._extend(/** @lends AV.SearchQuery.prototype */{\n _sid: null,\n _hits: 0,\n _queryString: null,\n _highlights: null,\n _sortBuilder: null,\n _createRequest: function(params, options){\n return AVRequest('search/select', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n /**\n * Sets the sid of app searching query.Default is null.\n * @param {String} sid Scroll id for searching.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n sid: function(sid) {\n this._sid = sid;\n return this;\n },\n\n /**\n * Sets the query string of app searching.\n * @param {String} q The query string.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n queryString: function(q) {\n this._queryString = q;\n return this;\n },\n\n\n /**\n * Sets the highlight fields. Such as\n *
\n     *   query.highlights('title');\n     *   //or pass an array.\n     *   query.highlights(['title', 'content'])\n     * 
\n * @param {String[]} highlights a list of fields.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n highlights: function(highlights) {\n var objects;\n if (highlights && _.isString(highlights)) {\n objects = arguments;\n } else {\n objects = highlights;\n }\n this._highlights = objects;\n return this;\n },\n\n /**\n * Sets the sort builder for this query.\n * @see AV.SearchSortBuilder\n * @param { AV.SearchSortBuilder} builder The sort builder.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n *\n */\n sortBy: function(builder) {\n this._sortBuilder = builder;\n return this;\n },\n\n /**\n * Returns the number of objects that match this query.\n * @return {Number}\n */\n hits: function() {\n if (!this._hits) {\n this._hits = 0;\n }\n return this._hits;\n },\n\n _processResult: function(json){\n delete json['className'];\n delete json['_app_url'];\n delete json['_deeplink'];\n return json;\n },\n\n /**\n * Returns true when there are more documents can be retrieved by this\n * query instance, you can call find function to get more results.\n * @see AV.SearchQuery#find\n * @return {Boolean}\n */\n hasMore: function() {\n return !this._hitEnd;\n },\n\n /**\n * Reset current query instance state(such as sid, hits etc) except params\n * for a new searching. After resetting, hasMore() will return true.\n */\n reset: function() {\n this._hitEnd = false;\n this._sid = null;\n this._hits = 0;\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n * Either options.success or options.error is called when the find\n * completes.\n *\n * @see AV.Query#find\n * @return {AV.Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find: function() {\n var self = this;\n\n var request = this._createRequest();\n\n return request.then(function(response) {\n //update sid for next querying.\n if(response.sid) {\n self._oldSid = self._sid;\n self._sid = response.sid;\n } else {\n self._sid = null;\n self._hitEnd = true;\n }\n self._hits = response.hits || 0;\n\n return _.map(response.results, function(json) {\n if(json.className) {\n response.className = json.className;\n }\n var obj = self._newObject(response);\n obj.appURL = json['_app_url'];\n obj._finishFetch(self._processResult(json), true);\n return obj;\n });\n });\n },\n\n toJSON: function(){\n var params = AV.SearchQuery.__super__.toJSON.call(this);\n delete params.where;\n if(this.className) {\n params.clazz = this.className;\n }\n if(this._sid) {\n params.sid = this._sid;\n }\n if(!this._queryString) {\n throw new Error('Please set query string.');\n } else {\n params.q = this._queryString;\n }\n if(this._highlights) {\n params.highlights = this._highlights.join(',');\n }\n if(this._sortBuilder && params.order) {\n throw new Error('sort and order can not be set at same time.');\n }\n if(this._sortBuilder) {\n params.sort = this._sortBuilder.build();\n }\n\n return params;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/search.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n const getUser = (options = {}) => AV.User.currentAsync()\n .then(currUser => currUser || AV.User._fetchUserBySessionToken(options.sessionToken));\n\n const getUserPointer = options => getUser(options)\n .then(currUser => AV.Object.createWithoutData('_User', currUser.id)._toPointer());\n\n /**\n * Contains functions to deal with Status in LeanCloud.\n * @class\n */\n AV.Status = function(imageUrl, message) {\n this.data = {};\n this.inboxType = 'default';\n this.query = null;\n if(imageUrl && typeof imageUrl === 'object') {\n this.data = imageUrl;\n } else {\n if(imageUrl){\n this.data.image = imageUrl;\n }\n if(message){\n this.data.message = message;\n }\n }\n return this;\n };\n\n AV.Status.prototype = {\n /**\n * Gets the value of an attribute in status data.\n * @param {String} attr The string name of an attribute.\n */\n get: function(attr){\n return this.data[attr];\n },\n /**\n * Sets a hash of model attributes on the status data.\n * @param {String} key The key to set.\n * @param {} value The value to give it.\n */\n set: function(key, value){\n this.data[key] = value;\n return this;\n },\n /**\n * Destroy this status,then it will not be avaiable in other user's inboxes.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options){\n if(!this.id)\n return AV.Promise.reject(new Error('The status id is not exists.'));\n var request = AVRequest('statuses', null, this.id, 'DELETE', options);\n return request;\n },\n /**\n * Cast the AV.Status object to an AV.Object pointer.\n * @return {AV.Object} A AV.Object pointer.\n */\n toObject: function(){\n if(!this.id)\n return null;\n return AV.Object.createWithoutData('_Status', this.id);\n },\n _getDataJSON: function() {\n var json = _.clone(this.data);\n return AV._encode(json);\n },\n /**\n * Send a status by a AV.Query object.\n * @since 0.3.0\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a status to male users\n * var status = new AVStatus('image url', 'a message');\n * status.query = new AV.Query('_User');\n * status.query.equalTo('gender', 'male');\n * status.send().then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n send: function(options = {}){\n if(!options.sessionToken && !AV.User.current()) {\n throw new Error('Please signin an user.');\n }\n if(!this.query){\n return AV.Status.sendStatusToFollowers(this, options);\n }\n\n return getUserPointer(options).then(currUser => {\n var query = this.query.toJSON();\n query.className = this.query.className;\n var data = {};\n data.query = query;\n this.data = this.data || {};\n this.data.source = this.data.source || currUser;\n data.data = this._getDataJSON();\n data.inboxType = this.inboxType || 'default';\n\n return AVRequest('statuses', null, null, 'POST', data, options);\n })\n .then((response) => {\n this.id = response.objectId;\n this.createdAt = AV._parseDate(response.createdAt);\n return this;\n });\n },\n\n _finishFetch: function(serverData){\n this.id = serverData.objectId;\n this.createdAt = AV._parseDate(serverData.createdAt);\n this.updatedAt = AV._parseDate(serverData.updatedAt);\n this.messageId = serverData.messageId;\n delete serverData.messageId;\n delete serverData.objectId;\n delete serverData.createdAt;\n delete serverData.updatedAt;\n this.data = AV._decode(serverData);\n }\n };\n\n /**\n * Send a status to current signined user's followers.\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendStatusToFollowers(status).then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendStatusToFollowers = function(status, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_Follower';\n query.keys = 'follower';\n query.where = {user: currUser};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = status.inboxType || 'default';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n *

Send a status from current signined user to other user's private status inbox.

\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {String} target The target user or user's objectId.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a private status to user '52e84e47e4b0f8de283b079b'\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendPrivateStatus = function(status, target, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n if(!target){\n throw new Error(\"Invalid target user.\");\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error(\"Invalid target user.\");\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_User';\n query.where = {objectId: userObjectId};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = 'private';\n status.inboxType = 'private';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n * Count unread statuses in someone's inbox.\n * @since 0.3.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the count\n * completes.\n * @example\n * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.countUnreadStatuses = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options);\n });\n };\n\n /**\n * reset unread statuses count in someone's inbox.\n * @since 2.1.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the reset\n * completes.\n * @example\n * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.resetUnreadCount = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options);\n });\n };\n\n /**\n * Create a status query to find someone's published statuses.\n * @since 0.3.0\n * @param {Object} source The status source.\n * @return {AV.Query} The query object for status.\n * @example\n * //Find current user's published statuses.\n * var query = AV.Status.statusQuery(AV.User.current());\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.statusQuery = function(source){\n var query = new AV.Query('_Status');\n if(source){\n query.equalTo('source', source);\n }\n return query;\n };\n\n /**\n *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

\n * @class\n */\n AV.InboxQuery = AV.Query._extend(/** @lends AV.InboxQuery.prototype */{\n _objectClass: AV.Status,\n _sinceId: 0,\n _maxId: 0,\n _inboxType: 'default',\n _owner: null,\n _newObject: function(){\n return new AV.Status();\n },\n _createRequest: function(params, options){\n return AVRequest('subscribe/statuses', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n\n /**\n * Sets the messageId of results to skip before returning any results.\n * This is useful for pagination.\n * Default is zero.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n sinceId: function(id){\n this._sinceId = id;\n return this;\n },\n /**\n * Sets the maximal messageId of results。\n * This is useful for pagination.\n * Default is zero that is no limition.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n maxId: function(id){\n this._maxId = id;\n return this;\n },\n /**\n * Sets the owner of the querying inbox.\n * @param {Object} owner The inbox owner.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n owner: function(owner){\n this._owner = owner;\n return this;\n },\n /**\n * Sets the querying inbox type.default is 'default'.\n * @param {Object} owner The inbox type.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n inboxType: function(type){\n this._inboxType = type;\n return this;\n },\n toJSON: function(){\n var params = AV.InboxQuery.__super__.toJSON.call(this);\n params.owner = AV._encode(this._owner);\n params.inboxType = AV._encode(this._inboxType);\n params.sinceId = AV._encode(this._sinceId);\n params.maxId = AV._encode(this._maxId);\n return params;\n }\n });\n\n /**\n * Create a inbox status query to find someone's inbox statuses.\n * @since 0.3.0\n * @param {Object} owner The inbox's owner\n * @param {String} inboxType The inbox type,'default' by default.\n * @return {AV.InboxQuery} The inbox query object.\n * @see AV.InboxQuery\n * @example\n * //Find current user's default inbox statuses.\n * var query = AV.Status.inboxQuery(AV.User.current());\n * //find the statuses after the last message id\n * query.sinceId(lastMessageId);\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.inboxQuery = function(owner, inboxType){\n var query = new AV.InboxQuery(AV.Status);\n if(owner){\n query._owner = owner;\n }\n if(inboxType){\n query._inboxType = inboxType;\n }\n return query;\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/status.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\n\nconst getWeappLoginCode = () => {\n if (typeof wx === 'undefined' || typeof wx.login !== 'function') {\n throw new Error('Weapp Login is only available in Weapp');\n }\n return new Promise((resolve, reject) => {\n wx.login({\n success: ({ code, errMsg }) => {\n if (code) {\n resolve(code);\n } else {\n reject(new Error(errMsg));\n }\n },\n });\n });\n};\n\nmodule.exports = function(AV) {\n /**\n * @class\n *\n *

An AV.User object is a local representation of a user persisted to the\n * LeanCloud server. This class is a subclass of an AV.Object, and retains the\n * same functionality of an AV.Object, but also extends it with various\n * user specific methods, like authentication, signing up, and validation of\n * uniqueness.

\n */\n AV.User = AV.Object.extend(\"_User\", /** @lends AV.User.prototype */ {\n // Instance Variables\n _isCurrentUser: false,\n\n\n // Instance Methods\n\n /**\n * Internal method to handle special fields in a _User response.\n * @private\n */\n _mergeMagicFields: function(attrs) {\n if (attrs.sessionToken) {\n this._sessionToken = attrs.sessionToken;\n delete attrs.sessionToken;\n }\n AV.User.__super__._mergeMagicFields.call(this, attrs);\n },\n\n /**\n * Removes null values from authData (which exist temporarily for\n * unlinking)\n * @private\n */\n _cleanupAuthData: function() {\n if (!this.isCurrent()) {\n return;\n }\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n AV._objectEach(this.get('authData'), function(value, key) {\n if (!authData[key]) {\n delete authData[key];\n }\n });\n },\n\n /**\n * Synchronizes authData for all providers.\n * @private\n */\n _synchronizeAllAuthData: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._synchronizeAuthData(key);\n });\n },\n\n /**\n * Synchronizes auth data for a provider (e.g. puts the access token in the\n * right place to be used by the Facebook SDK).\n * @private\n */\n _synchronizeAuthData: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[authType];\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData');\n if (!authData || !provider) {\n return;\n }\n var success = provider.restoreAuthentication(authData[authType]);\n if (!success) {\n this._unlinkFrom(provider);\n }\n },\n\n _handleSaveResult: function(makeCurrent) {\n // Clean up and synchronize the authData object, removing any unset values\n if (makeCurrent && !AV._config.disableCurrentUser) {\n this._isCurrentUser = true;\n }\n this._cleanupAuthData();\n this._synchronizeAllAuthData();\n // Don't keep the password around.\n delete this._serverData.password;\n this._rebuildEstimatedDataForKey(\"password\");\n this._refreshCache();\n if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) {\n // Some old version of leanengine-node-sdk will overwrite\n // AV.User._saveCurrentUser which returns no Promise.\n // So we need a Promise wrapper.\n return Promise.resolve(AV.User._saveCurrentUser(this));\n } else {\n return Promise.resolve();\n }\n },\n\n /**\n * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can\n * call linkWith on the user (even if it doesn't exist yet on the server).\n * @private\n */\n _linkWith: function(provider, data) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[provider];\n } else {\n authType = provider.getAuthType();\n }\n if (data) {\n var authData = this.get('authData') || {};\n authData[authType] = data;\n return this.save({ authData })\n .then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n } else {\n return provider.authenticate().then(result => this._linkWith(provider, result));\n }\n },\n\n /**\n * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。\n * 仅在小程序中可用。\n *\n * @return {AV.User}\n */\n linkWithWeapp() {\n return getWeappLoginCode().then(code => this._linkWith('lc_weapp', { code }));\n },\n\n /**\n * Unlinks a user from a service.\n * @private\n */\n _unlinkFrom: function(provider) {\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n return this._linkWith(provider, null).then(model => {\n this._synchronizeAuthData(provider);\n return model;\n });\n },\n\n /**\n * Checks whether a user is linked to a service.\n * @private\n */\n _isLinked: function(provider) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData') || {};\n return !!authData[authType];\n },\n\n logOut: function() {\n this._logOutWithAll();\n this._isCurrentUser = false;\n },\n\n /**\n * Deauthenticates all providers.\n * @private\n */\n _logOutWithAll: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._logOutWith(key);\n });\n },\n\n /**\n * Deauthenticates a single provider (e.g. removing access tokens from the\n * Facebook SDK).\n * @private\n */\n _logOutWith: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n if (provider && provider.deauthenticate) {\n provider.deauthenticate();\n }\n },\n\n /**\n * Signs up a new user. You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUp\n */\n signUp: function(attrs, options) {\n var error;\n\n var username = (attrs && attrs.username) || this.get(\"username\");\n if (!username || (username === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty name.\");\n throw error;\n }\n\n var password = (attrs && attrs.password) || this.get(\"password\");\n if (!password || (password === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty password.\");\n throw error;\n }\n\n return this.save(attrs, options).then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Signs up a new user with mobile phone and sms code.\n * You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(attrs, options = {}) {\n var error;\n\n var mobilePhoneNumber = (attrs && attrs.mobilePhoneNumber) ||\n this.get(\"mobilePhoneNumber\");\n if (!mobilePhoneNumber || (mobilePhoneNumber === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty mobilePhoneNumber.\");\n throw error;\n }\n\n var smsCode = (attrs && attrs.smsCode) || this.get(\"smsCode\");\n if (!smsCode || (smsCode === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty smsCode.\");\n throw error;\n }\n\n options._makeRequest = function(route, className, id, method, json) {\n return AVRequest('usersByMobilePhone', null, null, \"POST\", json);\n };\n return this.save(attrs, options).then(function(model) {\n delete model.attributes.smsCode;\n delete model._serverData.smsCode;\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Logs in a AV.User. On success, this saves the session to localStorage,\n * so you can retrieve the currently logged in user using\n * current.\n *\n *

A username and password must be set before calling logIn.

\n *\n * @see AV.User.logIn\n * @return {Promise} A promise that is fulfilled with the user when\n * the login is complete.\n */\n logIn: function() {\n var model = this;\n var request = AVRequest('login', null, null, 'POST', this.toJSON());\n return request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n model._finishFetch(serverAttrs);\n return model._handleSaveResult(true).then(function() {\n if(!serverAttrs.smsCode)\n delete model.attributes['smsCode'];\n return model;\n });\n });\n },\n /**\n * @see AV.Object#save\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n options = options || {};\n\n return AV.Object.prototype.save\n .call(this, attrs, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Follow a user\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to follow.\n * @param {AuthOptions} options\n */\n follow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'POST', null, options);\n return request;\n },\n\n /**\n * Unfollow a user.\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to unfollow.\n * @param {AuthOptions} options\n */\n unfollow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'DELETE', null, options);\n return request;\n },\n\n /**\n *Create a follower query to query the user's followers.\n * @since 0.3.0\n * @see AV.User#followerQuery\n */\n followerQuery: function() {\n return AV.User.followerQuery(this.id);\n },\n\n /**\n *Create a followee query to query the user's followees.\n * @since 0.3.0\n * @see AV.User#followeeQuery\n */\n followeeQuery: function() {\n return AV.User.followeeQuery(this.id);\n },\n\n /**\n * @see AV.Object#fetch\n */\n fetch: function(fetchOptions, options) {\n return AV.Object.prototype.fetch.call(this, fetchOptions, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Update user's new password safely based on old password.\n * @param {String} oldPassword the old password.\n * @param {String} newPassword the new password.\n * @param {AuthOptions} options\n */\n updatePassword: function(oldPassword, newPassword, options) {\n var route = 'users/' + this.id + '/updatePassword';\n var params = {\n old_password: oldPassword,\n new_password: newPassword\n };\n var request = AVRequest(route, null, null, 'PUT', params, options);\n return request;\n },\n\n /**\n * Returns true if current would return this user.\n * @see AV.User#current\n */\n isCurrent: function() {\n return this._isCurrentUser;\n },\n\n /**\n * Returns get(\"username\").\n * @return {String}\n * @see AV.Object#get\n */\n getUsername: function() {\n return this.get(\"username\");\n },\n\n /**\n * Returns get(\"mobilePhoneNumber\").\n * @return {String}\n * @see AV.Object#get\n */\n getMobilePhoneNumber: function(){\n return this.get(\"mobilePhoneNumber\");\n },\n\n /**\n * Calls set(\"mobilePhoneNumber\", phoneNumber, options) and returns the result.\n * @param {String} mobilePhoneNumber\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setMobilePhoneNumber: function(phone, options) {\n return this.set(\"mobilePhoneNumber\", phone, options);\n },\n\n /**\n * Calls set(\"username\", username, options) and returns the result.\n * @param {String} username\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setUsername: function(username, options) {\n return this.set(\"username\", username, options);\n },\n\n /**\n * Calls set(\"password\", password, options) and returns the result.\n * @param {String} password\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setPassword: function(password, options) {\n return this.set(\"password\", password, options);\n },\n\n /**\n * Returns get(\"email\").\n * @return {String}\n * @see AV.Object#get\n */\n getEmail: function() {\n return this.get(\"email\");\n },\n\n /**\n * Calls set(\"email\", email, options) and returns the result.\n * @param {String} email\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setEmail: function(email, options) {\n return this.set(\"email\", email, options);\n },\n\n /**\n * Checks whether this user is the current user and has been authenticated.\n * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),\n * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id\n * @return (Boolean) whether this user is the current user and is logged in.\n */\n authenticated: function() {\n console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。')\n return !!this._sessionToken &&\n (!AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id);\n },\n\n /**\n * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。\n *\n * @since 2.0.0\n * @return Promise.\n */\n isAuthenticated() {\n return Promise.resolve().then(() =>\n !!this._sessionToken &&\n AV.User._fetchUserBySessionToken(this._sessionToken).then(\n () => true,\n (error) => {\n if (error.code === 211) {\n return false;\n }\n throw error;\n }\n )\n );\n },\n\n /**\n * Get sessionToken of current user.\n * @return {String} sessionToken\n */\n getSessionToken() {\n return this._sessionToken;\n },\n\n /**\n * Refresh sessionToken of current user.\n * @since 2.1.0\n * @param {AuthOptions} [options]\n * @return {Promise.} user with refreshed sessionToken\n */\n refreshSessionToken(options) {\n return AVRequest(`users/${this.id}/refreshSessionToken`, null, null, 'PUT', null, options)\n .then(response => {\n this._finishFetch(response);\n return this._handleSaveResult(true).then(() => this);\n });\n },\n\n /**\n * Get this user's Roles.\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that is fulfilled with the roles when\n * the query is complete.\n */\n getRoles(options) {\n return AV.Relation.reverseQuery(\"_Role\", \"users\", this).find(options);\n },\n\n }, /** @lends AV.User */ {\n // Class Variables\n\n // The currently logged-in user.\n _currentUser: null,\n\n // Whether currentUser is known to match the serialized version on disk.\n // This is useful for saving a localstorage check if you try to load\n // _currentUser frequently while there is none stored.\n _currentUserMatchesDisk: false,\n\n // The localStorage key suffix that the current user is stored under.\n _CURRENT_USER_KEY: \"currentUser\",\n\n // The mapping of auth provider names to actual providers\n _authProviders: {},\n\n // Class Methods\n\n /**\n * Signs up a new user with a username (or email) and password.\n * This will create a new AV.User on the server, and also persist the\n * session in localStorage so that you can access the user using\n * {@link #current}.\n *\n * @param {String} username The username (or email) to sign up with.\n * @param {String} password The password to sign up with.\n * @param {Object} attrs Extra fields to set on the new user.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the signup completes.\n * @see AV.User#signUp\n */\n signUp: function(username, password, attrs, options) {\n attrs = attrs || {};\n attrs.username = username;\n attrs.password = password;\n var user = AV.Object._create(\"_User\");\n return user.signUp(attrs, options);\n },\n\n /**\n * Logs in a user with a username (or email) and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} username The username (or email) to log in with.\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logIn: function(username, password, options) {\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ username: username, password: password });\n return user.logIn(options);\n },\n\n /**\n * Logs in a user with a session token. On success, this saves the session\n * to disk, so you can retrieve the currently logged in user using\n * current.\n *\n * @param {String} sessionToken The sessionToken to log in with.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n */\n become: function(sessionToken) {\n return this._fetchUserBySessionToken(sessionToken).then(user =>\n user._handleSaveResult(true).then(() => user)\n );\n },\n\n _fetchUserBySessionToken: function(sessionToken) {\n var user = AV.Object._create(\"_User\");\n return AVRequest(\n \"users\",\n \"me\",\n null,\n \"GET\", {\n session_token: sessionToken\n }\n ).then(function(resp) {\n var serverAttrs = user.parse(resp);\n user._finishFetch(serverAttrs);\n return user;\n });\n },\n\n /**\n * Logs in a user with a mobile phone number and sms code sent by\n * AV.User.requestLoginSmsCode.On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhoneSmsCode: function(mobilePhone, smsCode, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a mobilePhoneNumber and smsCode.\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {String} mobilePhoneNumber The user's mobilePhoneNumber.\n * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode\n * @param {Object} attributes The user's other attributes such as username etc.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(mobilePhoneNumber, smsCode, attrs, options) {\n attrs = attrs || {};\n attrs.mobilePhoneNumber = mobilePhoneNumber;\n attrs.smsCode = smsCode;\n var user = AV.Object._create(\"_User\");\n return user.signUpOrlogInWithMobilePhone(attrs, options);\n },\n\n\n /**\n * Logs in a user with a mobile phone number and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhone: function(mobilePhone, password, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a third party auth data(AccessToken).\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @param {string} platform Available platform for sign up.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户}\n */\n signUpOrlogInWithAuthData(authData, platform) {\n return AV.User._logInWith(platform, authData);\n },\n\n /**\n * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。\n * 仅在小程序中可用。\n *\n * @since 2.0.0\n * @return {AV.User}\n */\n loginWithWeapp() {\n return getWeappLoginCode().then(code => this.signUpOrlogInWithAuthData({ code }, 'lc_weapp'));\n },\n\n /**\n * Associate a user with a third party auth data(AccessToken).\n *\n * @param {AV.User} userObj A user which you want to associate.\n * @param {string} platform Available platform for sign up.\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @return {Promise} A promise that is fulfilled with the user when completed.\n * @example AV.User.associateWithAuthData(loginUser, 'weixin', {\n * openid: 'abc123',\n * access_token: '123abc',\n * expires_in: 1382686496\n * }).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n */\n associateWithAuthData(userObj, platform, authData) {\n return userObj._linkWith(platform, authData);\n },\n /**\n * Logs out the currently logged in user session. This will remove the\n * session from disk, log out of linked services, and future calls to\n * current will return null.\n * @return {Promise}\n */\n logOut: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser !== null) {\n AV.User._currentUser._logOutWithAll();\n AV.User._currentUser._isCurrentUser = false;\n }\n AV.User._currentUserMatchesDisk = true;\n AV.User._currentUser = null;\n return AV.localStorage.removeItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY));\n },\n\n /**\n *Create a follower query for special user to query the user's followers.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followerQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Follower');\n query._friendshipTag ='follower';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n *Create a followee query for special user to query the user's followees.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followeeQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Followee');\n query._friendshipTag ='followee';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n * Requests a password reset email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * reset their password on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * forgot their password.\n * @return {Promise}\n */\n requestPasswordReset: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestPasswordReset\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * verify their email address on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * doesn't verify their email address.\n * @return {Promise}\n */\n requestEmailVerify: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestEmailVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * verify their mobile phone number by calling AV.User.verifyMobilePhone\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestMobilePhoneVerify: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestMobilePhoneVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n\n /**\n * Requests a reset password sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * reset their account's password by calling AV.User.resetPasswordBySmsCode\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestPasswordResetBySmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestPasswordResetBySmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Makes a call to reset user's account password by sms code and new password.\n * The sms code is sent by AV.User.requestPasswordResetBySmsCode.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @param {String} password The new password.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n resetPasswordBySmsCode: function(code, password){\n var json = { password: password};\n var request = AVRequest(\"resetPasswordBySmsCode\", null, code, \"PUT\",\n json);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode\n * If verify successfully,the user mobilePhoneVerified attribute will be true.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifyMobilePhone: function(code){\n var request = AVRequest(\"verifyMobilePhone\", null, code, \"POST\",\n null);\n return request;\n },\n\n /**\n * Requests a logIn sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * login by AV.User.logInWithMobilePhoneSmsCode function.\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that want to login by AV.User.logInWithMobilePhoneSmsCode\n * @return {Promise}\n */\n requestLoginSmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestLoginSmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {Promise.} resolved with the currently logged in AV.User.\n */\n currentAsync: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser) {\n return Promise.resolve(AV.User._currentUser);\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return Promise.resolve(AV.User._currentUser);\n }\n\n\n return AV.localStorage.getItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY)\n ).then(function(userData) {\n if (!userData) {\n return null;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n });\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {AV.User} The currently logged in AV.User.\n */\n current: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return null;\n }\n\n if (AV.User._currentUser) {\n return AV.User._currentUser;\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return AV.User._currentUser;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n var userData = AV.localStorage.getItem(AV._getAVPath(\n AV.User._CURRENT_USER_KEY));\n if (!userData) {\n\n return null;\n }\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n },\n\n /**\n * Persists a user as currentUser to localStorage, and into the singleton.\n * @private\n */\n _saveCurrentUser: function(user) {\n var promise;\n if (AV.User._currentUser !== user) {\n promise = AV.User.logOut();\n }\n else {\n promise = Promise.resolve();\n }\n return promise.then(function() {\n user._isCurrentUser = true;\n AV.User._currentUser = user;\n\n var json = user.toJSON();\n json._id = user.id;\n json._sessionToken = user._sessionToken;\n return AV.localStorage.setItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY),\n JSON.stringify(json)\n ).then(function() {\n AV.User._currentUserMatchesDisk = true;\n });\n });\n },\n\n _registerAuthenticationProvider: function(provider) {\n AV.User._authProviders[provider.getAuthType()] = provider;\n // Synchronize the current user with the auth provider.\n if (!AV._config.disableCurrentUser && AV.User.current()) {\n AV.User.current()._synchronizeAuthData(provider.getAuthType());\n }\n },\n\n _logInWith: function(provider, options) {\n var user = AV.Object._create(\"_User\");\n return user._linkWith(provider, options);\n }\n\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/user.js","/*!\n * LeanCloud JavaScript SDK\n * https://leancloud.cn\n *\n * Copyright 2016 LeanCloud.cn, Inc.\n * The LeanCloud JavaScript SDK is freely distributable under the MIT license.\n */\n\nconst AV = require('./av');\n\nAV._ = require('underscore');\nAV.version = require('./version');\nAV.Promise = require('./promise');\nAV.localStorage = require('./localstorage');\nAV.Cache = require('./cache');\nAV.Error = require('./error');\n\nrequire('./init');\nrequire('./event')(AV);\nrequire('./geopoint')(AV);\nrequire('./acl')(AV);\nrequire('./op')(AV);\nrequire('./relation')(AV);\nrequire('./file')(AV);\nrequire('./object')(AV);\nrequire('./role')(AV);\nrequire('./user')(AV);\nrequire('./query')(AV);\nrequire('./cloudfunction')(AV);\nrequire('./push')(AV);\nrequire('./status')(AV);\nrequire('./search')(AV);\nrequire('./insight')(AV);\n\nmodule.exports = AV;\n\n/**\n * Options to controll the authentication for an operation\n * @typedef {Object} AuthOptions\n * @property {String} [sessionToken] Specify a user to excute the operation as.\n * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided.\n * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set.\n */\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","module.exports = [];\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/comments-browser.js","const version = require('../version');\nconst comments = [process.env.CLIENT_PLATFORM || 'Node.js'].concat(require('./comments'));\n\nmodule.exports = `LeanCloud-JS-SDK/${version} (${comments.join('; ')})`;\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/index.js","const request = require('superagent');\nconst debug = require('debug')('cos');\nconst Promise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n const uploadUrl = uploadInfo.upload_url + \"?sign=\" + encodeURIComponent(uploadInfo.token);\n\n return new Promise((resolve, reject) => {\n const req = request('POST', uploadUrl)\n .field('fileContent', data)\n .field('op', 'upload');\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/cos.js","const request = require('superagent');\nconst Promise = require('../promise');\nconst debug = require('debug')('qiniu');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n // Get the uptoken to upload files to qiniu.\n const uptoken = uploadInfo.token;\n return new Promise((resolve, reject) => {\n const req = request('POST', 'https://up.qbox.me')\n .field('file', data)\n .field('name', file.attributes.name)\n .field('key', file._qiniu_key)\n .field('token', uptoken);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/qiniu-browser.js","const request = require('superagent');\nconst AVPromise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n return new Promise((resolve, reject) => {\n // 海外节点,针对 S3 才会返回 upload_url\n const req = request('PUT', uploadInfo.upload_url)\n .set('Content-Type', file.get('mime_type'))\n .send(data);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/s3.js","var _ = require('underscore');\nvar Promise = require('../promise');\n\n// interface Storage {\n// readonly attribute boolean async;\n// string getItem(string key);\n// void setItem(string key, string value);\n// void removeItem(string key);\n// void clear();\n// Promise getItemAsync(string key);\n// Promise setItemAsync(string key, string value);\n// Promise removeItemAsync(string key);\n// Promise clearAsync();\n// }\nvar Storage = {};\nvar apiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nvar AsyncStorage = require('react-native').AsyncStorage;\n_(apiNames).each(function(apiName) {\n Storage[apiName + 'Async'] = function() {\n return Promise.resolve(AsyncStorage[apiName].apply(AsyncStorage, arguments));\n };\n});\nStorage.async = true;\n\nmodule.exports = Storage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/localstorage-rn.js","var dataURItoBlob = function(dataURI, type) {\n var byteString;\n\n // 传入的 base64,不是 dataURL\n if (dataURI.indexOf('base64') < 0) {\n byteString = atob(dataURI);\n } else if (dataURI.split(',')[0].indexOf('base64') >= 0) {\n type = type || dataURI.split(',')[0].split(':')[1].split(';')[0];\n byteString = atob(dataURI.split(',')[1]);\n } else {\n byteString = unescape(dataURI.split(',')[1]);\n }\n var ia = new Uint8Array(byteString.length);\n for (var i = 0; i < byteString.length; i ++) {\n ia[i] = byteString.charCodeAt(i);\n }\n return new Blob([ia], {type});\n};\n\nmodule.exports = dataURItoBlob;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/parse-base64-browser.js","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/component-emitter/index.js\n// module id = 38\n// module chunks = 0","(function() {\n var base64map\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n crypt = {\n // Bit-wise rotation left\n rotl: function(n, b) {\n return (n << b) | (n >>> (32 - b));\n },\n\n // Bit-wise rotation right\n rotr: function(n, b) {\n return (n << (32 - b)) | (n >>> b);\n },\n\n // Swap big-endian to little-endian and vice versa\n endian: function(n) {\n // If number given, swap endian\n if (n.constructor == Number) {\n return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n }\n\n // Else, assume array and swap all items\n for (var i = 0; i < n.length; i++)\n n[i] = crypt.endian(n[i]);\n return n;\n },\n\n // Generate an array of any length of random bytes\n randomBytes: function(n) {\n for (var bytes = []; n > 0; n--)\n bytes.push(Math.floor(Math.random() * 256));\n return bytes;\n },\n\n // Convert a byte array to big-endian 32-bit words\n bytesToWords: function(bytes) {\n for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n words[b >>> 5] |= bytes[i] << (24 - b % 32);\n return words;\n },\n\n // Convert big-endian 32-bit words to a byte array\n wordsToBytes: function(words) {\n for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a hex string\n bytesToHex: function(bytes) {\n for (var hex = [], i = 0; i < bytes.length; i++) {\n hex.push((bytes[i] >>> 4).toString(16));\n hex.push((bytes[i] & 0xF).toString(16));\n }\n return hex.join('');\n },\n\n // Convert a hex string to a byte array\n hexToBytes: function(hex) {\n for (var bytes = [], c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return bytes;\n },\n\n // Convert a byte array to a base-64 string\n bytesToBase64: function(bytes) {\n for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n for (var j = 0; j < 4; j++)\n if (i * 8 + j * 6 <= bytes.length * 8)\n base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n else\n base64.push('=');\n }\n return base64.join('');\n },\n\n // Convert a base-64 string to a byte array\n base64ToBytes: function(base64) {\n // Remove non-base-64 characters\n base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n imod4 = ++i % 4) {\n if (imod4 == 0) continue;\n bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n }\n return bytes;\n }\n };\n\n module.exports = crypt;\n})();\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/crypt/crypt.js\n// module id = 39\n// module chunks = 0","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (namespaces || '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/debug.js\n// module id = 40\n// module chunks = 0","/*!\n * @overview es6-promise - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE\n * @version 4.1.0\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.ES6Promise = factory());\n}(this, (function () { 'use strict';\n\nfunction objectOrFunction(x) {\n return typeof x === 'function' || typeof x === 'object' && x !== null;\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\nvar _isArray = undefined;\nif (!Array.isArray) {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n} else {\n _isArray = Array.isArray;\n}\n\nvar isArray = _isArray;\n\nvar len = 0;\nvar vertxNext = undefined;\nvar customSchedulerFn = undefined;\n\nvar asap = function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 2, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n if (customSchedulerFn) {\n customSchedulerFn(flush);\n } else {\n scheduleFlush();\n }\n }\n};\n\nfunction setScheduler(scheduleFn) {\n customSchedulerFn = scheduleFn;\n}\n\nfunction setAsap(asapFn) {\n asap = asapFn;\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // see https://github.com/cujojs/when/issues/410 for details\n return function () {\n return process.nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n if (typeof vertxNext !== 'undefined') {\n return function () {\n vertxNext(flush);\n };\n }\n\n return useSetTimeout();\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n // Store setTimeout reference so es6-promise will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var globalSetTimeout = setTimeout;\n return function () {\n return globalSetTimeout(flush, 1);\n };\n}\n\nvar queue = new Array(1000);\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n\n callback(arg);\n\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertx() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush = undefined;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush = attemptVertx();\n} else {\n scheduleFlush = useSetTimeout();\n}\n\nfunction then(onFulfillment, onRejection) {\n var _arguments = arguments;\n\n var parent = this;\n\n var child = new this.constructor(noop);\n\n if (child[PROMISE_ID] === undefined) {\n makePromise(child);\n }\n\n var _state = parent._state;\n\n if (_state) {\n (function () {\n var callback = _arguments[_state - 1];\n asap(function () {\n return invokeCallback(_state, child, callback, parent._result);\n });\n })();\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\n/**\n `Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {Any} value value that the returned promise will be resolved with\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve(object) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop);\n _resolve(promise, object);\n return promise;\n}\n\nvar PROMISE_ID = Math.random().toString(36).substring(16);\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nfunction selfFulfillment() {\n return new TypeError(\"You cannot resolve a promise with itself\");\n}\n\nfunction cannotReturnOwn() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then) {\n asap(function (promise) {\n var sealed = false;\n var error = tryThen(then, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n _resolve(promise, value);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n _reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n _reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n _reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n return _resolve(promise, value);\n }, function (reason) {\n return _reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$) {\n if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$ === GET_THEN_ERROR) {\n _reject(promise, GET_THEN_ERROR.error);\n GET_THEN_ERROR.error = null;\n } else if (then$$ === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$)) {\n handleForeignThenable(promise, maybeThenable, then$$);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction _resolve(promise, value) {\n if (promise === value) {\n _reject(promise, selfFulfillment());\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onerror) {\n promise._onerror(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length !== 0) {\n asap(publish, promise);\n }\n}\n\nfunction _reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n\n asap(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var _subscribers = parent._subscribers;\n var length = _subscribers.length;\n\n parent._onerror = null;\n\n _subscribers[length] = child;\n _subscribers[length + FULFILLED] = onFulfillment;\n _subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n asap(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = undefined,\n callback = undefined,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = undefined,\n error = undefined,\n succeeded = undefined,\n failed = undefined;\n\n if (hasCallback) {\n value = tryCatch(callback, detail);\n\n if (value === TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value.error = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n _reject(promise, cannotReturnOwn());\n return;\n }\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n _resolve(promise, value);\n } else if (failed) {\n _reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n _reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n try {\n resolver(function resolvePromise(value) {\n _resolve(promise, value);\n }, function rejectPromise(reason) {\n _reject(promise, reason);\n });\n } catch (e) {\n _reject(promise, e);\n }\n}\n\nvar id = 0;\nfunction nextId() {\n return id++;\n}\n\nfunction makePromise(promise) {\n promise[PROMISE_ID] = id++;\n promise._state = undefined;\n promise._result = undefined;\n promise._subscribers = [];\n}\n\nfunction Enumerator(Constructor, input) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop);\n\n if (!this.promise[PROMISE_ID]) {\n makePromise(this.promise);\n }\n\n if (isArray(input)) {\n this._input = input;\n this.length = input.length;\n this._remaining = input.length;\n\n this._result = new Array(this.length);\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate();\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n _reject(this.promise, validationError());\n }\n}\n\nfunction validationError() {\n return new Error('Array Methods must be provided an Array');\n};\n\nEnumerator.prototype._enumerate = function () {\n var length = this.length;\n var _input = this._input;\n\n for (var i = 0; this._state === PENDING && i < length; i++) {\n this._eachEntry(_input[i], i);\n }\n};\n\nEnumerator.prototype._eachEntry = function (entry, i) {\n var c = this._instanceConstructor;\n var resolve$$ = c.resolve;\n\n if (resolve$$ === resolve) {\n var _then = getThen(entry);\n\n if (_then === then && entry._state !== PENDING) {\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof _then !== 'function') {\n this._remaining--;\n this._result[i] = entry;\n } else if (c === Promise) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, _then);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve$$) {\n return resolve$$(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve$$(entry), i);\n }\n};\n\nEnumerator.prototype._settledAt = function (state, i, value) {\n var promise = this.promise;\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (state === REJECTED) {\n _reject(promise, value);\n } else {\n this._result[i] = value;\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n};\n\nEnumerator.prototype._willSettleAt = function (promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n};\n\n/**\n `Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = resolve(2);\n let promise3 = resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = reject(new Error(\"2\"));\n let promise3 = reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries) {\n return new Enumerator(this, entries).promise;\n}\n\n/**\n `Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} promises array of promises to observe\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (!isArray(entries)) {\n return new Constructor(function (_, reject) {\n return reject(new TypeError('You must pass an array to race.'));\n });\n } else {\n return new Constructor(function (resolve, reject) {\n var length = entries.length;\n for (var i = 0; i < length; i++) {\n Constructor.resolve(entries[i]).then(resolve, reject);\n }\n });\n }\n}\n\n/**\n `Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {Any} reason value that the returned promise will be rejected with.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject(reason) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop);\n _reject(promise, reason);\n return promise;\n}\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise's eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {function} resolver\n Useful for tooling.\n @constructor\n*/\nfunction Promise(resolver) {\n this[PROMISE_ID] = nextId();\n this._result = this._state = undefined;\n this._subscribers = [];\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n}\n\nPromise.all = all;\nPromise.race = race;\nPromise.resolve = resolve;\nPromise.reject = reject;\nPromise._setScheduler = setScheduler;\nPromise._setAsap = setAsap;\nPromise._asap = asap;\n\nPromise.prototype = {\n constructor: Promise,\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n \n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n \n Chaining\n --------\n \n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n \n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n \n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n \n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n \n Assimilation\n ------------\n \n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n \n If the assimliated promise rejects, then the downstream promise will also reject.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n \n Simple Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let result;\n \n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n \n Advanced Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let author, books;\n \n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n \n function foundBooks(books) {\n \n }\n \n function failure(reason) {\n \n }\n \n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n \n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n then: then,\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function _catch(onRejection) {\n return this.then(null, onRejection);\n }\n};\n\nfunction polyfill() {\n var local = undefined;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P) {\n var promiseToString = null;\n try {\n promiseToString = Object.prototype.toString.call(P.resolve());\n } catch (e) {\n // silently ignored\n }\n\n if (promiseToString === '[object Promise]' && !P.cast) {\n return;\n }\n }\n\n local.Promise = Promise;\n}\n\n// Strange compat..\nPromise.polyfill = polyfill;\nPromise.Promise = Promise;\n\nreturn Promise;\n\n})));\n//# sourceMappingURL=es6-promise.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/es6-promise/dist/es6-promise.js\n// module id = 41\n// module chunks = 0","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/is-buffer/index.js\n// module id = 42\n// module chunks = 0","(function(){\r\n var crypt = require('crypt'),\r\n utf8 = require('charenc').utf8,\r\n isBuffer = require('is-buffer'),\r\n bin = require('charenc').bin,\r\n\r\n // The core\r\n md5 = function (message, options) {\r\n // Convert to byte array\r\n if (message.constructor == String)\r\n if (options && options.encoding === 'binary')\r\n message = bin.stringToBytes(message);\r\n else\r\n message = utf8.stringToBytes(message);\r\n else if (isBuffer(message))\r\n message = Array.prototype.slice.call(message, 0);\r\n else if (!Array.isArray(message))\r\n message = message.toString();\r\n // else, assume byte array already\r\n\r\n var m = crypt.bytesToWords(message),\r\n l = message.length * 8,\r\n a = 1732584193,\r\n b = -271733879,\r\n c = -1732584194,\r\n d = 271733878;\r\n\r\n // Swap endian\r\n for (var i = 0; i < m.length; i++) {\r\n m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;\r\n }\r\n\r\n // Padding\r\n m[l >>> 5] |= 0x80 << (l % 32);\r\n m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n // Method shortcuts\r\n var FF = md5._ff,\r\n GG = md5._gg,\r\n HH = md5._hh,\r\n II = md5._ii;\r\n\r\n for (var i = 0; i < m.length; i += 16) {\r\n\r\n var aa = a,\r\n bb = b,\r\n cc = c,\r\n dd = d;\r\n\r\n a = FF(a, b, c, d, m[i+ 0], 7, -680876936);\r\n d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n c = FF(c, d, a, b, m[i+ 2], 17, 606105819);\r\n b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n a = FF(a, b, c, d, m[i+ 4], 7, -176418897);\r\n d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);\r\n c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);\r\n d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n a = FF(a, b, c, d, m[i+12], 7, 1804603682);\r\n d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n b = FF(b, c, d, a, m[i+15], 22, 1236535329);\r\n\r\n a = GG(a, b, c, d, m[i+ 1], 5, -165796510);\r\n d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);\r\n c = GG(c, d, a, b, m[i+11], 14, 643717713);\r\n b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n a = GG(a, b, c, d, m[i+ 5], 5, -701558691);\r\n d = GG(d, a, b, c, m[i+10], 9, 38016083);\r\n c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n a = GG(a, b, c, d, m[i+ 9], 5, 568446438);\r\n d = GG(d, a, b, c, m[i+14], 9, -1019803690);\r\n c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);\r\n a = GG(a, b, c, d, m[i+13], 5, -1444681467);\r\n d = GG(d, a, b, c, m[i+ 2], 9, -51403784);\r\n c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);\r\n b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n a = HH(a, b, c, d, m[i+ 5], 4, -378558);\r\n d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n c = HH(c, d, a, b, m[i+11], 16, 1839030562);\r\n b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);\r\n d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);\r\n c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n a = HH(a, b, c, d, m[i+13], 4, 681279174);\r\n d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n b = HH(b, c, d, a, m[i+ 6], 23, 76029189);\r\n a = HH(a, b, c, d, m[i+ 9], 4, -640364487);\r\n d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n c = HH(c, d, a, b, m[i+15], 16, 530742520);\r\n b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n a = II(a, b, c, d, m[i+ 0], 6, -198630844);\r\n d = II(d, a, b, c, m[i+ 7], 10, 1126891415);\r\n c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n a = II(a, b, c, d, m[i+12], 6, 1700485571);\r\n d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n a = II(a, b, c, d, m[i+ 8], 6, 1873313359);\r\n d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n b = II(b, c, d, a, m[i+13], 21, 1309151649);\r\n a = II(a, b, c, d, m[i+ 4], 6, -145523070);\r\n d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n c = II(c, d, a, b, m[i+ 2], 15, 718787259);\r\n b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n a = (a + aa) >>> 0;\r\n b = (b + bb) >>> 0;\r\n c = (c + cc) >>> 0;\r\n d = (d + dd) >>> 0;\r\n }\r\n\r\n return crypt.endian([a, b, c, d]);\r\n };\r\n\r\n // Auxiliary functions\r\n md5._ff = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._gg = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._hh = function (a, b, c, d, x, s, t) {\r\n var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._ii = function (a, b, c, d, x, s, t) {\r\n var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n\r\n // Package private blocksize\r\n md5._blocksize = 16;\r\n md5._digestsize = 16;\r\n\r\n module.exports = function (message, options) {\r\n if (message === undefined || message === null)\r\n throw new Error('Illegal argument ' + message);\r\n\r\n var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n return options && options.asBytes ? digestbytes :\r\n options && options.asString ? bin.bytesToString(digestbytes) :\r\n crypt.bytesToHex(digestbytes);\r\n };\r\n\r\n})();\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/md5/md5.js\n// module id = 43\n// module chunks = 0","/**\n * Helpers.\n */\n\nvar s = 1000\nvar m = s * 60\nvar h = m * 60\nvar d = h * 24\nvar y = d * 365.25\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} options\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {}\n var type = typeof val\n if (type === 'string' && val.length > 0) {\n return parse(val)\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ?\n\t\t\tfmtLong(val) :\n\t\t\tfmtShort(val)\n }\n throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))\n}\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str)\n if (str.length > 10000) {\n return\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)\n if (!match) {\n return\n }\n var n = parseFloat(match[1])\n var type = (match[2] || 'ms').toLowerCase()\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y\n case 'days':\n case 'day':\n case 'd':\n return n * d\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n\n default:\n return undefined\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd'\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h'\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm'\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's'\n }\n return ms + 'ms'\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms'\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name\n }\n return Math.ceil(ms / n) + ' ' + name + 's'\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ms/index.js\n// module id = 44\n// module chunks = 0","/**\n * Check if `fn` is a function.\n *\n * @param {Function} fn\n * @return {Boolean}\n * @api private\n */\nvar isObject = require('./is-object');\n\nfunction isFunction(fn) {\n var tag = isObject(fn) ? Object.prototype.toString.call(fn) : '';\n return tag === '[object Function]';\n}\n\nmodule.exports = isFunction;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-function.js\n// module id = 45\n// module chunks = 0","/**\n * Module of mixed-in functions shared between node and client code\n */\nvar isObject = require('./is-object');\n\n/**\n * Expose `RequestBase`.\n */\n\nmodule.exports = RequestBase;\n\n/**\n * Initialize a new `RequestBase`.\n *\n * @api public\n */\n\nfunction RequestBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in RequestBase.prototype) {\n obj[key] = RequestBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Clear previous timeout.\n *\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.clearTimeout = function _clearTimeout(){\n clearTimeout(this._timer);\n clearTimeout(this._responseTimeoutTimer);\n delete this._timer;\n delete this._responseTimeoutTimer;\n return this;\n};\n\n/**\n * Override default response body parser\n *\n * This function will be called to convert incoming data into request.body\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.parse = function parse(fn){\n this._parser = fn;\n return this;\n};\n\n/**\n * Set format of binary response body.\n * In browser valid formats are 'blob' and 'arraybuffer',\n * which return Blob and ArrayBuffer, respectively.\n *\n * In Node all values result in Buffer.\n *\n * Examples:\n *\n * req.get('/')\n * .responseType('blob')\n * .end(callback);\n *\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.responseType = function(val){\n this._responseType = val;\n return this;\n};\n\n/**\n * Override default request body serializer\n *\n * This function will be called to convert data set via .send or .attach into payload to send\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.serialize = function serialize(fn){\n this._serializer = fn;\n return this;\n};\n\n/**\n * Set timeouts.\n *\n * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.\n * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.\n *\n * Value of 0 or false means no timeout.\n *\n * @param {Number|Object} ms or {response, read, deadline}\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.timeout = function timeout(options){\n if (!options || 'object' !== typeof options) {\n this._timeout = options;\n this._responseTimeout = 0;\n return this;\n }\n\n for(var option in options) {\n switch(option) {\n case 'deadline':\n this._timeout = options.deadline;\n break;\n case 'response':\n this._responseTimeout = options.response;\n break;\n default:\n console.warn(\"Unknown timeout option\", option);\n }\n }\n return this;\n};\n\n/**\n * Set number of retry attempts on error.\n *\n * Failed requests will be retried 'count' times if timeout or err.code >= 500.\n *\n * @param {Number} count\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.retry = function retry(count){\n // Default to 1 if no count passed or true\n if (arguments.length === 0 || count === true) count = 1;\n if (count <= 0) count = 0;\n this._maxRetries = count;\n this._retries = 0;\n return this;\n};\n\n/**\n * Retry request\n *\n * @return {Request} for chaining\n * @api private\n */\n\nRequestBase.prototype._retry = function() {\n this.clearTimeout();\n\n // node\n if (this.req) {\n this.req = null;\n this.req = this.request();\n }\n\n this._aborted = false;\n this.timedout = false;\n\n return this._end();\n};\n\n/**\n * Promise support\n *\n * @param {Function} resolve\n * @param {Function} [reject]\n * @return {Request}\n */\n\nRequestBase.prototype.then = function then(resolve, reject) {\n if (!this._fullfilledPromise) {\n var self = this;\n if (this._endCalled) {\n console.warn(\"Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises\");\n }\n this._fullfilledPromise = new Promise(function(innerResolve, innerReject){\n self.end(function(err, res){\n if (err) innerReject(err); else innerResolve(res);\n });\n });\n }\n return this._fullfilledPromise.then(resolve, reject);\n}\n\nRequestBase.prototype.catch = function(cb) {\n return this.then(undefined, cb);\n};\n\n/**\n * Allow for extension\n */\n\nRequestBase.prototype.use = function use(fn) {\n fn(this);\n return this;\n}\n\nRequestBase.prototype.ok = function(cb) {\n if ('function' !== typeof cb) throw Error(\"Callback required\");\n this._okCallback = cb;\n return this;\n};\n\nRequestBase.prototype._isResponseOK = function(res) {\n if (!res) {\n return false;\n }\n\n if (this._okCallback) {\n return this._okCallback(res);\n }\n\n return res.status >= 200 && res.status < 300;\n};\n\n\n/**\n * Get request header `field`.\n * Case-insensitive.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nRequestBase.prototype.get = function(field){\n return this._header[field.toLowerCase()];\n};\n\n/**\n * Get case-insensitive header `field` value.\n * This is a deprecated internal API. Use `.get(field)` instead.\n *\n * (getHeader is no longer used internally by the superagent code base)\n *\n * @param {String} field\n * @return {String}\n * @api private\n * @deprecated\n */\n\nRequestBase.prototype.getHeader = RequestBase.prototype.get;\n\n/**\n * Set header `field` to `val`, or multiple fields with one object.\n * Case-insensitive.\n *\n * Examples:\n *\n * req.get('/')\n * .set('Accept', 'application/json')\n * .set('X-API-Key', 'foobar')\n * .end(callback);\n *\n * req.get('/')\n * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })\n * .end(callback);\n *\n * @param {String|Object} field\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.set = function(field, val){\n if (isObject(field)) {\n for (var key in field) {\n this.set(key, field[key]);\n }\n return this;\n }\n this._header[field.toLowerCase()] = val;\n this.header[field] = val;\n return this;\n};\n\n/**\n * Remove header `field`.\n * Case-insensitive.\n *\n * Example:\n *\n * req.get('/')\n * .unset('User-Agent')\n * .end(callback);\n *\n * @param {String} field\n */\nRequestBase.prototype.unset = function(field){\n delete this._header[field.toLowerCase()];\n delete this.header[field];\n return this;\n};\n\n/**\n * Write the field `name` and `val`, or multiple fields with one object\n * for \"multipart/form-data\" request bodies.\n *\n * ``` js\n * request.post('/upload')\n * .field('foo', 'bar')\n * .end(callback);\n *\n * request.post('/upload')\n * .field({ foo: 'bar', baz: 'qux' })\n * .end(callback);\n * ```\n *\n * @param {String|Object} name\n * @param {String|Blob|File|Buffer|fs.ReadStream} val\n * @return {Request} for chaining\n * @api public\n */\nRequestBase.prototype.field = function(name, val) {\n\n // name should be either a string or an object.\n if (null === name || undefined === name) {\n throw new Error('.field(name, val) name can not be empty');\n }\n\n if (this._data) {\n console.error(\".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObject(name)) {\n for (var key in name) {\n this.field(key, name[key]);\n }\n return this;\n }\n\n if (Array.isArray(val)) {\n for (var i in val) {\n this.field(name, val[i]);\n }\n return this;\n }\n\n // val should be defined now\n if (null === val || undefined === val) {\n throw new Error('.field(name, val) val can not be empty');\n }\n if ('boolean' === typeof val) {\n val = '' + val;\n }\n this._getFormData().append(name, val);\n return this;\n};\n\n/**\n * Abort the request, and clear potential timeout.\n *\n * @return {Request}\n * @api public\n */\nRequestBase.prototype.abort = function(){\n if (this._aborted) {\n return this;\n }\n this._aborted = true;\n this.xhr && this.xhr.abort(); // browser\n this.req && this.req.abort(); // node\n this.clearTimeout();\n this.emit('abort');\n return this;\n};\n\n/**\n * Enable transmission of cookies with x-domain requests.\n *\n * Note that for this to work the origin must not be\n * using \"Access-Control-Allow-Origin\" with a wildcard,\n * and also must set \"Access-Control-Allow-Credentials\"\n * to \"true\".\n *\n * @api public\n */\n\nRequestBase.prototype.withCredentials = function(on){\n // This is browser-only functionality. Node side is no-op.\n if(on==undefined) on = true;\n this._withCredentials = on;\n return this;\n};\n\n/**\n * Set the max redirects to `n`. Does noting in browser XHR implementation.\n *\n * @param {Number} n\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.redirects = function(n){\n this._maxRedirects = n;\n return this;\n};\n\n/**\n * Convert to a plain javascript object (not JSON string) of scalar properties.\n * Note as this method is designed to return a useful non-this value,\n * it cannot be chained.\n *\n * @return {Object} describing method, url, and data of this request\n * @api public\n */\n\nRequestBase.prototype.toJSON = function(){\n return {\n method: this.method,\n url: this.url,\n data: this._data,\n headers: this._header\n };\n};\n\n\n/**\n * Send `data` as the request body, defaulting the `.type()` to \"json\" when\n * an object is given.\n *\n * Examples:\n *\n * // manual json\n * request.post('/user')\n * .type('json')\n * .send('{\"name\":\"tj\"}')\n * .end(callback)\n *\n * // auto json\n * request.post('/user')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // manual x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send('name=tj')\n * .end(callback)\n *\n * // auto x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // defaults to x-www-form-urlencoded\n * request.post('/user')\n * .send('name=tobi')\n * .send('species=ferret')\n * .end(callback)\n *\n * @param {String|Object} data\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.send = function(data){\n var isObj = isObject(data);\n var type = this._header['content-type'];\n\n if (this._formData) {\n console.error(\".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObj && !this._data) {\n if (Array.isArray(data)) {\n this._data = [];\n } else if (!this._isHost(data)) {\n this._data = {};\n }\n } else if (data && this._data && this._isHost(this._data)) {\n throw Error(\"Can't merge these send calls\");\n }\n\n // merge\n if (isObj && isObject(this._data)) {\n for (var key in data) {\n this._data[key] = data[key];\n }\n } else if ('string' == typeof data) {\n // default to x-www-form-urlencoded\n if (!type) this.type('form');\n type = this._header['content-type'];\n if ('application/x-www-form-urlencoded' == type) {\n this._data = this._data\n ? this._data + '&' + data\n : data;\n } else {\n this._data = (this._data || '') + data;\n }\n } else {\n this._data = data;\n }\n\n if (!isObj || this._isHost(data)) {\n return this;\n }\n\n // default to json\n if (!type) this.type('json');\n return this;\n};\n\n\n/**\n * Sort `querystring` by the sort function\n *\n *\n * Examples:\n *\n * // default order\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery()\n * .end(callback)\n *\n * // customized sort function\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery(function(a, b){\n * return a.length - b.length;\n * })\n * .end(callback)\n *\n *\n * @param {Function} sort\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.sortQuery = function(sort) {\n // _sort default to true but otherwise can be a function or boolean\n this._sort = typeof sort === 'undefined' ? true : sort;\n return this;\n};\n\n/**\n * Invoke callback with timeout error.\n *\n * @api private\n */\n\nRequestBase.prototype._timeoutError = function(reason, timeout, errno){\n if (this._aborted) {\n return;\n }\n var err = new Error(reason + timeout + 'ms exceeded');\n err.timeout = timeout;\n err.code = 'ECONNABORTED';\n err.errno = errno;\n this.timedout = true;\n this.abort();\n this.callback(err);\n};\n\nRequestBase.prototype._setTimeouts = function() {\n var self = this;\n\n // deadline\n if (this._timeout && !this._timer) {\n this._timer = setTimeout(function(){\n self._timeoutError('Timeout of ', self._timeout, 'ETIME');\n }, this._timeout);\n }\n // response timeout\n if (this._responseTimeout && !this._responseTimeoutTimer) {\n this._responseTimeoutTimer = setTimeout(function(){\n self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');\n }, this._responseTimeout);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/request-base.js\n// module id = 46\n// module chunks = 0","\n/**\n * Module dependencies.\n */\n\nvar utils = require('./utils');\n\n/**\n * Expose `ResponseBase`.\n */\n\nmodule.exports = ResponseBase;\n\n/**\n * Initialize a new `ResponseBase`.\n *\n * @api public\n */\n\nfunction ResponseBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in ResponseBase.prototype) {\n obj[key] = ResponseBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Get case-insensitive `field` value.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nResponseBase.prototype.get = function(field){\n return this.header[field.toLowerCase()];\n};\n\n/**\n * Set header related properties:\n *\n * - `.type` the content type without params\n *\n * A response of \"Content-Type: text/plain; charset=utf-8\"\n * will provide you with a `.type` of \"text/plain\".\n *\n * @param {Object} header\n * @api private\n */\n\nResponseBase.prototype._setHeaderProperties = function(header){\n // TODO: moar!\n // TODO: make this a util\n\n // content-type\n var ct = header['content-type'] || '';\n this.type = utils.type(ct);\n\n // params\n var params = utils.params(ct);\n for (var key in params) this[key] = params[key];\n\n this.links = {};\n\n // links\n try {\n if (header.link) {\n this.links = utils.parseLinks(header.link);\n }\n } catch (err) {\n // ignore\n }\n};\n\n/**\n * Set flags such as `.ok` based on `status`.\n *\n * For example a 2xx response will give you a `.ok` of __true__\n * whereas 5xx will be __false__ and `.error` will be __true__. The\n * `.clientError` and `.serverError` are also available to be more\n * specific, and `.statusType` is the class of error ranging from 1..5\n * sometimes useful for mapping respond colors etc.\n *\n * \"sugar\" properties are also defined for common cases. Currently providing:\n *\n * - .noContent\n * - .badRequest\n * - .unauthorized\n * - .notAcceptable\n * - .notFound\n *\n * @param {Number} status\n * @api private\n */\n\nResponseBase.prototype._setStatusProperties = function(status){\n var type = status / 100 | 0;\n\n // status / class\n this.status = this.statusCode = status;\n this.statusType = type;\n\n // basics\n this.info = 1 == type;\n this.ok = 2 == type;\n this.redirect = 3 == type;\n this.clientError = 4 == type;\n this.serverError = 5 == type;\n this.error = (4 == type || 5 == type)\n ? this.toError()\n : false;\n\n // sugar\n this.accepted = 202 == status;\n this.noContent = 204 == status;\n this.badRequest = 400 == status;\n this.unauthorized = 401 == status;\n this.notAcceptable = 406 == status;\n this.forbidden = 403 == status;\n this.notFound = 404 == status;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/response-base.js\n// module id = 47\n// module chunks = 0","var ERROR_CODES = [\n 'ECONNRESET',\n 'ETIMEDOUT',\n 'EADDRINFO',\n 'ESOCKETTIMEDOUT'\n];\n\n/**\n * Determine if a request should be retried.\n * (Borrowed from segmentio/superagent-retry)\n *\n * @param {Error} err\n * @param {Response} [res]\n * @returns {Boolean}\n */\nmodule.exports = function shouldRetry(err, res) {\n if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true;\n if (res && res.status && res.status >= 500) return true;\n // Superagent timeout\n if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true;\n if (err && 'crossDomain' in err) return true;\n return false;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/should-retry.js\n// module id = 48\n// module chunks = 0","\n/**\n * Return the mime type for the given `str`.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nexports.type = function(str){\n return str.split(/ *; */).shift();\n};\n\n/**\n * Return header field parameters.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.params = function(str){\n return str.split(/ *; */).reduce(function(obj, str){\n var parts = str.split(/ *= */);\n var key = parts.shift();\n var val = parts.shift();\n\n if (key && val) obj[key] = val;\n return obj;\n }, {});\n};\n\n/**\n * Parse Link header fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.parseLinks = function(str){\n return str.split(/ *, */).reduce(function(obj, str){\n var parts = str.split(/ *; */);\n var url = parts[0].slice(1, -1);\n var rel = parts[1].split(/ *= */)[1].slice(1, -1);\n obj[rel] = url;\n return obj;\n }, {});\n};\n\n/**\n * Strip content related fields from `header`.\n *\n * @param {Object} header\n * @return {Object} header\n * @api private\n */\n\nexports.cleanHeader = function(header, shouldStripCookie){\n delete header['content-type'];\n delete header['content-length'];\n delete header['transfer-encoding'];\n delete header['host'];\n if (shouldStripCookie) {\n delete header['cookie'];\n }\n return header;\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/utils.js\n// module id = 49\n// module chunks = 0","module.exports = __WEBPACK_EXTERNAL_MODULE_50__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"react-native\"\n// module id = 50\n// module chunks = 0","/* (ignored) */\n\n\n//////////////////\n// WEBPACK FOOTER\n// vertx (ignored)\n// module id = 51\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/av-weapp-min.js b/dist/av-weapp-min.js new file mode 100644 index 000000000..0e8187785 --- /dev/null +++ b/dist/av-weapp-min.js @@ -0,0 +1,6 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.AV=t():e.AV=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=30)}([function(e,t,n){var r,i;(function(){function n(e){function t(t,n,r,i,o,s){for(;o>=0&&o0?0:a-1;return arguments.length<3&&(i=n[s?s[u]:u],u+=e),t(n,r,i,s,u,a)}}function o(e){return function(t,n,r){n=A(n,r);for(var i=C(t),o=e>0?0:i-1;o>=0&&o0?s=o>=0?o:Math.max(o+a,s):a=o>=0?Math.min(o+1,a):o+a+1;else if(n&&o&&a)return o=n(r,i),r[o]===i?o:-1;if(i!==i)return o=t(p.call(r,s,a),S.isNaN),o>=0?o+s:-1;for(o=e>0?s:a-1;o>=0&&o=0&&t<=N};S.each=S.forEach=function(e,t,n){t=O(t,n);var r,i;if(x(e))for(r=0,i=e.length;r=0},S.invoke=function(e,t){var n=p.call(arguments,2),r=S.isFunction(t);return S.map(e,function(e){var i=r?t:e[t];return null==i?i:i.apply(e,n)})},S.pluck=function(e,t){return S.map(e,S.property(t))},S.where=function(e,t){return S.filter(e,S.matcher(t))},S.findWhere=function(e,t){return S.find(e,S.matcher(t))},S.max=function(e,t,n){var r,i,o=-(1/0),s=-(1/0);if(null==t&&null!=e){e=x(e)?e:S.values(e);for(var a=0,u=e.length;ao&&(o=r)}else t=A(t,n),S.each(e,function(e,n,r){i=t(e,n,r),(i>s||i===-(1/0)&&o===-(1/0))&&(o=e,s=i)});return o},S.min=function(e,t,n){var r,i,o=1/0,s=1/0;if(null==t&&null!=e){e=x(e)?e:S.values(e);for(var a=0,u=e.length;ar||void 0===n)return 1;if(nt?(s&&(clearTimeout(s),s=null),a=c,o=e.apply(r,i),s||(r=i=null)):s||n.trailing===!1||(s=setTimeout(u,l)),o}},S.debounce=function(e,t,n){var r,i,o,s,a,u=function(){var c=S.now()-s;c=0?r=setTimeout(u,t-c):(r=null,n||(a=e.apply(o,i),r||(o=i=null)))};return function(){o=this,i=arguments,s=S.now();var c=n&&!r;return r||(r=setTimeout(u,t)),c&&(a=e.apply(o,i),o=i=null),a}},S.wrap=function(e,t){return S.partial(t,e)},S.negate=function(e){return function(){return!e.apply(this,arguments)}},S.compose=function(){var e=arguments,t=e.length-1;return function(){for(var n=t,r=e[t].apply(this,arguments);n--;)r=e[n].call(this,r);return r}},S.after=function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},S.before=function(e,t){var n;return function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=null),n}},S.once=S.partial(S.before,2);var P=!{toString:null}.propertyIsEnumerable("toString"),R=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];S.keys=function(e){if(!S.isObject(e))return[];if(m)return m(e);var t=[];for(var n in e)S.has(e,n)&&t.push(n);return P&&a(e,t),t},S.allKeys=function(e){if(!S.isObject(e))return[];var t=[];for(var n in e)t.push(n);return P&&a(e,t),t},S.values=function(e){for(var t=S.keys(e),n=t.length,r=Array(n),i=0;i":">",'"':""","'":"'","`":"`"},q=S.invert(L),M=function(e){var t=function(t){return e[t]},n="(?:"+S.keys(e).join("|")+")",r=RegExp(n),i=RegExp(n,"g");return function(e){return e=null==e?"":""+e,r.test(e)?e.replace(i,t):e}};S.escape=M(L),S.unescape=M(q),S.result=function(e,t,n){var r=null==e?void 0:e[t];return void 0===r&&(r=n),S.isFunction(r)?r.call(e):r};var F=0;S.uniqueId=function(e){var t=++F+"";return e?e+t:t},S.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var B=/(.)^/,J={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},W=/\\|'|\r|\n|\u2028|\u2029/g,V=function(e){return"\\"+J[e]};S.template=function(e,t,n){!t&&n&&(t=n),t=S.defaults({},t,S.templateSettings);var r=RegExp([(t.escape||B).source,(t.interpolate||B).source,(t.evaluate||B).source].join("|")+"|$","g"),i=0,o="__p+='";e.replace(r,function(t,n,r,s,a){return o+=e.slice(i,a).replace(W,V),i=a+t.length,n?o+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":r?o+="'+\n((__t=("+r+"))==null?'':__t)+\n'":s&&(o+="';\n"+s+"\n__p+='"),t}),o+="';\n",t.variable||(o="with(obj||{}){\n"+o+"}\n"),o="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{var s=new Function(t.variable||"obj","_",o)}catch(e){throw e.source=o,e}var a=function(e){return s.call(this,e,S)},u=t.variable||"obj";return a.source="function("+u+"){\n"+o+"}",a},S.chain=function(e){var t=S(e);return t._chain=!0,t};var Q=function(e,t){return e._chain?S(t).chain():t};S.mixin=function(e){S.each(S.functions(e),function(t){var n=S[t]=e[t];S.prototype[t]=function(){var e=[this._wrapped];return d.apply(e,arguments),Q(this,n.apply(S,e))}})},S.mixin(S),S.each(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=l[e];S.prototype[e]=function(){var n=this._wrapped;return t.apply(n,arguments),"shift"!==e&&"splice"!==e||0!==n.length||delete n[0],Q(this,n)}}),S.each(["concat","join","slice"],function(e){var t=l[e];S.prototype[e]=function(){return Q(this,t.apply(this._wrapped,arguments))}}),S.prototype.value=function(){return this._wrapped},S.prototype.valueOf=S.prototype.toJSON=S.prototype.value,S.prototype.toString=function(){return""+this._wrapped},r=[],i=function(){return S}.apply(t,r),!(void 0!==i&&(e.exports=i))}).call(this)},function(e,t,n){"use strict";var r=(n(0),n(52).Promise);r._continueWhile=function(e,t){return e()?t().then(function(){return r._continueWhile(e,t)}):r.resolve()},e.exports=r},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=n(7),o=n(5)("leancloud:request"),s=n(57),a=n(1),u=n(16),c=n(3),l=n(6),f=n(0),h=n(4),d=h.getSessionToken,p=void 0,_={cn:"https://api.leancloud.cn",us:"https://us-api.leancloud.cn"},v=function(e,t){var n=(new Date).getTime(),r=s(n+e);return t?r+","+n+",master":r+","+n},y=0,m=function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},s=arguments[4],u=y++;return o("request("+u+")",e,t,n,r),new a(function(a,c){var l=i(e,t).set(r).send(n);s&&l.on("progress",s),l.end(function(e,t){return t&&o("response("+u+")",t.status,t.body||t.text,t.header),e?(t&&(e.statusCode=t.status,e.responseText=t.text,e.response=t.body),c(e)):a(t.body)})})},g=function(e,t){t?e["X-LC-Sign"]=v(l.applicationKey):e["X-LC-Key"]=l.applicationKey},b=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],n={"X-LC-Id":l.applicationId,"Content-Type":"application/json;charset=UTF-8"},r=!1;return"boolean"==typeof e.useMasterKey?r=e.useMasterKey:"boolean"==typeof l._useMasterKey&&(r=l._useMasterKey),r?l.masterKey?t?n["X-LC-Sign"]=v(l.masterKey,!0):n["X-LC-Key"]=l.masterKey+",master":(console.warn("masterKey is not set, fall back to use appKey"),g(n,t)):g(n,t),l.hookKey&&(n["X-LC-Hook-Key"]=l.hookKey),null!==l._config.applicationProduction&&(n["X-LC-Prod"]=String(l._config.applicationProduction)),n["X-LC-UA"]=l._config.userAgent,a.resolve().then(function(){var t=d(e);if(t)n["X-LC-Session"]=t;else if(!l._config.disableCurrentUser)return l.User.currentAsync().then(function(e){return e&&e._sessionToken&&(n["X-LC-Session"]=e._sessionToken),n});return n})},w=function(e,t,n,i,o){l.serverURL&&(l._config.APIServerURL=l.serverURL,console.warn("Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface."));var s=l._config.APIServerURL||_.cn;if("/"!==s.charAt(s.length-1)&&(s+="/"),s+="1.1/"+e,t&&(s+="/"+t),n&&(s+="/"+n),"users"!==e&&"classes"!==e||!o||(s+="?",o._fetchWhenSave&&(delete o._fetchWhenSave,s+="&new=true"),o._where&&(s+="&where="+encodeURIComponent(JSON.stringify(o._where)),delete o._where)),"get"===i.toLowerCase()){s.indexOf("?")===-1&&(s+="?");for(var a in o)"object"===r(o[a])&&(o[a]=JSON.stringify(o[a])),s+="&"+a+"="+encodeURIComponent(o[a])}return s},S=function(e,t){return"number"!=typeof t&&(t=3600),u.setAsync("APIServerURL",e,1e3*t)},O=function(e){return new a(function(t,n){if(410===e.statusCode)S(e.response.api_server,e.response.ttl).then(function(){t(e.response.location)}).catch(n);else{var r={code:e.code||-1,error:e.message||e.responseText};if(e.response&&e.response.code)r=e.response;else if(e.responseText)try{r=JSON.parse(e.responseText)}catch(e){}n(new c(r.code,r.error))}})},A=function(e){l._config.APIServerURL="https://"+e;var t=f.findKey(_,function(e){return e===l._config.APIServerURL});t&&(l._config.region=t)},E=function(){var e="https://app-router.leancloud.cn/1/route?appId="+l.applicationId;return m("get",e).then(function(e){if(e.api_server)return A(e.api_server),S(e.api_server,e.ttl)},function(e){if(e.statusCode>=400&&e.statusCode<500)throw e})},T=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"cn";p=new a(function(t,n){return l._config.APIServerURL?void t():"cn"===e?u.getAsync("APIServerURL").then(function(e){return e?void A(e):E()}).then(function(){t()}).catch(function(e){n(e)}):(l._config.region=e,l._config.APIServerURL=_[e],t(),void 0)})},j=function(e,t,n,r){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},o=arguments[5];if(!l.applicationId)throw new Error("You must specify your applicationId using AV.init()");if(!l.applicationKey&&!l.masterKey)throw new Error("You must specify a AppKey using AV.init()");return p?p.then(function(){var s=w(e,t,n,r,i);return b(o,"bigquery"!==e).then(function(e){return m(r,s,i,e).then(null,function(t){return O(t).then(function(t){return m(r,t,i,e)})})})}):a.reject(new Error("Not initialized"))};e.exports={ajax:m,request:j,setServerUrlByRegion:T}},function(e,t,n){"use strict";function r(e,t){var n=new Error(t);return n.code=e,n}var i=n(0);i.extend(r,{OTHER_CAUSE:-1,INTERNAL_SERVER_ERROR:1,CONNECTION_FAILED:100,OBJECT_NOT_FOUND:101,INVALID_QUERY:102,INVALID_CLASS_NAME:103,MISSING_OBJECT_ID:104,INVALID_KEY_NAME:105,INVALID_POINTER:106,INVALID_JSON:107,COMMAND_UNAVAILABLE:108,NOT_INITIALIZED:109,INCORRECT_TYPE:111,INVALID_CHANNEL_NAME:112,PUSH_MISCONFIGURED:115,OBJECT_TOO_LARGE:116,OPERATION_FORBIDDEN:119,CACHE_MISS:120,INVALID_NESTED_KEY:121,INVALID_FILE_NAME:122,INVALID_ACL:123,TIMEOUT:124,INVALID_EMAIL_ADDRESS:125,MISSING_CONTENT_TYPE:126,MISSING_CONTENT_LENGTH:127,INVALID_CONTENT_LENGTH:128,FILE_TOO_LARGE:129,FILE_SAVE_ERROR:130,FILE_DELETE_ERROR:153,DUPLICATE_VALUE:137,INVALID_ROLE_NAME:139,EXCEEDED_QUOTA:140,SCRIPT_FAILED:141,VALIDATION_ERROR:142,INVALID_IMAGE_DATA:150,UNSAVED_FILE_ERROR:151,INVALID_PUSH_TIME_ERROR:152,USERNAME_MISSING:200,PASSWORD_MISSING:201,USERNAME_TAKEN:202,EMAIL_TAKEN:203,EMAIL_MISSING:204,EMAIL_NOT_FOUND:205,SESSION_MISSING:206,MUST_CREATE_USER_THROUGH_SIGNUP:207,ACCOUNT_ALREADY_LINKED:208,LINKED_ID_MISSING:250,INVALID_LINKED_SESSION:251,UNSUPPORTED_SERVICE:252,X_DOMAIN_REQUEST:602}),e.exports=r},function(e,t,n){"use strict";var r=n(0),i=function(e){return r.isNull(e)||r.isUndefined(e)},o=function(e){return r.isArray(e)?e:void 0===e||null===e?[]:[e]},s=function(e){return e.sessionToken?e.sessionToken:e.user&&"function"==typeof e.user.getSessionToken?e.user.getSessionToken():void 0},a=function(e){return function(t){return e(t),t}};e.exports={isNullOrUndefined:i,ensureArray:o,getSessionToken:s,tap:a}},function(e,t,n){function r(){return!("undefined"==typeof window||!window||"undefined"==typeof window.process||"renderer"!==window.process.type)||("undefined"!=typeof document&&document&&"WebkitAppearance"in document.documentElement.style||"undefined"!=typeof window&&window&&window.console&&(console.firebug||console.exception&&console.table)||"undefined"!=typeof navigator&&navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function i(e){var n=this.useColors;if(e[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+e[0]+(n?"%c ":" ")+"+"+t.humanize(this.diff),n){var r="color: "+this.color;e.splice(1,0,r,"color: inherit");var i=0,o=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,r)}}function o(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function s(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}}function a(){var e;try{e=t.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}function u(){try{return window.localStorage}catch(e){}}t=e.exports=n(51),t.log=o,t.formatArgs=i,t.save=s,t.load=a,t.useColors=r,t.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(a())},function(e,t,n){"use strict";(function(t){var r=n(0),i=n(42),o=n(4),s=o.isNullOrUndefined,a=t.AV||{};a._config=a._config||{};var u=a._config;r.extend(u,{region:"cn",APIServerURL:u.APIServerURL||"",disableCurrentUser:!1,userAgent:i,applicationProduction:null});var c=function(){},l=function(e,t,n){var i;return i=t&&t.hasOwnProperty("constructor")?t.constructor:function(){e.apply(this,arguments)},r.extend(i,e),c.prototype=e.prototype,i.prototype=new c,t&&r.extend(i.prototype,t),n&&r.extend(i,n),i.prototype.constructor=i,i.__super__=e.prototype,i};a.setProduction=function(e){s(e)?u.applicationProduction=null:u.applicationProduction=e?1:0},a._getAVPath=function(e){if(!a.applicationId)throw new Error("You need to call AV.initialize before using AV.");if(e||(e=""),!r.isString(e))throw new Error("Tried to get a localStorage path that wasn't a String.");return"/"===e[0]&&(e=e.substring(1)),"AV/"+a.applicationId+"/"+e},a._installationId=null,a._getInstallationId=function(){if(a._installationId)return a.Promise.resolve(a._installationId);var e=a._getAVPath("installationId");return a.localStorage.getItemAsync(e).then(function(t){if(a._installationId=t,a._installationId)return t;var n=function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)};return a._installationId=n()+n()+"-"+n()+"-"+n()+"-"+n()+"-"+n()+n()+n(),a.localStorage.setItemAsync(e,a._installationId)})},a._parseDate=function(e){var t=new RegExp("^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})T([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(.([0-9]+))?Z$"),n=t.exec(e);if(!n)return null;var r=n[1]||0,i=(n[2]||1)-1,o=n[3]||0,s=n[4]||0,a=n[5]||0,u=n[6]||0,c=n[8]||0;return new Date(Date.UTC(r,i,o,s,a,u,c))},a._extend=function(e,t){var n=l(this,e,t);return n.extend=this.extend,n},a._getValue=function(e,t){return e&&e[t]?r.isFunction(e[t])?e[t]():e[t]:null},a._encode=function(e,t,n){if(e instanceof a.Object){if(n)throw new Error("AV.Objects not allowed here");if(!t||r.include(t,e)||!e._hasData)return e._toPointer();if(!e.dirty())return t=t.concat(e),a._encode(e._toFullJSON(t),t,n);throw new Error("Tried to save an object with a pointer to a new, unsaved object.")}if(e instanceof a.ACL)return e.toJSON();if(r.isDate(e))return{__type:"Date",iso:e.toJSON()};if(e instanceof a.GeoPoint)return e.toJSON();if(r.isArray(e))return r.map(e,function(e){return a._encode(e,t,n)});if(r.isRegExp(e))return e.source;if(e instanceof a.Relation)return e.toJSON();if(e instanceof a.Op)return e.toJSON();if(e instanceof a.File){if(!e.url()&&!e.id)throw new Error("Tried to save an object containing an unsaved file.");return e._toFullJSON()}return r.isObject(e)?r.mapObject(e,function(e,r){return a._encode(e,t,n)}):e},a._decode=function(e,t){if(!r.isObject(e)||r.isDate(e))return e;if(r.isArray(e))return r.map(e,function(e){return a._decode(e)});if(e instanceof a.Object)return e;if(e instanceof a.File)return e;if(e instanceof a.Op)return e;if(e instanceof a.GeoPoint)return e;if(e instanceof a.ACL)return e;if("ACL"===t)return new a.ACL(e);if(e.__op)return a.Op._decode(e);var n;if("Pointer"===e.__type){n=e.className;var i=a.Object._create(n,void 0,void 0,!0);if(Object.keys(e).length>3){var o=r.clone(e);delete o.__type,delete o.className,i._finishFetch(o,!0)}else i._finishFetch({objectId:e.objectId},!1);return i}if("Object"===e.__type){n=e.className;var s=r.clone(e);delete s.__type,delete s.className;var u=a.Object._create(n,void 0,void 0,!0);return u._finishFetch(s,!0),u}if("Date"===e.__type)return a._parseDate(e.iso);if("GeoPoint"===e.__type)return new a.GeoPoint({latitude:e.latitude,longitude:e.longitude});if("Relation"===e.__type){if(!t)throw new Error("key missing decoding a Relation");var c=new a.Relation(null,t);return c.targetClassName=e.className,c}if("File"===e.__type){var l=new a.File(e.name),f=r.clone(e);return delete f.__type,l._finishFetch(f),l}return r.mapObject(e,a._decode)},a._encodeObjectOrArray=function(e){var t=function(e){return e&&e._toFullJSON&&(e=e._toFullJSON([])),r.mapObject(e,function(e){return a._encode(e,[])})};return r.isArray(e)?e.map(function(e){return t(e)}):t(e)},a._arrayEach=r.each,a._traverse=function(e,t,n){if(e instanceof a.Object){if(n=n||[],r.indexOf(n,e)>=0)return;return n.push(e),a._traverse(e.attributes,t,n),t(e)}return e instanceof a.Relation||e instanceof a.File?t(e):r.isArray(e)?(r.each(e,function(r,i){var o=a._traverse(r,t,n);o&&(e[i]=o)}),t(e)):r.isObject(e)?(a._each(e,function(r,i){var o=a._traverse(r,t,n);o&&(e[i]=o)}),t(e)):t(e)},a._objectEach=a._each=function(e,t){r.isObject(e)?r.each(r.keys(e),function(n){t(e[n],n)}):r.each(e,t)},e.exports=a}).call(t,n(8))},function(e,t,n){function r(){}function i(e){if(!_(e))return e;var t=[];for(var n in e)o(t,n,e[n]);return t.join("&")}function o(e,t,n){if(null!=n)if(Array.isArray(n))n.forEach(function(n){o(e,t,n)});else if(_(n))for(var r in n)o(e,t+"["+r+"]",n[r]);else e.push(encodeURIComponent(t)+"="+encodeURIComponent(n));else null===n&&e.push(encodeURIComponent(t))}function s(e){for(var t,n,r={},i=e.split("&"),o=0,s=i.length;o=0?"&":"?")+e),this._sort){var t=this.url.indexOf("?");if(t>=0){var n=this.url.substring(t+1).split("&");v(this._sort)?n.sort(this._sort):n.sort(),this.url=this.url.substring(0,t)+"?"+n.join("&")}}},l.prototype._isHost=function(e){return e&&"object"==typeof e&&!Array.isArray(e)&&"[object Object]"!==Object.prototype.toString.call(e)},l.prototype.end=function(e){return this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=e||r,this._appendQueryString(),this._end()},l.prototype._end=function(){var e=this,t=this.xhr=g.getXHR(),n=this._formData||this._data;this._setTimeouts(),t.onreadystatechange=function(){var n=t.readyState;if(n>=2&&e._responseTimeoutTimer&&clearTimeout(e._responseTimeoutTimer),4==n){var r;try{r=t.status}catch(e){r=0}if(!r){if(e.timedout||e._aborted)return;return e.crossDomainError()}e.emit("end")}};var r=function(t,n){n.total>0&&(n.percent=n.loaded/n.total*100),n.direction=t,e.emit("progress",n)};if(this.hasListeners("progress"))try{t.onprogress=r.bind(null,"download"),t.upload&&(t.upload.onprogress=r.bind(null,"upload"))}catch(e){}try{this.username&&this.password?t.open(this.method,this.url,!0,this.username,this.password):t.open(this.method,this.url,!0)}catch(e){return this.callback(e)}if(this._withCredentials&&(t.withCredentials=!0),!this._formData&&"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof n&&!this._isHost(n)){var i=this._header["content-type"],o=this._serializer||g.serialize[i?i.split(";")[0]:""];!o&&u(i)&&(o=g.serialize["application/json"]),o&&(n=o(n))}for(var s in this.header)null!=this.header[s]&&this.header.hasOwnProperty(s)&&t.setRequestHeader(s,this.header[s]);return this._responseType&&(t.responseType=this._responseType),this.emit("request",this),t.send("undefined"!=typeof n?n:null),this},g.get=function(e,t,n){var r=g("GET",e);return"function"==typeof t&&(n=t,t=null),t&&r.query(t),n&&r.end(n),r},g.head=function(e,t,n){var r=g("HEAD",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},g.options=function(e,t,n){var r=g("OPTIONS",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},g.del=f,g.delete=f,g.patch=function(e,t,n){var r=g("PATCH",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},g.post=function(e,t,n){var r=g("POST",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r},g.put=function(e,t,n){var r=g("PUT",e);return"function"==typeof t&&(n=t,t=null),t&&r.send(t),n&&r.end(n),r}},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=function(){function e(e,t){for(var n=0;n2&&void 0!==arguments[2])||arguments[2];if(this.readyState!==h)throw new Error("request is already opened");if(!n)throw new Error("sync request is not supported");this._method=e,this._url=t,this.readyState=d,this.dispatchEvent({type:"readystatechange"})}},{key:"setRequestHeader",value:function(e,t){if(this.readyState!==d)throw new Error("request is not opened");this._headers[e.toLowerCase()]=t}},{key:"send",value:function(e){var t=this;if(this.readyState!==d)throw new Error("request is not opened");if(e instanceof f){var n=e.entries(),i=n.filter(function(e){return"string"!=typeof e[1]});if(0===i.length)throw new Error("Must specify a Blob field in FormData");i.length>1&&console.warn("Only the first Blob will be send in Weapp");var o=n.filter(function(e){return"string"==typeof e[1]}).reduce(function(e,t){return c(e,r({},t[0],t[1]))},{});wx.uploadFile({url:this._url,name:i[0][0],filePath:i[0][1].uri,formData:o,header:this._headers,success:a.bind(this),fail:function(e){t.status=0,t.readyState=v,t.dispatchEvent({type:"readystatechange"}),t.dispatchEvent({type:"error"})}})}else wx.request({url:this._url,data:e||"",method:this._method.toUpperCase(),header:this._headers,success:a.bind(this),fail:function(e){t.status=0,t.readyState=v,t.dispatchEvent({type:"readystatechange"}),t.dispatchEvent({type:"error"})}})}}]),t}(l(y));c(m,{UNSENT:h,OPENED:d,HEADERS_RECEIVED:p,LOADING:_,DONE:v}),e.exports=m},function(e,t,n){"use strict";var r=n(17),i=n(6),o=t.removeAsync=r.removeItemAsync.bind(r),s=function(e,t){try{e=JSON.parse(e)}catch(e){return null}if(e){var n=e.expiredAt&&e.expiredAt0){for(var t=Array(arguments.length),n=0;n0&&void 0!==arguments[0]?arguments[0]:t||window;if("object"!==("undefined"==typeof e?"undefined":r(e)))throw new Error("polyfill target is not an Object");var n={localStorage:i,XMLHttpRequest:o,FormData:s,WebSocket:a,Object:Object,navigator:u};for(var c in n)e[c]||(e[c]=n[c])},localStorage:i,XMLHttpRequest:o,FormData:s,WebSocket:a}}).call(t,n(8))},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){var t="*";e.ACL=function(t){var n=this;if(n.permissionsById={},r.isObject(t))if(t instanceof e.User)n.setReadAccess(t,!0),n.setWriteAccess(t,!0);else{if(r.isFunction(t))throw new Error("AV.ACL() called with a function. Did you forget ()?");e._objectEach(t,function(t,i){if(!r.isString(i))throw new Error("Tried to create an ACL with an invalid userId.");n.permissionsById[i]={},e._objectEach(t,function(e,t){if("read"!==t&&"write"!==t)throw new Error("Tried to create an ACL with an invalid permission type.");if(!r.isBoolean(e))throw new Error("Tried to create an ACL with an invalid permission value.");n.permissionsById[i][t]=e})})}},e.ACL.prototype.toJSON=function(){return r.clone(this.permissionsById)},e.ACL.prototype._setAccess=function(t,n,i){if(n instanceof e.User?n=n.id:n instanceof e.Role&&(n="role:"+n.getName()),!r.isString(n))throw new Error("userId must be a string.");if(!r.isBoolean(i))throw new Error("allowed must be either true or false.");var o=this.permissionsById[n];if(!o){if(!i)return;o={},this.permissionsById[n]=o}i?this.permissionsById[n][t]=!0:(delete o[t],r.isEmpty(o)&&delete this.permissionsById[n])},e.ACL.prototype._getAccess=function(t,n){n instanceof e.User?n=n.id:n instanceof e.Role&&(n="role:"+n.getName());var r=this.permissionsById[n];return!!r&&!!r[t]},e.ACL.prototype.setReadAccess=function(e,t){this._setAccess("read",e,t)},e.ACL.prototype.getReadAccess=function(e){return this._getAccess("read",e)},e.ACL.prototype.setWriteAccess=function(e,t){this._setAccess("write",e,t)},e.ACL.prototype.getWriteAccess=function(e){return this._getAccess("write",e)},e.ACL.prototype.setPublicReadAccess=function(e){this.setReadAccess(t,e)},e.ACL.prototype.getPublicReadAccess=function(){return this.getReadAccess(t)},e.ACL.prototype.setPublicWriteAccess=function(e){this.setWriteAccess(t,e)},e.ACL.prototype.getPublicWriteAccess=function(){return this.getWriteAccess(t)},e.ACL.prototype.getRoleReadAccess=function(t){if(t instanceof e.Role&&(t=t.getName()),r.isString(t))return this.getReadAccess("role:"+t);throw new Error("role must be a AV.Role or a String")},e.ACL.prototype.getRoleWriteAccess=function(t){if(t instanceof e.Role&&(t=t.getName()),r.isString(t))return this.getWriteAccess("role:"+t);throw new Error("role must be a AV.Role or a String")},e.ACL.prototype.setRoleReadAccess=function(t,n){if(t instanceof e.Role&&(t=t.getName()),r.isString(t))return void this.setReadAccess("role:"+t,n);throw new Error("role must be a AV.Role or a String")},e.ACL.prototype.setRoleWriteAccess=function(t,n){if(t instanceof e.Role&&(t=t.getName()),r.isString(t))return void this.setWriteAccess("role:"+t,n);throw new Error("role must be a AV.Role or a String")}}},function(e,t,n){"use strict";var r=n(0),i=n(2).request;e.exports=function(e){e.Cloud=e.Cloud||{},r.extend(e.Cloud,{run:function(t,n,r){var o=i("functions",t,null,"POST",e._encode(n,null,!0),r);return o.then(function(t){return e._decode(t).result})},rpc:function(t,n,o){return r.isArray(n)?Promise.reject(new Error("Can't pass Array as the param of rpc function in JavaScript SDK.")):i("call",t,null,"POST",e._encodeObjectOrArray(n),o).then(function(t){return e._decode(t).result})},getServerDate:function(){var t=i("date",null,null,"GET");return t.then(function(t){return e._decode(t)})},requestSmsCode:function(e){if(r.isString(e)&&(e={mobilePhoneNumber:e}),!e.mobilePhoneNumber)throw new Error("Missing mobilePhoneNumber.");var t=i("requestSmsCode",null,null,"POST",e);return t},verifySmsCode:function(e,t){if(!e)throw new Error("Missing sms code.");var n={};r.isString(t)&&(n.mobilePhoneNumber=t);var o=i("verifySmsCode",e,null,"POST",n);return o}})}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){var t=/\s+/,n=Array.prototype.slice;e.Events={on:function(e,n,r){var i,o,s,a,u;if(!n)return this;for(e=e.split(t),i=this._callbacks||(this._callbacks={}),o=e.shift();o;)u=i[o],s=u?u.tail:{},s.next=a={},s.context=r,s.callback=n,i[o]={tail:a,next:u?u.next:s},o=e.shift();return this},off:function(e,n,i){var o,s,a,u,c,l;if(s=this._callbacks){if(!(e||n||i))return delete this._callbacks,this;for(e=e?e.split(t):r.keys(s),o=e.shift();o;)if(a=s[o],delete s[o],a&&(n||i)){for(u=a.tail,a=a.next;a!==u;)c=a.callback,l=a.context,(n&&c!==n||i&&l!==i)&&this.on(o,c,l),a=a.next;o=e.shift()}return this}},trigger:function(e){var r,i,o,s,a,u,c;if(!(o=this._callbacks))return this;for(u=o.all,e=e.split(t),c=n.call(arguments,1),r=e.shift();r;){if(i=o[r])for(s=i.tail;(i=i.next)!==s;)i.callback.apply(i.context||this,c);if(i=u)for(s=i.tail,a=[r].concat(c);(i=i.next)!==s;)i.callback.apply(i.context||this,a);r=e.shift()}return this}},e.Events.bind=e.Events.on,e.Events.unbind=e.Events.off}},function(e,t,n){"use strict";var r=n(0),i=n(43),o=n(44),s=n(45),a=n(3),u=n(2).request,c=n(1),l=n(4),f=l.tap,h=n(5)("leancloud:file"),d=n(48);e.exports=function(e){var t=(e._config,function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}),n=function(e){return e.match(/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/)[4]},l=function(e){if(e<26)return String.fromCharCode(65+e);if(e<52)return String.fromCharCode(97+(e-26));if(e<62)return String.fromCharCode(48+(e-52));if(62===e)return"+";if(63===e)return"/";throw new Error("Tried to encode large digit "+e+" in base64.")},p=function(e){var t=[];return t.length=Math.ceil(e.length/3),r.times(t.length,function(n){var r=e[3*n],i=e[3*n+1]||0,o=e[3*n+2]||0,s=3*n+1>2&63),l(r<<4&48|i>>4&15),s?l(i<<2&60|o>>6&3):"=",a?l(63&o):"="].join("")}),t.join("")};e.File=function(t,n,i){if(this.attributes={name:t,url:"",metaData:{},base64:""},r.isString(n))throw new TypeError("Creating an AV.File from a String is not yet supported.");r.isArray(n)&&(this.attributes.metaData.size=n.length,n={base64:p(n)}),this._extName="",this._data=n;var o=void 0;if(n&&n.owner)o=n.owner;else if(!e._config.disableCurrentUser)try{o=e.User.current()}catch(e){if("SYNC_API_NOT_AVAILABLE"!==e.code)throw e;console.warn("Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().")}this.attributes.metaData.owner=o?o.id:"unknown",this.set("mime_type",i)},e.File.withURL=function(t,n,r,i){if(!t||!n)throw new Error("Please provide file name and url");var o=new e.File(t,null,i);if(r)for(var s in r)o.attributes.metaData[s]||(o.attributes.metaData[s]=r[s]);return o.attributes.url=n,o.attributes.metaData.__source="external",o},e.File.createWithoutData=function(t){var n=new e.File;return n.id=t,n},e.File.prototype={className:"_File",_toFullJSON:function(t){var n=this,i=r.clone(this.attributes);return e._objectEach(i,function(n,r){i[r]=e._encode(n,t)}),e._objectEach(this._operations,function(e,t){i[t]=e}),r.has(this,"id")&&(i.objectId=this.id),r(["createdAt","updatedAt"]).each(function(e){if(r.has(n,e)){var t=n[e];i[e]=r.isDate(t)?t.toJSON():t}}),i.__type="File",i},toJSON:function(){var e=this._toFullJSON();return r.has(this,"id")&&(e.id=this.id),e},getACL:function(){return this._acl},setACL:function(t){return t instanceof e.ACL?void(this._acl=t):new a(a.OTHER_CAUSE,"ACL must be a AV.ACL.")},name:function(){return this.get("name")},url:function(){return this.get("url")},get:function(e){switch(e){case"objectId":return this.id;case"url":case"name":case"mime_type":case"metaData":case"createdAt":case"updatedAt":return this.attributes[e];default:return this.attributes.metaData[e]}},set:function e(){for(var t=this,e=function(e,n){switch(e){case"name":case"url":case"mime_type":case"base64":case"metaData":t.attributes[e]=n;break;default:t.attributes.metaData[e]=n}},n=arguments.length,r=Array(n),i=0;i100)throw new Error("Invalid quality value.");i=i||"png";var s=r?2:1;return o+"?imageView/"+s+"/w/"+e+"/h/"+t+"/q/"+n+"/format/"+i},size:function(){return this.metaData().size},ownerId:function(){return this.metaData().owner},destroy:function(e){if(!this.id)return c.reject(new Error("The file id is not eixsts."));var t=u("files",null,this.id,"DELETE",null,e);return t},_fileToken:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"fileTokens",i=this.attributes.name,o=n(i);!o&&this._extName&&(i+=this._extName,o=this._extName);var s=t()+t()+t()+t()+t()+o,a={key:s,name:i,ACL:this._acl,mime_type:e,metaData:this.attributes.metaData};return this._qiniu_key=s,u(r,null,null,"POST",a)},save:function(e){var t=this;if(this.id)throw new Error("File already saved. If you want to manipulate a file, use AV.Query to get it.");if(!this._previousSave)if(this._data){var r=this.get("mime_type");this._previousSave=this._fileToken(r).then(function(a){return a.mime_type&&(r=a.mime_type,t.set("mime_type",r)),t._token=a.token,c.resolve().then(function(){var e=t._data;if(e&&e.base64)return d(e.base64,r);if(e&&e.blob)return!e.blob.type&&r&&(e.blob.type=r),e.blob.name||(e.blob.name=t.get("name")),t._extName=n(e.blob.uri),e.blob;if("undefined"!=typeof File&&e instanceof File)return e.size&&(t.attributes.metaData.size=e.size),e.name&&(t._extName=n(e.name)),e;if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return t.attributes.metaData.size=e.length,e;throw new TypeError("malformed file data")}).then(function(n){var r=void 0;switch(a.provider){case"s3":r=s(a,n,t,e);break;case"qcloud":r=i(a,n,t,e);break;case"qiniu":default:r=o(a,n,t,e)}return r.then(f(function(){return t._callback(!0)}),function(e){throw t._callback(!1),e})})})}else if(this.attributes.url&&"external"===this.attributes.metaData.__source){var a={name:this.attributes.name,ACL:this._acl,metaData:this.attributes.metaData,mime_type:this.mimeType,url:this.attributes.url};this._previousSave=u("files",this.attributes.name,null,"post",a).then(function(e){return t.attributes.name=e.name,t.attributes.url=e.url,t.id=e.objectId,e.size&&(t.attributes.metaData.size=e.size),t})}return this._previousSave},_callback:function(e){u("fileCallback",null,null,"post",{token:this._token,result:e}).catch(h),delete this._token,delete this._data},fetch:function(e){var e=null,t=u("files",null,this.id,"GET",e);return t.then(this._finishFetch.bind(this))},_finishFetch:function(t){var n=e.Object.prototype.parse(t);return n.attributes={name:n.name,url:n.url,mime_type:n.mime_type,bucket:n.bucket},n.attributes.metaData=n.metaData||{},n.id=n.objectId,delete n.objectId,delete n.metaData,delete n.url,delete n.name,delete n.mime_type,delete n.bucket,r.extend(this,n),this}}}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){e.GeoPoint=function(t,n){r.isArray(t)?(e.GeoPoint._validate(t[0],t[1]),this.latitude=t[0],this.longitude=t[1]):r.isObject(t)?(e.GeoPoint._validate(t.latitude,t.longitude),this.latitude=t.latitude,this.longitude=t.longitude):r.isNumber(t)&&r.isNumber(n)?(e.GeoPoint._validate(t,n),this.latitude=t,this.longitude=n):(this.latitude=0,this.longitude=0);var i=this;this.__defineGetter__&&this.__defineSetter__&&(this._latitude=this.latitude,this._longitude=this.longitude,this.__defineGetter__("latitude",function(){return i._latitude}),this.__defineGetter__("longitude",function(){return i._longitude}),this.__defineSetter__("latitude",function(t){e.GeoPoint._validate(t,i.longitude),i._latitude=t}),this.__defineSetter__("longitude",function(t){e.GeoPoint._validate(i.latitude,t),i._longitude=t}))},e.GeoPoint._validate=function(e,t){if(e<-90)throw new Error("AV.GeoPoint latitude "+e+" < -90.0.");if(e>90)throw new Error("AV.GeoPoint latitude "+e+" > 90.0.");if(t<-180)throw new Error("AV.GeoPoint longitude "+t+" < -180.0.");if(t>180)throw new Error("AV.GeoPoint longitude "+t+" > 180.0.")},e.GeoPoint.current=function(){return new e.Promise(function(t,n){navigator.geolocation.getCurrentPosition(function(n){t(new e.GeoPoint({latitude:n.coords.latitude,longitude:n.coords.longitude}))},n)})},e.GeoPoint.prototype={toJSON:function(){return e.GeoPoint._validate(this.latitude,this.longitude),{__type:"GeoPoint",latitude:this.latitude,longitude:this.longitude}},radiansTo:function(e){var t=Math.PI/180,n=this.latitude*t,r=this.longitude*t,i=e.latitude*t,o=e.longitude*t,s=n-i,a=r-o,u=Math.sin(s/2),c=Math.sin(a/2),l=u*u+Math.cos(n)*Math.cos(i)*c*c; +return l=Math.min(1,l),2*Math.asin(Math.sqrt(l))},kilometersTo:function(e){return 6371*this.radiansTo(e)},milesTo:function(e){return 3958.8*this.radiansTo(e)}}}},function(e,t,n){"use strict";n(22),e.exports=n(23)},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=n(6),o=n(2),s=function(e,t,n,r){i.applicationId&&e!==i.applicationId&&t!==i.applicationKey&&n!==i.masterKey&&console.warn("LeanCloud SDK is already initialized, please do not reinitialize it."),i.applicationId=e,i.applicationKey=t,i.masterKey=n,i._useMasterKey=!1},a=function(){console.warn("MasterKey is not supposed to be used in browser.")};i.init=function(){if(1===arguments.length){var e=arguments.length<=0?void 0:arguments[0];if("object"!==("undefined"==typeof e?"undefined":r(e)))throw new Error("AV.init(): Parameter is not correct.");e.masterKey&&a(),s(e.appId,e.appKey,e.masterKey,e.hookKey),o.setServerUrlByRegion(e.region)}else(arguments.length<=3?void 0:arguments[3])&&a(),s.apply(void 0,arguments),o.setServerUrlByRegion("cn")},i.initialize=i.init},function(e,t,n){"use strict";var r=n(0),i=n(3),o=n(2).request;e.exports=function(e){e.Insight=e.Insight||{},r.extend(e.Insight,{startJob:function(t,n){if(!t||!t.sql)throw new Error("Please provide the sql to run the job.");var r={jobConfig:t,appId:e.applicationId},i=o("bigquery","jobs",null,"POST",e._encode(r,null,!0),n);return i.then(function(t){return e._decode(t).id})},on:function(e,t){}}),e.Insight.JobQuery=function(e,t){if(!e)throw new Error("Please provide the job id.");this.id=e,this.className=t,this._skip=0,this._limit=100},e.Insight.JobQuery.prototype={skip:function(e){return this._skip=e,this},limit:function(e){return this._limit=e,this},find:function(t){var n={skip:this._skip,limit:this._limit},r=o("bigquery","jobs",this.id,"GET",n,t);return r.then(function(t){return t.error?e.Promise.reject(new i(t.code,t.error)):e.Promise.resolve(t)})}}}},function(e,t,n){"use strict";var r=n(0),i=n(3),o=n(2).request,s=n(4),a=["objectId","createdAt","updatedAt"],u=function(e){if(a.indexOf(e)!==-1)throw new Error("key["+e+"] is reserved")};e.exports=function(e){e.Object=function(t,n){if(r.isString(t))return e.Object._create.apply(this,arguments);t=t||{},n&&n.parse&&(t=this.parse(t),t=this._mergeMagicFields(t));var i=e._getValue(this,"defaults");i&&(t=r.extend({},i,t)),n&&n.collection&&(this.collection=n.collection),this._serverData={},this._opSetQueue=[{}],this._flags={},this.attributes={},this._hashedJSON={},this._escapedAttributes={},this.cid=r.uniqueId("c"),this.changed={},this._silent={},this._pending={},this.set(t,{silent:!0}),this.changed={},this._silent={},this._pending={},this._hasData=!0,this._previousAttributes=r.clone(this.attributes),this.initialize.apply(this,arguments)},e.Object.saveAll=function(t,n){return e.Object._deepSaveAsync(t,null,n)},e.Object.fetchAll=function(t,n){return e.Promise.resolve().then(function(){return o("batch",null,null,"POST",{requests:r.map(t,function(e){if(!e.className)throw new Error("object must have className to fetch");if(!e.id)throw new Error("object must have id to fetch");if(e.dirty())throw new Error("object is modified but not saved");return{method:"GET",path:"/1.1/classes/"+e.className+"/"+e.id}})},n)}).then(function(e){return r.forEach(t,function(t,n){if(!e[n].success){var r=new Error(e[n].error.error);throw r.code=e[n].error.code,r}t._finishFetch(t.parse(e[n].success))}),t})},r.extend(e.Object.prototype,e.Events,{_fetchWhenSave:!1,initialize:function(){},fetchWhenSave:function(e){if(console.warn("AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead."),!r.isBoolean(e))throw new Error("Expect boolean value for fetchWhenSave");this._fetchWhenSave=e},getObjectId:function(){return this.id},getCreatedAt:function(){return this.createdAt||this.get("createdAt")},getUpdatedAt:function(){return this.updatedAt||this.get("updatedAt")},toJSON:function(){var t=this._toFullJSON();return e._arrayEach(["__type","className"],function(e){delete t[e]}),t},_toFullJSON:function(t){var n=this,i=r.clone(this.attributes);return e._objectEach(i,function(n,r){i[r]=e._encode(n,t)}),e._objectEach(this._operations,function(e,t){i[t]=e}),r.has(this,"id")&&(i.objectId=this.id),r(["createdAt","updatedAt"]).each(function(e){if(r.has(n,e)){var t=n[e];i[e]=r.isDate(t)?t.toJSON():t}}),i.__type="Object",i.className=this.className,i},_refreshCache:function(){var t=this;t._refreshingCache||(t._refreshingCache=!0,e._objectEach(this.attributes,function(n,i){n instanceof e.Object?n._refreshCache():r.isObject(n)&&t._resetCacheForKey(i)&&t.set(i,new e.Op.Set(n),{silent:!0})}),delete t._refreshingCache)},dirty:function(e){this._refreshCache();var t=r.last(this._opSetQueue);return e?!!t[e]:!this.id||r.keys(t).length>0},_toPointer:function(){return{__type:"Pointer",className:this.className,objectId:this.id}},get:function(e){switch(e){case"objectId":return this.id;case"createdAt":case"updatedAt":return this[e];default:return this.attributes[e]}},relation:function(t){var n=this.get(t);if(n){if(!(n instanceof e.Relation))throw new Error("Called relation() on non-relation field "+t);return n._ensureParentAndKey(this,t),n}return new e.Relation(this,t)},escape:function(e){var t=this._escapedAttributes[e];if(t)return t;var n,i=this.attributes[e];return n=s.isNullOrUndefined(i)?"":r.escape(i.toString()),this._escapedAttributes[e]=n,n},has:function(e){return!s.isNullOrUndefined(this.attributes[e])},_mergeMagicFields:function(t){var n=this,i=["objectId","createdAt","updatedAt"];return e._arrayEach(i,function(i){t[i]&&("objectId"===i?n.id=t[i]:"createdAt"!==i&&"updatedAt"!==i||r.isDate(t[i])?n[i]=t[i]:n[i]=e._parseDate(t[i]),delete t[i])}),t},_startSave:function(){this._opSetQueue.push({})},_cancelSave:function(){var t=r.first(this._opSetQueue);this._opSetQueue=r.rest(this._opSetQueue);var n=r.first(this._opSetQueue);e._objectEach(t,function(e,r){var i=t[r],o=n[r];i&&o?n[r]=o._mergeWithPrevious(i):i&&(n[r]=i)}),this._saving=this._saving-1},_finishSave:function(t){var n={};e._traverse(this.attributes,function(t){t instanceof e.Object&&t.id&&t._hasData&&(n[t.id]=t)});var i=r.first(this._opSetQueue);this._opSetQueue=r.rest(this._opSetQueue),this._applyOpSet(i,this._serverData),this._mergeMagicFields(t);var o=this;e._objectEach(t,function(t,r){o._serverData[r]=e._decode(t,r);var i=e._traverse(o._serverData[r],function(t){if(t instanceof e.Object&&n[t.id])return n[t.id]});i&&(o._serverData[r]=i)}),this._rebuildAllEstimatedData(),this._saving=this._saving-1},_finishFetch:function(t,n){this._opSetQueue=[{}],this._mergeMagicFields(t);var r=this;e._objectEach(t,function(t,n){r._serverData[n]=e._decode(t,n)}),this._rebuildAllEstimatedData(),this._refreshCache(),this._opSetQueue=[{}],this._hasData=n},_applyOpSet:function(t,n){var r=this;e._objectEach(t,function(t,i){n[i]=t._estimate(n[i],r,i),n[i]===e.Op._UNSET&&delete n[i]})},_resetCacheForKey:function(t){var n=this.attributes[t];if(r.isObject(n)&&!(n instanceof e.Object)&&!(n instanceof e.File)){n=n.toJSON?n.toJSON():n;var i=JSON.stringify(n);if(this._hashedJSON[t]!==i){var o=!!this._hashedJSON[t];return this._hashedJSON[t]=i,o}}return!1},_rebuildEstimatedDataForKey:function(t){var n=this;delete this.attributes[t],this._serverData[t]&&(this.attributes[t]=this._serverData[t]),e._arrayEach(this._opSetQueue,function(r){var i=r[t];i&&(n.attributes[t]=i._estimate(n.attributes[t],n,t),n.attributes[t]===e.Op._UNSET?delete n.attributes[t]:n._resetCacheForKey(t))})},_rebuildAllEstimatedData:function(){var t=this,n=r.clone(this.attributes);this.attributes=r.clone(this._serverData),e._arrayEach(this._opSetQueue,function(n){t._applyOpSet(n,t.attributes),e._objectEach(n,function(e,n){t._resetCacheForKey(n)})}),e._objectEach(n,function(e,n){t.attributes[n]!==e&&t.trigger("change:"+n,t,t.attributes[n],{})}),e._objectEach(this.attributes,function(e,i){r.has(n,i)||t.trigger("change:"+i,t,e,{})})},set:function(t,n,i){var o;if(r.isObject(t)||s.isNullOrUndefined(t)?(o=r.mapObject(t,function(t,n){return u(n),e._decode(t,n)}),i=n):(o={},u(t),o[t]=e._decode(n,t)),i=i||{},!o)return this;o instanceof e.Object&&(o=o.attributes),i.unset&&e._objectEach(o,function(t,n){o[n]=new e.Op.Unset});var a=r.clone(o),c=this;e._objectEach(a,function(t,n){t instanceof e.Op&&(a[n]=t._estimate(c.attributes[n],c,n),a[n]===e.Op._UNSET&&delete a[n])}),this._validate(o,i),i.changes={};var l=this._escapedAttributes;this._previousAttributes||{};return e._arrayEach(r.keys(o),function(t){var n=o[t];n instanceof e.Relation&&(n.parent=c),n instanceof e.Op||(n=new e.Op.Set(n));var s=!0;n instanceof e.Op.Set&&r.isEqual(c.attributes[t],n.value)&&(s=!1),s&&(delete l[t],i.silent?c._silent[t]=!0:i.changes[t]=!0);var a=r.last(c._opSetQueue);a[t]=n._mergeWithPrevious(a[t]),c._rebuildEstimatedDataForKey(t),s?(c.changed[t]=c.attributes[t],i.silent||(c._pending[t]=!0)):(delete c.changed[t],delete c._pending[t])}),i.silent||this.change(i),this},unset:function(e,t){return t=t||{},t.unset=!0,this.set(e,null,t)},increment:function(t,n){return(r.isUndefined(n)||r.isNull(n))&&(n=1),this.set(t,new e.Op.Increment(n))},add:function(t,n){return this.set(t,new e.Op.Add(s.ensureArray(n)))},addUnique:function(t,n){return this.set(t,new e.Op.AddUnique(s.ensureArray(n)))},remove:function(t,n){return this.set(t,new e.Op.Remove(s.ensureArray(n)))},op:function(e){return r.last(this._opSetQueue)[e]},clear:function(e){e=e||{},e.unset=!0;var t=r.extend(this.attributes,this._operations);return this.set(t,e)},_getSaveJSON:function(){var t=r.clone(r.first(this._opSetQueue));return e._objectEach(t,function(e,n){t[n]=e.toJSON()}),t},_canBeSerialized:function(){return e.Object._canBeSerializedAsValue(this.attributes)},fetch:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];r.isArray(e.keys)&&(e.keys=e.keys.join(",")),r.isArray(e.include)&&(e.include=e.include.join(","));var n=this,i=o("classes",this.className,this.id,"GET",e,t);return i.then(function(e){return n._finishFetch(n.parse(e),!0),n})},save:function(t,n,i){var a,u,c;r.isObject(t)||s.isNullOrUndefined(t)?(a=t,c=n):(a={},a[t]=n,c=i),c=r.clone(c)||{},c.wait&&(u=r.clone(this.attributes));var l=r.clone(c)||{};l.wait&&(l.silent=!0),a&&this.set(a,l);var f=this;f._refreshCache();var h=[],d=[];return e.Object._findUnsavedChildren(f.attributes,h,d),h.length+d.length>0?e.Object._deepSaveAsync(this.attributes,f,c).then(function(){return f.save(null,c)}):(this._startSave(),this._saving=(this._saving||0)+1,this._allPreviousSaves=this._allPreviousSaves||e.Promise.resolve(),this._allPreviousSaves=this._allPreviousSaves.catch(function(e){}).then(function(){var e=f.id?"PUT":"POST",t=f._getSaveJSON();if(f._fetchWhenSave&&(t._fetchWhenSave=!0),c.fetchWhenSave&&(t._fetchWhenSave=!0),c.query){var n;if("function"==typeof c.query.toJSON&&(n=c.query.toJSON(),n&&(t._where=n.where)),!t._where){var i=new Error("options.query is not an AV.Query");throw i}}r.extend(t,f._flags);var s="classes",h=f.className;"_User"!==f.className||f.id||(s="users",h=null);var d=c._makeRequest||o,p=d(s,h,f.id,e,t,c);return p=p.then(function(e){var t=f.parse(e);return c.wait&&(t=r.extend(a||{},t)),f._finishSave(t),c.wait&&f.set(u,l),f},function(e){throw f._cancelSave(),e})}),this._allPreviousSaves)},destroy:function(e){e=e||{};var t=this,n=function(){t.trigger("destroy",t,t.collection,e)};if(!this.id)return n();e.wait||n();var r=o("classes",this.className,this.id,"DELETE",this._flags,e);return r.then(function(){return e.wait&&n(),t})},parse:function(t){var n=r.clone(t);return r(["createdAt","updatedAt"]).each(function(t){n[t]&&(n[t]=e._parseDate(n[t]))}),n.updatedAt||(n.updatedAt=n.createdAt),n},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.id},change:function(t){t=t||{};var n=this._changing;this._changing=!0;var i=this;e._objectEach(this._silent,function(e){i._pending[e]=!0});var o=r.extend({},t.changes,this._silent);if(this._silent={},e._objectEach(o,function(e,n){i.trigger("change:"+n,i,i.get(n),t)}),n)return this;for(var s=function(e,t){i._pending[t]||i._silent[t]||delete i.changed[t]};!r.isEmpty(this._pending);)this._pending={},this.trigger("change",this,t),e._objectEach(this.changed,s),i._previousAttributes=r.clone(this.attributes);return this._changing=!1,this},hasChanged:function(e){return arguments.length?this.changed&&r.has(this.changed,e):!r.isEmpty(this.changed)},changedAttributes:function(t){if(!t)return!!this.hasChanged()&&r.clone(this.changed);var n={},i=this._previousAttributes;return e._objectEach(t,function(e,t){r.isEqual(i[t],e)||(n[t]=e)}),n},previous:function(e){return arguments.length&&this._previousAttributes?this._previousAttributes[e]:null},previousAttributes:function(){return r.clone(this._previousAttributes)},isValid:function(){try{this.validate(this.attributes)}catch(e){return!1}return!0},validate:function(t){if(r.has(t,"ACL")&&!(t.ACL instanceof e.ACL))throw new i(i.OTHER_CAUSE,"ACL must be a AV.ACL.")},_validate:function(e,t){!t.silent&&this.validate&&(e=r.extend({},this.attributes,e),this.validate(e))},getACL:function(){return this.get("ACL")},setACL:function(e,t){return this.set("ACL",e,t)},disableBeforeHook:function(){this.ignoreHook("beforeSave"),this.ignoreHook("beforeUpdate"),this.ignoreHook("beforeDelete")},disableAfterHook:function(){this.ignoreHook("afterSave"),this.ignoreHook("afterUpdate"),this.ignoreHook("afterDelete")},ignoreHook:function(t){r.contains(["beforeSave","afterSave","beforeUpdate","afterUpdate","beforeDelete","afterDelete"],t)||console.trace("Unsupported hookName: "+t),e.hookKey||console.trace("ignoreHook required hookKey"),this._flags.__ignore_hooks||(this._flags.__ignore_hooks=[]),this._flags.__ignore_hooks.push(t)}}),e.Object.createWithoutData=function(t,n,r){var i=e.Object._create(t,void 0,void 0,!0);return i.id=n,i._hasData=r,i},e.Object.destroyAll=function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!t||0===t.length)return e.Promise.resolve();var i=r.groupBy(t,function(e){return JSON.stringify({className:e.className,flags:e._flags})}),s={requests:r.map(i,function(e){var t=r.map(e,"id").join(",");return{method:"DELETE",path:"/1.1/classes/"+e[0].className+"/"+t,body:e[0]._flags}})};return o("batch",null,null,"POST",s,n)},e.Object._getSubclass=function(t){if(!r.isString(t))throw new Error("AV.Object._getSubclass requires a string argument.");var n=e.Object._classMap[t];return n||(n=e.Object.extend(t),e.Object._classMap[t]=n),n},e.Object._create=function(t,n,r,i){var o=e.Object._getSubclass(t);return new o(n,r,i)},e.Object._classMap={},e.Object._extend=e._extend,e.Object.new=function(t,n){return new e.Object(t,n)},e.Object.extend=function(t,n,i){if(!r.isString(t)){if(t&&r.has(t,"className"))return e.Object.extend(t.className,t,n);throw new Error("AV.Object.extend's first argument should be the className.")}"User"===t&&(t="_User");var o=null;if(r.has(e.Object._classMap,t)){var s=e.Object._classMap[t];if(!n&&!i)return s;o=s._extend(n,i)}else n=n||{},n._className=t,o=this._extend(n,i);return o.extend=function(n){if(r.isString(n)||n&&r.has(n,"className"))return e.Object.extend.apply(o,arguments);var i=[t].concat(r.toArray(arguments));return e.Object.extend.apply(o,i)},o.new=function(e,t){return new o(e,t)},e.Object._classMap[t]=o,o},Object.defineProperty(e.Object.prototype,"className",{get:function(){var e=this._className||this.constructor._LCClassName||this.constructor.name;return"User"===e?"_User":e}}),e.Object.register=function(t,n){if(!(t.prototype instanceof e.Object))throw new Error("registered class is not a subclass of AV.Object");var r=n||t.name;if(!r.length)throw new Error("registered class must be named");n&&(t._LCClassName=n),e.Object._classMap[r]=t},e.Object._findUnsavedChildren=function(t,n,r){e._traverse(t,function(t){return t instanceof e.Object?(t._refreshCache(),void(t.dirty()&&n.push(t))):t instanceof e.File?void(t.url()||t.id||r.push(t)):void 0})},e.Object._canBeSerializedAsValue=function(t){var n=!0;return t instanceof e.Object||t instanceof e.File?n=!!t.id:r.isArray(t)?e._arrayEach(t,function(t){e.Object._canBeSerializedAsValue(t)||(n=!1)}):r.isObject(t)&&e._objectEach(t,function(t){e.Object._canBeSerializedAsValue(t)||(n=!1)}),n},e.Object._deepSaveAsync=function(t,n,s){var a=[],u=[];e.Object._findUnsavedChildren(t,a,u),n&&(a=r.filter(a,function(e){return e!=n}));var c=e.Promise.resolve();r.each(u,function(e){c=c.then(function(){return e.save()})});var l=r.uniq(a),f=r.uniq(l);return c.then(function(){return e.Promise._continueWhile(function(){return f.length>0},function(){var t=[],n=[];if(e._arrayEach(f,function(e){return t.length>20?void n.push(e):void(e._canBeSerialized()?t.push(e):n.push(e))}),f=n,0===t.length)return e.Promise.reject(new i(i.OTHER_CAUSE,"Tried to save a batch with a cycle."));var a=e.Promise.resolve(r.map(t,function(t){return t._allPreviousSaves||e.Promise.resolve()})),u=a.then(function(){return o("batch",null,null,"POST",{requests:r.map(t,function(e){var t=e._getSaveJSON();r.extend(t,e._flags);var n="POST",i="/1.1/classes/"+e.className;return e.id&&(i=i+"/"+e.id,n="PUT"),e._startSave(),{method:n,path:i,body:t}})},s).then(function(n){var r;if(e._arrayEach(t,function(e,t){n[t].success?e._finishSave(e.parse(n[t].success)):(r=r||n[t].error,e._cancelSave())}),r)return e.Promise.reject(new i(r.code,r.error))})});return e._arrayEach(t,function(e){e._allPreviousSaves=u}),u})}).then(function(){return t})}}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){e.Op=function(){this._initialize.apply(this,arguments)},e.Op.prototype={_initialize:function(){}},r.extend(e.Op,{_extend:e._extend,_opDecoderMap:{},_registerDecoder:function(t,n){e.Op._opDecoderMap[t]=n},_decode:function(t){var n=e.Op._opDecoderMap[t.__op];return n?n(t):void 0}}),e.Op._registerDecoder("Batch",function(t){var n=null;return e._arrayEach(t.ops,function(t){t=e.Op._decode(t),n=t._mergeWithPrevious(n)}),n}),e.Op.Set=e.Op._extend({_initialize:function(e){this._value=e},value:function(){return this._value},toJSON:function(){return e._encode(this.value())},_mergeWithPrevious:function(e){return this},_estimate:function(e){return this.value()}}),e.Op._UNSET={},e.Op.Unset=e.Op._extend({toJSON:function(){return{__op:"Delete"}},_mergeWithPrevious:function(e){return this},_estimate:function(t){return e.Op._UNSET}}),e.Op._registerDecoder("Delete",function(t){return new e.Op.Unset}),e.Op.Increment=e.Op._extend({_initialize:function(e){this._amount=e},amount:function(){return this._amount},toJSON:function(){return{__op:"Increment",amount:this._amount}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)return new e.Op.Set(this.amount());if(t instanceof e.Op.Set)return new e.Op.Set(t.value()+this.amount());if(t instanceof e.Op.Increment)return new e.Op.Increment(this.amount()+t.amount());throw new Error("Op is invalid after previous op.")}return this},_estimate:function(e){return e?e+this.amount():this.amount()}}),e.Op._registerDecoder("Increment",function(t){return new e.Op.Increment(t.amount)}),e.Op.Add=e.Op._extend({_initialize:function(e){this._objects=e},objects:function(){return this._objects},toJSON:function(){return{__op:"Add",objects:e._encode(this.objects())}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)return new e.Op.Set(this.objects());if(t instanceof e.Op.Set)return new e.Op.Set(this._estimate(t.value()));if(t instanceof e.Op.Add)return new e.Op.Add(t.objects().concat(this.objects()));throw new Error("Op is invalid after previous op.")}return this},_estimate:function(e){return e?e.concat(this.objects()):r.clone(this.objects())}}),e.Op._registerDecoder("Add",function(t){return new e.Op.Add(e._decode(t.objects))}),e.Op.AddUnique=e.Op._extend({_initialize:function(e){this._objects=r.uniq(e)},objects:function(){return this._objects},toJSON:function(){return{__op:"AddUnique",objects:e._encode(this.objects())}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)return new e.Op.Set(this.objects());if(t instanceof e.Op.Set)return new e.Op.Set(this._estimate(t.value()));if(t instanceof e.Op.AddUnique)return new e.Op.AddUnique(this._estimate(t.objects()));throw new Error("Op is invalid after previous op.")}return this},_estimate:function(t){if(t){var n=r.clone(t);return e._arrayEach(this.objects(),function(t){if(t instanceof e.Object&&t.id){var i=r.find(n,function(n){return n instanceof e.Object&&n.id===t.id});if(i){var o=r.indexOf(n,i);n[o]=t}else n.push(t)}else r.contains(n,t)||n.push(t)}),n}return r.clone(this.objects())}}),e.Op._registerDecoder("AddUnique",function(t){return new e.Op.AddUnique(e._decode(t.objects))}),e.Op.Remove=e.Op._extend({_initialize:function(e){this._objects=r.uniq(e)},objects:function(){return this._objects},toJSON:function(){return{__op:"Remove",objects:e._encode(this.objects())}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)return t;if(t instanceof e.Op.Set)return new e.Op.Set(this._estimate(t.value()));if(t instanceof e.Op.Remove)return new e.Op.Remove(r.union(t.objects(),this.objects()));throw new Error("Op is invalid after previous op.")}return this},_estimate:function(t){if(t){var n=r.difference(t,this.objects());return e._arrayEach(this.objects(),function(t){t instanceof e.Object&&t.id&&(n=r.reject(n,function(n){return n instanceof e.Object&&n.id===t.id}))}),n}return[]}}),e.Op._registerDecoder("Remove",function(t){return new e.Op.Remove(e._decode(t.objects))}),e.Op.Relation=e.Op._extend({_initialize:function(t,n){this._targetClassName=null;var i=this,o=function(t){if(t instanceof e.Object){if(!t.id)throw new Error("You can't add an unsaved AV.Object to a relation.");if(i._targetClassName||(i._targetClassName=t.className),i._targetClassName!==t.className)throw new Error("Tried to create a AV.Relation with 2 different types: "+i._targetClassName+" and "+t.className+".");return t.id}return t};this.relationsToAdd=r.uniq(r.map(t,o)),this.relationsToRemove=r.uniq(r.map(n,o))},added:function(){var t=this;return r.map(this.relationsToAdd,function(n){var r=e.Object._create(t._targetClassName);return r.id=n,r})},removed:function(){var t=this;return r.map(this.relationsToRemove,function(n){var r=e.Object._create(t._targetClassName);return r.id=n,r})},toJSON:function(){var e=null,t=null,n=this,i=function(e){return{__type:"Pointer",className:n._targetClassName,objectId:e}},o=null;return this.relationsToAdd.length>0&&(o=r.map(this.relationsToAdd,i),e={__op:"AddRelation",objects:o}),this.relationsToRemove.length>0&&(o=r.map(this.relationsToRemove,i),t={__op:"RemoveRelation",objects:o}),e&&t?{__op:"Batch",ops:[e,t]}:e||t||{}},_mergeWithPrevious:function(t){if(t){if(t instanceof e.Op.Unset)throw new Error("You can't modify a relation after deleting it.");if(t instanceof e.Op.Relation){if(t._targetClassName&&t._targetClassName!==this._targetClassName)throw new Error("Related object must be of class "+t._targetClassName+", but "+this._targetClassName+" was passed in.");var n=r.union(r.difference(t.relationsToAdd,this.relationsToRemove),this.relationsToAdd),i=r.union(r.difference(t.relationsToRemove,this.relationsToAdd),this.relationsToRemove),o=new e.Op.Relation(n,i);return o._targetClassName=this._targetClassName,o}throw new Error("Op is invalid after previous op.")}return this},_estimate:function(t,n,r){if(t){if(t instanceof e.Relation){if(this._targetClassName)if(t.targetClassName){if(t.targetClassName!==this._targetClassName)throw new Error("Related object must be a "+t.targetClassName+", but a "+this._targetClassName+" was passed in.")}else t.targetClassName=this._targetClassName;return t}throw new Error("Op is invalid after previous op.")}var i=new e.Relation(n,r);i.targetClassName=this._targetClassName}}),e.Op._registerDecoder("AddRelation",function(t){return new e.Op.Relation(e._decode(t.objects),[])}),e.Op._registerDecoder("RemoveRelation",function(t){return new e.Op.Relation([],e._decode(t.objects))})}},function(e,t,n){"use strict";var r=n(2).request;e.exports=function(e){e.Installation=e.Object.extend("_Installation"),e.Push=e.Push||{},e.Push.send=function(e,t){if(e.where&&(e.where=e.where.toJSON().where),e.where&&e.cql)throw new Error("Both where and cql can't be set");if(e.push_time&&(e.push_time=e.push_time.toJSON()),e.expiration_time&&(e.expiration_time=e.expiration_time.toJSON()),e.expiration_time&&e.expiration_time_interval)throw new Error("Both expiration_time and expiration_time_interval can't be set");var n=r("push",null,null,"POST",e,t);return n}}},function(e,t,n){"use strict";var r=n(0),i=n(5)("leancloud:query"),o=n(1),s=n(3),a=n(2).request,u=n(4),c=u.ensureArray,l=function(e,t){if(void 0===e)throw new Error(t)};e.exports=function(e){e.Query=function(t){r.isString(t)&&(t=e.Object._getSubclass(t)),this.objectClass=t,this.className=t.prototype.className,this._where={},this._include=[],this._select=[],this._limit=-1,this._skip=0,this._extraOptions={}},e.Query.or=function(){var t=r.toArray(arguments),n=null;e._arrayEach(t,function(e){if(r.isNull(n)&&(n=e.className),n!==e.className)throw new Error("All queries must be for the same class")});var i=new e.Query(n);return i._orQuery(t),i},e.Query.and=function(){var t=r.toArray(arguments),n=null;e._arrayEach(t,function(e){if(r.isNull(n)&&(n=e.className),n!==e.className)throw new Error("All queries must be for the same class")});var i=new e.Query(n);return i._andQuery(t),i},e.Query.doCloudQuery=function(t,n,i){var o={cql:t};r.isArray(n)?o.pvalues=n:i=n;var s=a("cloudQuery",null,null,"GET",o,i);return s.then(function(t){var n=new e.Query(t.className),i=r.map(t.results,function(e){var r=n._newObject(t);return r._finishFetch&&r._finishFetch(n._processResult(e),!0),r});return{results:i,count:t.count,className:t.className}})},e.Query._extend=e._extend,e.Query.prototype={_processResult:function(e){return e},get:function(e,t){if(!e){var n=new s(s.OBJECT_NOT_FOUND,"Object not found.");throw n}var r=this,i=r._newObject();i.id=e;var o=r.toJSON(),a={};return o.keys&&(a.keys=o.keys),o.include&&(a.include=o.include),i.fetch(a,t)},toJSON:function(){var t={where:this._where};return this._include.length>0&&(t.include=this._include.join(",")),this._select.length>0&&(t.keys=this._select.join(",")),this._limit>=0&&(t.limit=this._limit),this._skip>0&&(t.skip=this._skip),void 0!==this._order&&(t.order=this._order),e._objectEach(this._extraOptions,function(e,n){t[n]=e}),t},_newObject:function(t){var n;return n=t&&t.className?new e.Object(t.className):new this.objectClass},_createRequest:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.toJSON(),t=arguments[1];if(JSON.stringify(e).length>2e3){var n={requests:[{method:"GET",path:"/1.1/classes/"+this.className,params:e}]};return a("batch",null,null,"POST",n,t).then(function(e){var t=e[0];if(t.success)return t.success;var n=new Error(t.error.error||"Unknown batch error");throw n.code=t.error.code,n})}return a("classes",this.className,null,"GET",e,t)},_parseResponse:function(e){var t=this;return r.map(e.results,function(n){var r=t._newObject(e);return r._finishFetch&&r._finishFetch(t._processResult(n),!0),r})},find:function(e){var t=this._createRequest(void 0,e);return t.then(this._parseResponse.bind(this))},scan:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=t.orderedBy,s=t.batchSize,u=arguments[1],c=this.toJSON();i("scan %O",c),c.order&&(console.warn("The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan."),delete c.order),c.skip&&(console.warn("The skip option of the query is ignored for Query#scan."),delete c.skip),c.limit&&(console.warn("The limit option of the query is ignored for Query#scan."),delete c.limit),n&&(c.scan_key=n),s&&(c.limit=s);var l=o.resolve([]),f=void 0,h=!1;return{next:function(){return l=l.then(function(t){return h?[]:t.length>1?t:f||0===t.length?a("scan/classes",e.className,null,"GET",f?r.extend({},c,{cursor:f}):c,u).then(function(t){return f=t.cursor,e._parseResponse(t)}).then(function(e){return e.length||(h=!0),t.concat(e)}):(h=!0,t)}),l.then(function(e){return e.shift()}).then(function(e){return{value:e,done:h}})}}},destroyAll:function(t){var n=this;return n.find(t).then(function(n){return e.Object.destroyAll(n,t)})},count:function(e){var t=this.toJSON();t.limit=0,t.count=1;var n=this._createRequest(t,e);return n.then(function(e){return e.count})},first:function(e){var t=this,n=this.toJSON();n.limit=1;var i=this._createRequest(n,e);return i.then(function(e){return r.map(e.results,function(e){var n=t._newObject();return n._finishFetch&&n._finishFetch(t._processResult(e),!0),n})[0]})},skip:function(e){return l(e,"undefined is not a valid skip value"),this._skip=e,this},limit:function(e){return l(e,"undefined is not a valid limit value"),this._limit=e,this},equalTo:function(t,n){return l(t,"undefined is not a valid key"),l(n,"undefined is not a valid value"),this._where[t]=e._encode(n),this},_addCondition:function(t,n,r){return l(t,"undefined is not a valid condition key"),l(n,"undefined is not a valid condition"),l(r,"undefined is not a valid condition value"),this._where[t]||(this._where[t]={}),this._where[t][n]=e._encode(r),this},sizeEqualTo:function(e,t){this._addCondition(e,"$size",t)},notEqualTo:function(e,t){return this._addCondition(e,"$ne",t),this},lessThan:function(e,t){return this._addCondition(e,"$lt",t),this},greaterThan:function(e,t){return this._addCondition(e,"$gt",t),this},lessThanOrEqualTo:function(e,t){return this._addCondition(e,"$lte",t),this},greaterThanOrEqualTo:function(e,t){return this._addCondition(e,"$gte",t),this},containedIn:function(e,t){return this._addCondition(e,"$in",t),this},notContainedIn:function(e,t){return this._addCondition(e,"$nin",t),this},containsAll:function(e,t){return this._addCondition(e,"$all",t),this},exists:function(e){return this._addCondition(e,"$exists",!0),this},doesNotExist:function(e){return this._addCondition(e,"$exists",!1),this},matches:function(e,t,n){return this._addCondition(e,"$regex",t),n||(n=""),t.ignoreCase&&(n+="i"),t.multiline&&(n+="m"),n&&n.length&&this._addCondition(e,"$options",n),this},matchesQuery:function(e,t){var n=t.toJSON();return n.className=t.className,this._addCondition(e,"$inQuery",n),this},doesNotMatchQuery:function(e,t){var n=t.toJSON();return n.className=t.className,this._addCondition(e,"$notInQuery",n),this},matchesKeyInQuery:function(e,t,n){var r=n.toJSON();return r.className=n.className,this._addCondition(e,"$select",{key:t,query:r}),this},doesNotMatchKeyInQuery:function(e,t,n){var r=n.toJSON();return r.className=n.className,this._addCondition(e,"$dontSelect",{key:t,query:r}),this},_orQuery:function(e){var t=r.map(e,function(e){return e.toJSON().where});return this._where.$or=t,this},_andQuery:function(e){var t=r.map(e,function(e){return e.toJSON().where});return this._where.$and=t,this},_quote:function(e){return"\\Q"+e.replace("\\E","\\E\\\\E\\Q")+"\\E"},contains:function(e,t){return this._addCondition(e,"$regex",this._quote(t)),this},startsWith:function(e,t){return this._addCondition(e,"$regex","^"+this._quote(t)),this},endsWith:function(e,t){return this._addCondition(e,"$regex",this._quote(t)+"$"),this},ascending:function(e){return l(e,"undefined is not a valid key"),this._order=e,this},addAscending:function(e){return l(e,"undefined is not a valid key"),this._order?this._order+=","+e:this._order=e,this},descending:function(e){return l(e,"undefined is not a valid key"),this._order="-"+e,this},addDescending:function(e){return l(e,"undefined is not a valid key"),this._order?this._order+=",-"+e:this._order="-"+e,this},near:function(t,n){return n instanceof e.GeoPoint||(n=new e.GeoPoint(n)),this._addCondition(t,"$nearSphere",n),this},withinRadians:function(e,t,n){return this.near(e,t),this._addCondition(e,"$maxDistance",n),this},withinMiles:function(e,t,n){return this.withinRadians(e,t,n/3958.8); +},withinKilometers:function(e,t,n){return this.withinRadians(e,t,n/6371)},withinGeoBox:function(t,n,r){return n instanceof e.GeoPoint||(n=new e.GeoPoint(n)),r instanceof e.GeoPoint||(r=new e.GeoPoint(r)),this._addCondition(t,"$within",{$box:[n,r]}),this},include:function(e){var t=this;return l(e,"undefined is not a valid key"),r(arguments).forEach(function(e){t._include=t._include.concat(c(e))}),this},select:function(e){var t=this;return l(e,"undefined is not a valid key"),r(arguments).forEach(function(e){t._select=t._select.concat(c(e))}),this},each:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this._order||this._skip||this._limit>=0){var i=new Error("Cannot iterate on a query with sort, skip, or limit.");return e.Promise.reject(i)}var o=new e.Query(this.objectClass);o._limit=n.batchSize||100,o._where=r.clone(this._where),o._include=r.clone(this._include),o.ascending("objectId");var s=!1;return e.Promise._continueWhile(function(){return!s},function(){return o.find(n).then(function(n){var i=e.Promise.resolve();return r.each(n,function(e){i=i.then(function(){return t(e)})}),i.then(function(){n.length>=o._limit?o.greaterThan("objectId",n[n.length-1].id):s=!0})})})}},e.FriendShipQuery=e.Query._extend({_objectClass:e.User,_newObject:function(){return new e.User},_processResult:function(e){if(e&&e[this._friendshipTag]){var t=e[this._friendshipTag];return"Pointer"===t.__type&&"_User"===t.className&&(delete t.__type,delete t.className),t}return null}})}},function(e,t,n){"use strict";var r=n(0);e.exports=function(e){e.Relation=function(e,t){if(!r.isString(t))throw new TypeError("key must be a string");this.parent=e,this.key=t,this.targetClassName=null},e.Relation.reverseQuery=function(t,n,r){var i=new e.Query(t);return i.equalTo(n,r._toPointer()),i},e.Relation.prototype={_ensureParentAndKey:function(e,t){if(this.parent=this.parent||e,this.key=this.key||t,this.parent!==e)throw new Error("Internal Error. Relation retrieved from two different Objects.");if(this.key!==t)throw new Error("Internal Error. Relation retrieved from two different keys.")},add:function(t){r.isArray(t)||(t=[t]);var n=new e.Op.Relation(t,[]);this.parent.set(this.key,n),this.targetClassName=n._targetClassName},remove:function(t){r.isArray(t)||(t=[t]);var n=new e.Op.Relation([],t);this.parent.set(this.key,n),this.targetClassName=n._targetClassName},toJSON:function(){return{__type:"Relation",className:this.targetClassName}},query:function t(){var n,t;return this.targetClassName?(n=e.Object._getSubclass(this.targetClassName),t=new e.Query(n)):(n=e.Object._getSubclass(this.parent.className),t=new e.Query(n),t._extraOptions.redirectClassNameForKey=this.key),t._addCondition("$relatedTo","object",this.parent._toPointer()),t._addCondition("$relatedTo","key",this.key),t}}}},function(e,t,n){"use strict";var r=n(0),i=n(3);e.exports=function(e){e.Role=e.Object.extend("_Role",{constructor:function(t,n,i){if(r.isString(t)?(e.Object.prototype.constructor.call(this,null,null),this.setName(t)):e.Object.prototype.constructor.call(this,t,n),void 0===n){if(!i&&!this.getACL()){console.warn("DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.");var o=new e.ACL;o.setPublicReadAccess(!0),this.setACL(o)}}else{if(!(n instanceof e.ACL))throw new TypeError("acl must be an instance of AV.ACL");this.setACL(n)}},getName:function(){return this.get("name")},setName:function(e,t){return this.set("name",e,t)},getUsers:function(){return this.relation("users")},getRoles:function(){return this.relation("roles")},validate:function(t,n){if("name"in t&&t.name!==this.getName()){var o=t.name;if(this.id&&this.id!==t.objectId)return new i(i.OTHER_CAUSE,"A role's name can only be set before it has been saved.");if(!r.isString(o))return new i(i.OTHER_CAUSE,"A role's name must be a String.");if(!/^[0-9a-zA-Z\-_ ]+$/.test(o))return new i(i.OTHER_CAUSE,"A role's name can only contain alphanumeric characters, _, -, and spaces.")}return!!e.Object.prototype.validate&&e.Object.prototype.validate.call(this,t,n)}})}},function(e,t,n){"use strict";var r=n(0),i=n(2).request;e.exports=function(e){e.SearchSortBuilder=function(){this._sortFields=[]},e.SearchSortBuilder.prototype={_addField:function(e,t,n,r){var i={};return i[e]={order:t||"asc",mode:n||"avg",missing:"_"+(r||"last")},this._sortFields.push(i),this},ascending:function(e,t,n){return this._addField(e,"asc",t,n)},descending:function(e,t,n){return this._addField(e,"desc",t,n)},whereNear:function(e,t,n){n=n||{};var r={},i={lat:t.latitude,lon:t.longitude},o={order:n.order||"asc",mode:n.mode||"avg",unit:n.unit||"km"};return o[e]=i,r._geo_distance=o,this._sortFields.push(r),this},build:function(){return JSON.stringify(e._encode(this._sortFields))}},e.SearchQuery=e.Query._extend({_sid:null,_hits:0,_queryString:null,_highlights:null,_sortBuilder:null,_createRequest:function(e,t){return i("search/select",null,null,"GET",e||this.toJSON(),t)},sid:function(e){return this._sid=e,this},queryString:function(e){return this._queryString=e,this},highlights:function(e){var t;return t=e&&r.isString(e)?arguments:e,this._highlights=t,this},sortBy:function(e){return this._sortBuilder=e,this},hits:function(){return this._hits||(this._hits=0),this._hits},_processResult:function(e){return delete e.className,delete e._app_url,delete e._deeplink,e},hasMore:function(){return!this._hitEnd},reset:function(){this._hitEnd=!1,this._sid=null,this._hits=0},find:function(){var e=this,t=this._createRequest();return t.then(function(t){return t.sid?(e._oldSid=e._sid,e._sid=t.sid):(e._sid=null,e._hitEnd=!0),e._hits=t.hits||0,r.map(t.results,function(n){n.className&&(t.className=n.className);var r=e._newObject(t);return r.appURL=n._app_url,r._finishFetch(e._processResult(n),!0),r})})},toJSON:function(){var t=e.SearchQuery.__super__.toJSON.call(this);if(delete t.where,this.className&&(t.clazz=this.className),this._sid&&(t.sid=this._sid),!this._queryString)throw new Error("Please set query string.");if(t.q=this._queryString,this._highlights&&(t.highlights=this._highlights.join(",")),this._sortBuilder&&t.order)throw new Error("sort and order can not be set at same time.");return this._sortBuilder&&(t.sort=this._sortBuilder.build()),t}})}},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=n(0),o=n(2).request;e.exports=function(e){var t=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e.User.currentAsync().then(function(n){return n||e.User._fetchUserBySessionToken(t.sessionToken)})},n=function(n){return t(n).then(function(t){return e.Object.createWithoutData("_User",t.id)._toPointer()})};e.Status=function(e,t){return this.data={},this.inboxType="default",this.query=null,e&&"object"===("undefined"==typeof e?"undefined":r(e))?this.data=e:(e&&(this.data.image=e),t&&(this.data.message=t)),this},e.Status.prototype={get:function(e){return this.data[e]},set:function(e,t){return this.data[e]=t,this},destroy:function(t){if(!this.id)return e.Promise.reject(new Error("The status id is not exists."));var n=o("statuses",null,this.id,"DELETE",t);return n},toObject:function(){return this.id?e.Object.createWithoutData("_Status",this.id):null},_getDataJSON:function(){var t=i.clone(this.data);return e._encode(t)},send:function(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!r.sessionToken&&!e.User.current())throw new Error("Please signin an user.");return this.query?n(r).then(function(e){var n=t.query.toJSON();n.className=t.query.className;var i={};return i.query=n,t.data=t.data||{},t.data.source=t.data.source||e,i.data=t._getDataJSON(),i.inboxType=t.inboxType||"default",o("statuses",null,null,"POST",i,r)}).then(function(n){return t.id=n.objectId,t.createdAt=e._parseDate(n.createdAt),t}):e.Status.sendStatusToFollowers(this,r)},_finishFetch:function(t){this.id=t.objectId,this.createdAt=e._parseDate(t.createdAt),this.updatedAt=e._parseDate(t.updatedAt),this.messageId=t.messageId,delete t.messageId,delete t.objectId,delete t.createdAt,delete t.updatedAt,this.data=e._decode(t)}},e.Status.sendStatusToFollowers=function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!r.sessionToken&&!e.User.current())throw new Error("Please signin an user.");return n(r).then(function(n){var i={};i.className="_Follower",i.keys="follower",i.where={user:n};var s={};s.query=i,t.data=t.data||{},t.data.source=t.data.source||n,s.data=t._getDataJSON(),s.inboxType=t.inboxType||"default";var a=o("statuses",null,null,"POST",s,r);return a.then(function(n){return t.id=n.objectId,t.createdAt=e._parseDate(n.createdAt),t})})},e.Status.sendPrivateStatus=function(t,r){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!s.sessionToken&&!e.User.current())throw new Error("Please signin an user.");if(!r)throw new Error("Invalid target user.");var a=i.isString(r)?r:r.id;if(!a)throw new Error("Invalid target user.");return n(s).then(function(n){var r={};r.className="_User",r.where={objectId:a};var i={};i.query=r,t.data=t.data||{},t.data.source=t.data.source||n,i.data=t._getDataJSON(),i.inboxType="private",t.inboxType="private";var u=o("statuses",null,null,"POST",i,s);return u.then(function(n){return t.id=n.objectId,t.createdAt=e._parseDate(n.createdAt),t})})},e.Status.countUnreadStatuses=function(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(i.isString(r)||(s=r),!s.sessionToken&&null==n&&!e.User.current())throw new Error("Please signin an user or pass the owner objectId.");return t(s).then(function(t){var n={};return n.inboxType=e._encode(r),n.owner=e._encode(t),o("subscribe/statuses/count",null,null,"GET",n,s)})},e.Status.resetUnreadCount=function(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(i.isString(r)||(s=r),!s.sessionToken&&null==n&&!e.User.current())throw new Error("Please signin an user or pass the owner objectId.");return t(s).then(function(t){var n={};return n.inboxType=e._encode(r),n.owner=e._encode(t),o("subscribe/statuses/resetUnreadCount",null,null,"POST",n,s)})},e.Status.statusQuery=function(t){var n=new e.Query("_Status");return t&&n.equalTo("source",t),n},e.InboxQuery=e.Query._extend({_objectClass:e.Status,_sinceId:0,_maxId:0,_inboxType:"default",_owner:null,_newObject:function(){return new e.Status},_createRequest:function(e,t){return o("subscribe/statuses",null,null,"GET",e||this.toJSON(),t)},sinceId:function(e){return this._sinceId=e,this},maxId:function(e){return this._maxId=e,this},owner:function(e){return this._owner=e,this},inboxType:function(e){return this._inboxType=e,this},toJSON:function(){var t=e.InboxQuery.__super__.toJSON.call(this);return t.owner=e._encode(this._owner),t.inboxType=e._encode(this._inboxType),t.sinceId=e._encode(this._sinceId),t.maxId=e._encode(this._maxId),t}}),e.Status.inboxQuery=function(t,n){var r=new e.InboxQuery(e.Status);return t&&(r._owner=t),n&&(r._inboxType=n),r}}},function(e,t,n){"use strict";e.exports=[]},function(e,t,n){"use strict";var r=n(18),i=["Weapp"].concat(n(41));e.exports="LeanCloud-JS-SDK/"+r+" ("+i.join("; ")+")"},function(e,t,n){"use strict";var r=n(7),i=n(5)("cos"),o=n(1);e.exports=function(e,t,n){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};n.attributes.url=e.url,n._bucket=e.bucket,n.id=e.objectId;var a=e.upload_url+"?sign="+encodeURIComponent(e.token);return new o(function(e,o){var u=r("POST",a).field("fileContent",t).field("op","upload");s.onprogress&&u.on("progress",s.onprogress),u.end(function(t,r){return r&&i(r.status,r.body,r.text),t?(r&&(t.statusCode=r.status,t.responseText=r.text,t.response=r.body),o(t)):void e(n)})})}},function(e,t,n){"use strict";var r=n(7),i=n(1),o=n(5)("qiniu");e.exports=function(e,t,n){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};n.attributes.url=e.url,n._bucket=e.bucket,n.id=e.objectId;var a=e.token;return new i(function(e,i){var u=r("POST","https://up.qbox.me").field("file",t).field("name",n.attributes.name).field("key",n._qiniu_key).field("token",a);s.onprogress&&u.on("progress",s.onprogress),u.end(function(t,r){return r&&o(r.status,r.body,r.text),t?(r&&(t.statusCode=r.status,t.responseText=r.text,t.response=r.body),i(t)):void e(n)})})}},function(e,t,n){"use strict";var r=n(7);n(1);e.exports=function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return n.attributes.url=e.url,n._bucket=e.bucket,n.id=e.objectId,new Promise(function(o,s){var a=r("PUT",e.upload_url).set("Content-Type",n.get("mime_type")).send(t);i.onprogress&&a.on("progress",i.onprogress),a.end(function(e,t){return e?(t&&(e.statusCode=t.status,e.responseText=t.text,e.response=t.body),s(e)):void o(n)})})}},function(e,t,n){"use strict";var r=n(0),i=n(3),o=n(2).request,s=n(1),a=function(){if("undefined"==typeof wx||"function"!=typeof wx.login)throw new Error("Weapp Login is only available in Weapp");return new s(function(e,t){wx.login({success:function(n){var r=n.code,i=n.errMsg;r?e(r):t(new Error(i))}})})};e.exports=function(e){e.User=e.Object.extend("_User",{_isCurrentUser:!1,_mergeMagicFields:function(t){t.sessionToken&&(this._sessionToken=t.sessionToken,delete t.sessionToken),e.User.__super__._mergeMagicFields.call(this,t)},_cleanupAuthData:function(){if(this.isCurrent()){var t=this.get("authData");t&&e._objectEach(this.get("authData"),function(e,n){t[n]||delete t[n]})}},_synchronizeAllAuthData:function(){var t=this.get("authData");if(t){var n=this;e._objectEach(this.get("authData"),function(e,t){n._synchronizeAuthData(t)})}},_synchronizeAuthData:function(t){if(this.isCurrent()){var n;r.isString(t)?(n=t,t=e.User._authProviders[n]):n=t.getAuthType();var i=this.get("authData");if(i&&t){var o=t.restoreAuthentication(i[n]);o||this._unlinkFrom(t)}}},_handleSaveResult:function(t){return t&&!e._config.disableCurrentUser&&(this._isCurrentUser=!0),this._cleanupAuthData(),this._synchronizeAllAuthData(),delete this._serverData.password,this._rebuildEstimatedDataForKey("password"),this._refreshCache(),!t&&!this.isCurrent()||e._config.disableCurrentUser?s.resolve():s.resolve(e.User._saveCurrentUser(this))},_linkWith:function(t,n){var i,o=this;if(r.isString(t)?(i=t,t=e.User._authProviders[t]):i=t.getAuthType(),n){var s=this.get("authData")||{};return s[i]=n,this.save({authData:s}).then(function(e){return e._handleSaveResult(!0).then(function(){return e})})}return t.authenticate().then(function(e){return o._linkWith(t,e)})},linkWithWeapp:function(){var e=this;return a().then(function(t){return e._linkWith("lc_weapp",{code:t})})},_unlinkFrom:function(t){var n=this;return r.isString(t)&&(t=e.User._authProviders[t]),this._linkWith(t,null).then(function(e){return n._synchronizeAuthData(t),e})},_isLinked:function(e){var t;t=r.isString(e)?e:e.getAuthType();var n=this.get("authData")||{};return!!n[t]},logOut:function(){this._logOutWithAll(),this._isCurrentUser=!1},_logOutWithAll:function(){var t=this.get("authData");if(t){var n=this;e._objectEach(this.get("authData"),function(e,t){n._logOutWith(t)})}},_logOutWith:function(t){this.isCurrent()&&(r.isString(t)&&(t=e.User._authProviders[t]),t&&t.deauthenticate&&t.deauthenticate())},signUp:function(e,t){var n,r=e&&e.username||this.get("username");if(!r||""===r)throw n=new i(i.OTHER_CAUSE,"Cannot sign up user with an empty name.");var o=e&&e.password||this.get("password");if(!o||""===o)throw n=new i(i.OTHER_CAUSE,"Cannot sign up user with an empty password.");return this.save(e,t).then(function(e){return e._handleSaveResult(!0).then(function(){return e})})},signUpOrlogInWithMobilePhone:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e&&e.mobilePhoneNumber||this.get("mobilePhoneNumber");if(!r||""===r)throw t=new i(i.OTHER_CAUSE,"Cannot sign up or login user by mobilePhoneNumber with an empty mobilePhoneNumber.");var s=e&&e.smsCode||this.get("smsCode");if(!s||""===s)throw t=new i(i.OTHER_CAUSE,"Cannot sign up or login user by mobilePhoneNumber with an empty smsCode.");return n._makeRequest=function(e,t,n,r,i){return o("usersByMobilePhone",null,null,"POST",i)},this.save(e,n).then(function(e){return delete e.attributes.smsCode,delete e._serverData.smsCode,e._handleSaveResult(!0).then(function(){return e})})},logIn:function(){var e=this,t=o("login",null,null,"POST",this.toJSON());return t.then(function(t){var n=e.parse(t);return e._finishFetch(n),e._handleSaveResult(!0).then(function(){return n.smsCode||delete e.attributes.smsCode,e})})},save:function(t,n,i){var o,s;return r.isObject(t)||r.isNull(t)||r.isUndefined(t)?(o=t,s=n):(o={},o[t]=n,s=i),s=s||{},e.Object.prototype.save.call(this,o,s).then(function(e){return e._handleSaveResult(!1).then(function(){return e})})},follow:function(e,t){if(!this.id)throw new Error("Please signin.");if(!e)throw new Error("Invalid target user.");var n=r.isString(e)?e:e.id;if(!n)throw new Error("Invalid target user.");var i="users/"+this.id+"/friendship/"+n,s=o(i,null,null,"POST",null,t);return s},unfollow:function(e,t){if(!this.id)throw new Error("Please signin.");if(!e)throw new Error("Invalid target user.");var n=r.isString(e)?e:e.id;if(!n)throw new Error("Invalid target user.");var i="users/"+this.id+"/friendship/"+n,s=o(i,null,null,"DELETE",null,t);return s},followerQuery:function(){return e.User.followerQuery(this.id)},followeeQuery:function(){return e.User.followeeQuery(this.id)},fetch:function(t,n){return e.Object.prototype.fetch.call(this,t,n).then(function(e){return e._handleSaveResult(!1).then(function(){return e})})},updatePassword:function(e,t,n){var r="users/"+this.id+"/updatePassword",i={old_password:e,new_password:t},s=o(r,null,null,"PUT",i,n);return s},isCurrent:function(){return this._isCurrentUser},getUsername:function(){return this.get("username")},getMobilePhoneNumber:function(){return this.get("mobilePhoneNumber")},setMobilePhoneNumber:function(e,t){return this.set("mobilePhoneNumber",e,t)},setUsername:function(e,t){return this.set("username",e,t)},setPassword:function(e,t){return this.set("password",e,t)},getEmail:function(){return this.get("email")},setEmail:function(e,t){return this.set("email",e,t)},authenticated:function(){return console.warn("DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。"),!!this._sessionToken&&!e._config.disableCurrentUser&&e.User.current()&&e.User.current().id===this.id},isAuthenticated:function(){var t=this;return s.resolve().then(function(){return!!t._sessionToken&&e.User._fetchUserBySessionToken(t._sessionToken).then(function(){return!0},function(e){if(211===e.code)return!1;throw e})})},getSessionToken:function(){return this._sessionToken},refreshSessionToken:function(e){var t=this;return o("users/"+this.id+"/refreshSessionToken",null,null,"PUT",null,e).then(function(e){return t._finishFetch(e),t._handleSaveResult(!0).then(function(){return t})})},getRoles:function(t){return e.Relation.reverseQuery("_Role","users",this).find(t)}},{_currentUser:null,_currentUserMatchesDisk:!1,_CURRENT_USER_KEY:"currentUser",_authProviders:{},signUp:function(t,n,r,i){r=r||{},r.username=t,r.password=n;var o=e.Object._create("_User");return o.signUp(r,i)},logIn:function(t,n,r){var i=e.Object._create("_User");return i._finishFetch({username:t,password:n}),i.logIn(r)},become:function(e){return this._fetchUserBySessionToken(e).then(function(e){return e._handleSaveResult(!0).then(function(){return e})})},_fetchUserBySessionToken:function(t){var n=e.Object._create("_User");return o("users","me",null,"GET",{session_token:t}).then(function(e){var t=n.parse(e);return n._finishFetch(t),n})},logInWithMobilePhoneSmsCode:function(t,n,r){var i=e.Object._create("_User");return i._finishFetch({mobilePhoneNumber:t,smsCode:n}),i.logIn(r)},signUpOrlogInWithMobilePhone:function(t,n,r,i){r=r||{},r.mobilePhoneNumber=t,r.smsCode=n;var o=e.Object._create("_User");return o.signUpOrlogInWithMobilePhone(r,i)},logInWithMobilePhone:function(t,n,r){var i=e.Object._create("_User");return i._finishFetch({mobilePhoneNumber:t,password:n}),i.logIn(r)},signUpOrlogInWithAuthData:function(t,n){return e.User._logInWith(n,t)},loginWithWeapp:function(){var e=this;return a().then(function(t){return e.signUpOrlogInWithAuthData({code:t},"lc_weapp")})},associateWithAuthData:function(e,t,n){return e._linkWith(t,n)},logOut:function(){return e._config.disableCurrentUser?(console.warn("AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html"),s.resolve(null)):(null!==e.User._currentUser&&(e.User._currentUser._logOutWithAll(),e.User._currentUser._isCurrentUser=!1),e.User._currentUserMatchesDisk=!0,e.User._currentUser=null,e.localStorage.removeItemAsync(e._getAVPath(e.User._CURRENT_USER_KEY)))},followerQuery:function(t){if(!t||!r.isString(t))throw new Error("Invalid user object id.");var n=new e.FriendShipQuery("_Follower");return n._friendshipTag="follower",n.equalTo("user",e.Object.createWithoutData("_User",t)),n},followeeQuery:function(t){if(!t||!r.isString(t))throw new Error("Invalid user object id.");var n=new e.FriendShipQuery("_Followee");return n._friendshipTag="followee",n.equalTo("user",e.Object.createWithoutData("_User",t)),n},requestPasswordReset:function(e){var t={email:e},n=o("requestPasswordReset",null,null,"POST",t);return n},requestEmailVerify:function(e){var t={email:e},n=o("requestEmailVerify",null,null,"POST",t);return n},requestMobilePhoneVerify:function(e){var t={mobilePhoneNumber:e},n=o("requestMobilePhoneVerify",null,null,"POST",t);return n},requestPasswordResetBySmsCode:function(e){var t={mobilePhoneNumber:e},n=o("requestPasswordResetBySmsCode",null,null,"POST",t);return n},resetPasswordBySmsCode:function(e,t){var n={password:t},r=o("resetPasswordBySmsCode",null,e,"PUT",n);return r},verifyMobilePhone:function(e){var t=o("verifyMobilePhone",null,e,"POST",null);return t},requestLoginSmsCode:function(e){var t={mobilePhoneNumber:e},n=o("requestLoginSmsCode",null,null,"POST",t);return n},currentAsync:function(){return e._config.disableCurrentUser?(console.warn("AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html"),s.resolve(null)):e.User._currentUser?s.resolve(e.User._currentUser):e.User._currentUserMatchesDisk?s.resolve(e.User._currentUser):e.localStorage.getItemAsync(e._getAVPath(e.User._CURRENT_USER_KEY)).then(function(t){if(!t)return null;e.User._currentUserMatchesDisk=!0,e.User._currentUser=e.Object._create("_User"),e.User._currentUser._isCurrentUser=!0;var n=JSON.parse(t);return e.User._currentUser.id=n._id,delete n._id,e.User._currentUser._sessionToken=n._sessionToken,delete n._sessionToken,e.User._currentUser._finishFetch(n),e.User._currentUser._synchronizeAllAuthData(),e.User._currentUser._refreshCache(),e.User._currentUser._opSetQueue=[{}],e.User._currentUser})},current:function(){if(e._config.disableCurrentUser)return console.warn("AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html"),null;if(e.User._currentUser)return e.User._currentUser;if(e.User._currentUserMatchesDisk)return e.User._currentUser;e.User._currentUserMatchesDisk=!0;var t=e.localStorage.getItem(e._getAVPath(e.User._CURRENT_USER_KEY));if(!t)return null;e.User._currentUser=e.Object._create("_User"),e.User._currentUser._isCurrentUser=!0;var n=JSON.parse(t);return e.User._currentUser.id=n._id,delete n._id,e.User._currentUser._sessionToken=n._sessionToken,delete n._sessionToken,e.User._currentUser._finishFetch(n),e.User._currentUser._synchronizeAllAuthData(),e.User._currentUser._refreshCache(),e.User._currentUser._opSetQueue=[{}],e.User._currentUser},_saveCurrentUser:function(t){var n;return n=e.User._currentUser!==t?e.User.logOut():s.resolve(),n.then(function(){t._isCurrentUser=!0,e.User._currentUser=t;var n=t.toJSON();return n._id=t.id,n._sessionToken=t._sessionToken,e.localStorage.setItemAsync(e._getAVPath(e.User._CURRENT_USER_KEY),JSON.stringify(n)).then(function(){e.User._currentUserMatchesDisk=!0})})},_registerAuthenticationProvider:function(t){e.User._authProviders[t.getAuthType()]=t,!e._config.disableCurrentUser&&e.User.current()&&e.User.current()._synchronizeAuthData(t.getAuthType())},_logInWith:function(t,n){var r=e.Object._create("_User");return r._linkWith(t,n)}})}},function(e,t,n){"use strict";(function(t){var r=n(0),i=(n(1),{}),o=["getItem","setItem","removeItem","clear"],s=t.localStorage;try{var a="__storejs__";if(s.setItem(a,a),s.getItem(a)!=a)throw new Error;s.removeItem(a)}catch(e){s=n(56)}r(o).each(function(e){i[e]=function(){return t.localStorage[e].apply(t.localStorage,arguments)}}),i.async=!1,e.exports=i}).call(t,n(8))},function(e,t,n){"use strict";var r=function(e,t){var n;e.indexOf("base64")<0?n=atob(e):e.split(",")[0].indexOf("base64")>=0?(t=t||e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1])):n=unescape(e.split(",")[1]);for(var r=new Uint8Array(n.length),i=0;i>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return 16711935&n.rotl(e,8)|4278255360&n.rotl(e,24);for(var t=0;t0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],n=0,r=0;n>>5]|=e[n]<<24-r%32;return t},wordsToBytes:function(e){for(var t=[],n=0;n<32*e.length;n+=8)t.push(e[n>>>5]>>>24-n%32&255);return t},bytesToHex:function(e){for(var t=[],n=0;n>>4).toString(16)),t.push((15&e[n]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],n=0;n>>6*(3-o)&63)):n.push("=");return n.join("")},base64ToBytes:function(e){e=e.replace(/[^A-Z0-9+\/]/gi,"");for(var n=[],r=0,i=0;r>>6-2*i);return n}};e.exports=n}()},function(e,t,n){function r(e){var n,r=0;for(n in e)r=(r<<5)-r+e.charCodeAt(n),r|=0;return t.colors[Math.abs(r)%t.colors.length]}function i(e){function n(){if(n.enabled){var e=n,r=+new Date,i=r-(c||r);e.diff=i,e.prev=c,e.curr=r,c=r;for(var o=new Array(arguments.length),s=0;s>>24)|4278255360&(a[d]<<24|a[d]>>>8);a[u>>>5]|=128<>>9<<4)+14]=u;for(var p=s._ff,_=s._gg,v=s._hh,y=s._ii,d=0;d>>0,l=l+g>>>0,f=f+b>>>0,h=h+w>>>0}return t.endian([c,l,f,h])};s._ff=function(e,t,n,r,i,o,s){var a=e+(t&n|~t&r)+(i>>>0)+s;return(a<>>32-o)+t},s._gg=function(e,t,n,r,i,o,s){var a=e+(t&r|n&~r)+(i>>>0)+s;return(a<>>32-o)+t},s._hh=function(e,t,n,r,i,o,s){var a=e+(t^n^r)+(i>>>0)+s;return(a<>>32-o)+t},s._ii=function(e,t,n,r,i,o,s){var a=e+(n^(t|~r))+(i>>>0)+s;return(a<>>32-o)+t},s._blocksize=16,s._digestsize=16,e.exports=function(e,n){if(void 0===e||null===e)throw new Error("Illegal argument "+e);var r=t.wordsToBytes(s(e,n));return n&&n.asBytes?r:n&&n.asString?o.bytesToString(r):t.bytesToHex(r)}}()},function(e,t){function n(e){if(e=String(e),!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*c;case"hours":case"hour":case"hrs":case"hr":case"h":return n*u;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function r(e){return e>=c?Math.round(e/c)+"d":e>=u?Math.round(e/u)+"h":e>=a?Math.round(e/a)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function i(e){return o(e,c,"day")||o(e,u,"hour")||o(e,a,"minute")||o(e,s,"second")||e+" ms"}function o(e,t,n){if(!(e0)return n(e);if("number"===o&&isNaN(e)===!1)return t.long?i(e):r(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},function(e,t,n){function r(e){var t=i(e)?Object.prototype.toString.call(e):"";return"[object Function]"===t}var i=n(11);e.exports=r},function(e,t,n){function r(e){if(e)return i(e)}function i(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}var o=n(11);e.exports=r,r.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,this},r.prototype.parse=function(e){return this._parser=e,this},r.prototype.responseType=function(e){return this._responseType=e,this},r.prototype.serialize=function(e){return this._serializer=e,this},r.prototype.timeout=function(e){if(!e||"object"!=typeof e)return this._timeout=e,this._responseTimeout=0,this;for(var t in e)switch(t){case"deadline":this._timeout=e.deadline;break;case"response":this._responseTimeout=e.response;break;default:console.warn("Unknown timeout option",t)}return this},r.prototype.retry=function(e){return 0!==arguments.length&&e!==!0||(e=1),e<=0&&(e=0),this._maxRetries=e,this._retries=0,this},r.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this._end()},r.prototype.then=function(e,t){if(!this._fullfilledPromise){var n=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(function(e,t){n.end(function(n,r){n?t(n):e(r)})})}return this._fullfilledPromise.then(e,t)},r.prototype.catch=function(e){return this.then(void 0,e)},r.prototype.use=function(e){return e(this),this},r.prototype.ok=function(e){if("function"!=typeof e)throw Error("Callback required");return this._okCallback=e,this},r.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},r.prototype.get=function(e){return this._header[e.toLowerCase()]},r.prototype.getHeader=r.prototype.get,r.prototype.set=function(e,t){if(o(e)){for(var n in e)this.set(n,e[n]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},r.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},r.prototype.field=function(e,t){if(null===e||void 0===e)throw new Error(".field(name, val) name can not be empty");if(this._data&&console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"),o(e)){for(var n in e)this.field(n,e[n]);return this}if(Array.isArray(t)){for(var r in t)this.field(e,t[r]);return this}if(null===t||void 0===t)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof t&&(t=""+t),this._getFormData().append(e,t),this},r.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},r.prototype.withCredentials=function(e){return void 0==e&&(e=!0),this._withCredentials=e,this},r.prototype.redirects=function(e){return this._maxRedirects=e,this},r.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},r.prototype.send=function(e){var t=o(e),n=this._header["content-type"];if(this._formData&&console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"),t&&!this._data)Array.isArray(e)?this._data=[]:this._isHost(e)||(this._data={});else if(e&&this._data&&this._isHost(this._data))throw Error("Can't merge these send calls");if(t&&o(this._data))for(var r in e)this._data[r]=e[r];else"string"==typeof e?(n||this.type("form"),n=this._header["content-type"],"application/x-www-form-urlencoded"==n?this._data=this._data?this._data+"&"+e:e:this._data=(this._data||"")+e):this._data=e;return!t||this._isHost(e)?this:(n||this.type("json"),this)},r.prototype.sortQuery=function(e){return this._sort="undefined"==typeof e||e,this},r.prototype._timeoutError=function(e,t,n){if(!this._aborted){var r=new Error(e+t+"ms exceeded");r.timeout=t,r.code="ECONNABORTED",r.errno=n,this.timedout=!0,this.abort(),this.callback(r)}},r.prototype._setTimeouts=function(){var e=this;this._timeout&&!this._timer&&(this._timer=setTimeout(function(){e._timeoutError("Timeout of ",e._timeout,"ETIME")},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){e._timeoutError("Response timeout of ",e._responseTimeout,"ETIMEDOUT")},this._responseTimeout))}},function(e,t,n){function r(e){if(e)return i(e)}function i(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}var o=n(63);e.exports=r,r.prototype.get=function(e){return this.header[e.toLowerCase()]},r.prototype._setHeaderProperties=function(e){var t=e["content-type"]||"";this.type=o.type(t);var n=o.params(t);for(var r in n)this[r]=n[r];this.links={};try{e.link&&(this.links=o.parseLinks(e.link))}catch(e){}},r.prototype._setStatusProperties=function(e){var t=e/100|0;this.status=this.statusCode=e,this.statusType=t,this.info=1==t,this.ok=2==t,this.redirect=3==t,this.clientError=4==t,this.serverError=5==t,this.error=(4==t||5==t)&&this.toError(),this.accepted=202==e,this.noContent=204==e,this.badRequest=400==e,this.unauthorized=401==e,this.notAcceptable=406==e,this.forbidden=403==e,this.notFound=404==e}},function(e,t){var n=["ECONNRESET","ETIMEDOUT","EADDRINFO","ESOCKETTIMEDOUT"];e.exports=function(e,t){return!!(e&&e.code&&~n.indexOf(e.code))||(!!(t&&t.status&&t.status>=500)||(!!(e&&"timeout"in e&&"ECONNABORTED"==e.code)||!!(e&&"crossDomain"in e)))}},function(e,t){t.type=function(e){return e.split(/ *; */).shift()},t.params=function(e){return e.split(/ *; */).reduce(function(e,t){var n=t.split(/ *= */),r=n.shift(),i=n.shift();return r&&i&&(e[r]=i),e},{})},t.parseLinks=function(e){return e.split(/ *, */).reduce(function(e,t){var n=t.split(/ *; */),r=n[0].slice(1,-1),i=n[1].split(/ *= */)[1].slice(1,-1);return e[i]=r,e},{})},t.cleanHeader=function(e,t){return delete e["content-type"],delete e["content-length"],delete e["transfer-encoding"],delete e.host,t&&delete e.cookie,e}},function(e,t){}])}); +//# sourceMappingURL=av-weapp-min.js.map \ No newline at end of file diff --git a/dist/av-weapp-min.js.map b/dist/av-weapp-min.js.map new file mode 100644 index 000000000..19df12977 --- /dev/null +++ b/dist/av-weapp-min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:/webpack/bootstrap 49fd826478e50efdbf60","webpack:///~/underscore/underscore.js","webpack:///src/promise.js","webpack:///src/request.js","webpack:///src/error.js","webpack:///src/utils/index.js","webpack:///~/debug/src/browser.js","webpack:///src/av.js","webpack:///~/superagent/lib/client.js","webpack:///(webpack)/buildin/global.js","webpack:///~/weapp-polyfill/formdata.js","webpack:///~/event-target-shim/lib/commons.js","webpack:///~/superagent/lib/is-object.js","webpack:///~/weapp-polyfill/localstorage.js","webpack:///~/weapp-polyfill/navigator.js","webpack:///~/weapp-polyfill/websocket.js","webpack:///~/weapp-polyfill/xmlhttprequest.js","webpack:///src/cache.js","webpack:///src/localstorage.js","webpack:///src/version.js","webpack:///~/charenc/charenc.js","webpack:///~/event-target-shim/lib/event-target.js","webpack:///~/object-assign/index.js","webpack:///~/weapp-polyfill/auto-polyfill.js","webpack:///src/index.js","webpack:///~/weapp-polyfill/index.js","webpack:///src/acl.js","webpack:///src/cloudfunction.js","webpack:///src/event.js","webpack:///src/file.js","webpack:///src/geopoint.js","webpack:///src/index-weapp.js","webpack:///src/init.js","webpack:///src/insight.js","webpack:///src/object.js","webpack:///src/op.js","webpack:///src/push.js","webpack:///src/query.js","webpack:///src/relation.js","webpack:///src/role.js","webpack:///src/search.js","webpack:///src/status.js","webpack:///src/ua/comments-browser.js","webpack:///src/ua/index.js","webpack:///src/uploader/cos.js","webpack:///src/uploader/qiniu-browser.js","webpack:///src/uploader/s3.js","webpack:///src/user.js","webpack:///src/utils/localstorage-browser.js","webpack:///src/utils/parse-base64-browser.js","webpack:///~/component-emitter/index.js","webpack:///~/crypt/crypt.js","webpack:///~/debug/src/debug.js","webpack:///~/es6-promise/dist/es6-promise.js","webpack:///~/event-target-shim/lib/custom-event-target.js","webpack:///~/event-target-shim/lib/event-wrapper.js","webpack:///~/is-buffer/index.js","webpack:///~/localstorage-memory/lib/localstorage-memory.js","webpack:///~/md5/md5.js","webpack:///~/ms/index.js","webpack:///~/superagent/lib/is-function.js","webpack:///~/superagent/lib/request-base.js","webpack:///~/superagent/lib/response-base.js","webpack:///~/superagent/lib/should-retry.js","webpack:///~/superagent/lib/utils.js"],"names":["root","factory","exports","module","define","amd","this","__webpack_require__","moduleId","installedModules","i","l","modules","call","m","c","value","d","name","getter","o","Object","defineProperty","configurable","enumerable","get","n","__esModule","object","property","prototype","hasOwnProperty","p","s","__WEBPACK_AMD_DEFINE_ARRAY__","__WEBPACK_AMD_DEFINE_RESULT__","createReduce","dir","iterator","obj","iteratee","memo","keys","index","length","currentKey","context","optimizeCb","isArrayLike","_","arguments","createPredicateIndexFinder","array","predicate","cb","getLength","createIndexFinder","predicateFind","sortedIndex","item","idx","Math","max","min","slice","isNaN","collectNonEnumProps","nonEnumIdx","nonEnumerableProps","constructor","proto","isFunction","ObjProto","prop","has","contains","push","previousUnderscore","ArrayProto","Array","FuncProto","Function","toString","nativeIsArray","isArray","nativeKeys","nativeBind","bind","nativeCreate","create","Ctor","_wrapped","VERSION","func","argCount","other","collection","accumulator","apply","identity","isObject","matcher","Infinity","createAssigner","keysFunc","undefinedOnly","source","key","baseCreate","result","MAX_ARRAY_INDEX","pow","each","forEach","map","collect","results","reduce","foldl","inject","reduceRight","foldr","find","detect","findIndex","findKey","filter","select","list","reject","negate","every","all","some","any","includes","include","fromIndex","guard","values","indexOf","invoke","method","args","isFunc","pluck","where","attrs","findWhere","computed","lastComputed","shuffle","rand","set","shuffled","random","sample","sortBy","criteria","sort","left","right","a","b","group","behavior","groupBy","indexBy","countBy","toArray","size","partition","pass","fail","first","head","take","initial","last","rest","tail","drop","compact","flatten","input","shallow","strict","startIndex","output","isArguments","j","len","without","difference","uniq","unique","isSorted","isBoolean","seen","union","intersection","argsLength","zip","unzip","findLastIndex","low","high","mid","floor","lastIndexOf","range","start","stop","step","ceil","executeBound","sourceFunc","boundFunc","callingContext","self","TypeError","bound","concat","partial","boundArgs","position","bindAll","Error","memoize","hasher","cache","address","delay","wait","setTimeout","defer","throttle","options","timeout","previous","later","leading","now","remaining","clearTimeout","trailing","debounce","immediate","timestamp","callNow","wrap","wrapper","compose","after","times","before","once","hasEnumBug","propertyIsEnumerable","allKeys","mapObject","pairs","invert","functions","methods","names","extend","extendOwn","assign","pick","oiteratee","omit","String","defaults","props","clone","tap","interceptor","isMatch","eq","aStack","bStack","className","areArrays","aCtor","bCtor","pop","isEqual","isEmpty","isString","isElement","nodeType","type","Int8Array","isFinite","parseFloat","isNumber","isNull","isUndefined","noConflict","constant","noop","propertyOf","matches","accum","Date","getTime","escapeMap","&","<",">","\"","'","`","unescapeMap","createEscaper","escaper","match","join","testRegexp","RegExp","replaceRegexp","string","test","replace","escape","unescape","fallback","idCounter","uniqueId","prefix","id","templateSettings","evaluate","interpolate","noMatch","escapes","\\","\r","\n","
","
","escapeChar","template","text","settings","oldSettings","offset","variable","render","e","data","argument","chain","instance","_chain","mixin","valueOf","toJSON","undefined","Promise","_continueWhile","asyncFunction","then","resolve","request","debug","md5","Cache","AVError","AV","getSessionToken","getServerURLPromise","API_HOST","cn","us","sign","isMasterKey","signature","requestsCount","ajax","resourceUrl","headers","onprogress","count","req","send","on","end","err","res","status","body","header","statusCode","responseText","response","setAppKey","signKey","applicationKey","setHeaders","authOptions","X-LC-Id","applicationId","Content-Type","useMasterKey","_useMasterKey","masterKey","console","warn","hookKey","_config","applicationProduction","userAgent","sessionToken","disableCurrentUser","User","currentAsync","currentUser","_sessionToken","createApiUrl","route","objectId","dataObject","serverURL","APIServerURL","apiURL","charAt","_fetchWhenSave","_where","encodeURIComponent","JSON","stringify","toLowerCase","k","_typeof","cacheServerURL","ttl","setAsync","handleError","error","api_server","location","catch","errorJSON","code","message","parse","setServerUrl","newRegion","region","refreshServerUrlByRouter","url","servers","setServerUrlByRegion","getAsync","AVRequest","OTHER_CAUSE","INTERNAL_SERVER_ERROR","CONNECTION_FAILED","OBJECT_NOT_FOUND","INVALID_QUERY","INVALID_CLASS_NAME","MISSING_OBJECT_ID","INVALID_KEY_NAME","INVALID_POINTER","INVALID_JSON","COMMAND_UNAVAILABLE","NOT_INITIALIZED","INCORRECT_TYPE","INVALID_CHANNEL_NAME","PUSH_MISCONFIGURED","OBJECT_TOO_LARGE","OPERATION_FORBIDDEN","CACHE_MISS","INVALID_NESTED_KEY","INVALID_FILE_NAME","INVALID_ACL","TIMEOUT","INVALID_EMAIL_ADDRESS","MISSING_CONTENT_TYPE","MISSING_CONTENT_LENGTH","INVALID_CONTENT_LENGTH","FILE_TOO_LARGE","FILE_SAVE_ERROR","FILE_DELETE_ERROR","DUPLICATE_VALUE","INVALID_ROLE_NAME","EXCEEDED_QUOTA","SCRIPT_FAILED","VALIDATION_ERROR","INVALID_IMAGE_DATA","UNSAVED_FILE_ERROR","INVALID_PUSH_TIME_ERROR","USERNAME_MISSING","PASSWORD_MISSING","USERNAME_TAKEN","EMAIL_TAKEN","EMAIL_MISSING","EMAIL_NOT_FOUND","SESSION_MISSING","MUST_CREATE_USER_THROUGH_SIGNUP","ACCOUNT_ALREADY_LINKED","LINKED_ID_MISSING","INVALID_LINKED_SESSION","UNSUPPORTED_SERVICE","X_DOMAIN_REQUEST","isNullOrUndefined","x","ensureArray","target","user","useColors","window","process","document","documentElement","style","firebug","exception","table","navigator","parseInt","$1","formatArgs","namespace","humanize","diff","color","splice","lastC","log","save","namespaces","storage","removeItem","load","r","env","DEBUG","localstorage","localStorage","chrome","local","colors","formatters","v","enable","global","AVConfig","EmptyConstructor","inherits","parent","protoProps","staticProps","child","__super__","setProduction","production","_getAVPath","path","substring","_installationId","_getInstallationId","getItemAsync","hexOctet","setItemAsync","_parseDate","iso8601","regexp","exec","year","month","day","hour","minute","second","milli","UTC","_extend","classProps","_getValue","_encode","seenObjects","disallowObjects","_hasData","_toPointer","dirty","_toFullJSON","ACL","isDate","__type","iso","GeoPoint","isRegExp","Relation","Op","File","_decode","__op","pointer","_create","_finishFetch","latitude","longitude","relation","targetClassName","file","_encodeObjectOrArray","encodeAVObject","_arrayEach","_traverse","attributes","newChild","_each","_objectEach","callback","serialize","pushEncodedKeyValuePair","val","subkey","parseString","str","pair","pos","split","decodeURIComponent","parseHeader","line","field","lines","fields","trim","isJSON","mime","Response","xhr","responseType","statusText","_setStatusProperties","getAllResponseHeaders","getResponseHeader","_setHeaderProperties","_responseType","_parseBody","Request","_query","_header","original","rawResponse","emit","new_err","_isResponseOK","del","fn","Emitter","RequestBase","ResponseBase","shouldRetry","getXHR","XMLHttpRequest","protocol","ActiveXObject","serializeObject","types","html","json","xml","urlencoded","form","form-data","application/x-www-form-urlencoded","application/json","_parser","toError","msg","accept","auth","btoa","username","password","query","attach","_data","_getFormData","append","_formData","FormData","_maxRetries","_retries","_retry","_callback","retries","crossDomainError","crossDomain","buffer","ca","agent","pipe","write","_appendQueryString","_sort","queryArr","_isHost","_endCalled","_end","_setTimeouts","onreadystatechange","readyState","_responseTimeoutTimer","timedout","_aborted","handleProgress","direction","total","percent","loaded","hasListeners","upload","open","_withCredentials","withCredentials","contentType","_serializer","setRequestHeader","patch","post","put","g","eval","_classCallCheck","_entries","uri","entry","createUniqueKey","Symbol","toFixed","LISTENERS","CAPTURE","BUBBLE","ATTRIBUTE","newNode","listener","kind","next","Storage","wx","getStorageSync","setStorageSync","setItem","clearStorageSync","errorHandler","event","_readyState","CLOSED","dispatchEvent","errMsg","EventTarget","CONNECTING","OPEN","CLOSING","EVENTS","WebSocket","protocal","_this","_possibleConstructorReturn","__proto__","getPrototypeOf","_url","_protocal","onSocketOpen","onSocketError","onSocketMessage","origin","ports","onSocketClose","reason","wasClean","connectSocket","closeSocket","sendSocketMessage","successCallback","DONE","UNSENT","OPENED","HEADERS_RECEIVED","LOADING","REQUEST_EVENTS","_headers","async","_method","_this2","entries","blobs","restData","_defineProperty","uploadFile","filePath","formData","success","toUpperCase","removeAsync","removeItemAsync","getCacheData","cacheData","expired","expiredAt","syncApiNames","apiName","charenc","utf8","stringToBytes","bin","bytesToString","bytes","charCodeAt","fromCharCode","Commons","CustomEventTarget","EventWrapper","defineCustomEventTarget","createEventWrapper","STOP_IMMEDIATE_PROPAGATION_FLAG","HAS_EVENTTARGET_INTERFACE","writable","addEventListener","capture","node","prev","removeEventListener","wrapped","handleEvent","defaultPrevented","toObject","shouldUseNative","test1","getOwnPropertyNames","test2","order2","test3","letter","getOwnPropertySymbols","propIsEnumerable","from","symbols","to","polyfill","version","polyfills","PUBLIC_KEY","arg1","permissionsById","setReadAccess","setWriteAccess","accessList","userId","allowed","permission","_setAccess","accessType","Role","getName","permissions","_getAccess","getReadAccess","getWriteAccess","setPublicReadAccess","getPublicReadAccess","setPublicWriteAccess","getPublicWriteAccess","getRoleReadAccess","role","getRoleWriteAccess","setRoleReadAccess","setRoleWriteAccess","Cloud","run","resp","rpc","getServerDate","requestSmsCode","mobilePhoneNumber","verifySmsCode","phone","params","eventSplitter","Events","events","calls","_callbacks","shift","off","ctx","trigger","unbind","cos","qiniu","s3","parseBase64","extname","b64Digit","number","encodeBase64","chunks","b1","b2","b3","has2","has3","mimeType","metaData","base64","_extName","owner","current","withURL","__source","createWithoutData","_operations","getACL","_acl","setACL","acl","attrName","_len","_key","attr","thumbnailURL","width","height","quality","scaleToFit","fmt","mode","ownerId","destroy","_fileToken","extName","mime_type","_qiniu_key","_this3","_previousSave","uploadInfo","_token","token","blob","Buffer","isBuffer","uploadPromise","provider","fetch","bucket","arg2","_validate","__defineGetter__","__defineSetter__","_latitude","_longitude","geolocation","getCurrentPosition","coords","radiansTo","point","d2r","PI","lat1rad","long1rad","lat2rad","long2rad","deltaLat","deltaLong","sinDeltaLatDiv2","sin","sinDeltaLongDiv2","asin","sqrt","kilometersTo","milesTo","initialize","appId","appKey","masterKeyWarn","init","Insight","startJob","jobConfig","sql","JobQuery","_skip","_limit","skip","limit","utils","RESERVED_KEYS","checkReservedKey","_mergeMagicFields","_serverData","_opSetQueue","_flags","_hashedJSON","_escapedAttributes","cid","changed","_silent","_pending","silent","_previousAttributes","saveAll","_deepSaveAsync","fetchAll","objects","requests","fetchWhenSave","getObjectId","getCreatedAt","createdAt","getUpdatedAt","updatedAt","_refreshCache","_refreshingCache","_resetCacheForKey","Set","currentChanges","_ensureParentAndKey","escaped","model","specialFields","_startSave","_cancelSave","failedChanges","nextChanges","op","op1","op2","_mergeWithPrevious","_saving","_finishSave","serverData","fetchedObjects","savedChanges","_applyOpSet","fetched","_rebuildAllEstimatedData","hasData","opSet","change","_estimate","_UNSET","wasSet","_rebuildEstimatedDataForKey","previousAttributes","oldValue","newValue","unset","unused_value","Unset","dataToValidate","changes","isRealChange","increment","amount","Increment","add","Add","addUnique","AddUnique","remove","Remove","clear","keysToClear","_getSaveJSON","_canBeSerialized","_canBeSerializedAsValue","fetchOptions","arg3","setOptions","unsavedChildren","unsavedFiles","_findUnsavedChildren","_allPreviousSaves","queryJSON","makeRequest","_makeRequest","serverAttrs","triggerDestroy","isNew","changing","_changing","deleteChanged","hasChanged","changedAttributes","old","diffVal","isValid","validate","disableBeforeHook","ignoreHook","disableAfterHook","hookName","trace","__ignore_hooks","destroyAll","objectsByClassNameAndFlags","flags","ids","_getSubclass","ObjectClass","_classMap","noDefaultACL","NewClassObject","OldClassObject","_className","arg0","newArguments","_LCClassName","register","klass","children","files","canBeSerializedAsValue","promise","batch","newRemaining","readyToStart","bathSavePromise","_initialize","_opDecoderMap","_registerDecoder","opName","decoder","ops","nextOp","_value","_amount","_objects","matchingObj","anObj","adds","removes","_targetClassName","pointerToId","relationsToAdd","relationsToRemove","added","removed","idToPointer","pointers","newAdd","newRemove","newRelation","Installation","Push","cql","push_time","expiration_time","expiration_time_interval","requires","Query","objectClass","_include","_select","_extraOptions","or","queries","q","_orQuery","and","_andQuery","doCloudQuery","pvalues","_newObject","_processResult","errorObject","_order","order","_createRequest","_parseResponse","scan","_ref","orderedBy","batchSize","condition","scan_key","cursor","done","remainResults","equalTo","_addCondition","sizeEqualTo","notEqualTo","lessThan","greaterThan","lessThanOrEqualTo","greaterThanOrEqualTo","containedIn","notContainedIn","containsAll","exists","doesNotExist","regex","modifiers","ignoreCase","multiline","matchesQuery","doesNotMatchQuery","matchesKeyInQuery","queryKey","doesNotMatchKeyInQuery","$or","$and","_quote","startsWith","endsWith","ascending","addAscending","descending","addDescending","near","withinRadians","distance","withinMiles","withinKilometers","withinGeoBox","southwest","northeast","$box","_this4","finished","callbacksDone","FriendShipQuery","_objectClass","_friendshipTag","reverseQuery","parentClass","relationKey","targetClass","redirectClassNameForKey","setName","defaultAcl","getUsers","getRoles","newName","SearchSortBuilder","_sortFields","_addField","missing","whereNear","geo","lat","lon","unit","build","SearchQuery","_sid","_hits","_queryString","_highlights","_sortBuilder","sid","queryString","highlights","builder","hits","hasMore","_hitEnd","reset","_oldSid","appURL","clazz","getUser","currUser","_fetchUserBySessionToken","getUserPointer","Status","imageUrl","inboxType","image","_getDataJSON","sendStatusToFollowers","messageId","sendPrivateStatus","userObjectId","countUnreadStatuses","resetUnreadCount","statusQuery","InboxQuery","_sinceId","_maxId","_inboxType","_owner","sinceId","maxId","inboxQuery","comments","saveOptions","_bucket","uploadUrl","upload_url","uptoken","getWeappLoginCode","login","_isCurrentUser","_cleanupAuthData","isCurrent","authData","_synchronizeAllAuthData","_synchronizeAuthData","authType","_authProviders","getAuthType","restoreAuthentication","_unlinkFrom","_handleSaveResult","makeCurrent","_saveCurrentUser","_linkWith","authenticate","linkWithWeapp","_isLinked","logOut","_logOutWithAll","_logOutWith","deauthenticate","signUp","signUpOrlogInWithMobilePhone","smsCode","logIn","follow","unfollow","followerQuery","followeeQuery","updatePassword","oldPassword","newPassword","old_password","new_password","getUsername","getMobilePhoneNumber","setMobilePhoneNumber","setUsername","setPassword","getEmail","setEmail","email","authenticated","isAuthenticated","refreshSessionToken","_this5","_currentUser","_currentUserMatchesDisk","_CURRENT_USER_KEY","become","session_token","logInWithMobilePhoneSmsCode","mobilePhone","logInWithMobilePhone","signUpOrlogInWithAuthData","platform","_logInWith","loginWithWeapp","_this6","associateWithAuthData","userObj","requestPasswordReset","requestEmailVerify","requestMobilePhoneVerify","requestPasswordResetBySmsCode","resetPasswordBySmsCode","verifyMobilePhone","requestLoginSmsCode","userData","_id","getItem","_registerAuthenticationProvider","apiNames","testKey","dataURItoBlob","dataURI","byteString","atob","ia","Uint8Array","Blob","removeListener","removeAllListeners","callbacks","listeners","base64map","crypt","rotl","rotr","endian","Number","randomBytes","bytesToWords","words","wordsToBytes","bytesToHex","hex","hexToBytes","substr","bytesToBase64","triplet","base64ToBytes","imod4","selectColor","hash","abs","createDebug","enabled","curr","ms","prevTime","coerce","unshift","format","formatter","logFn","skips","disable","stack","objectOrFunction","setScheduler","scheduleFn","customSchedulerFn","setAsap","asapFn","asap","useNextTick","nextTick","flush","useVertxTimer","vertxNext","useSetTimeout","useMutationObserver","iterations","observer","BrowserMutationObserver","createTextNode","observe","characterData","useMessageChannel","channel","MessageChannel","port1","onmessage","port2","postMessage","globalSetTimeout","queue","arg","attemptVertx","vertx","runOnLoop","runOnContext","onFulfillment","onRejection","_arguments","PROMISE_ID","makePromise","_state","invokeCallback","_result","subscribe","Constructor","_resolve","selfFulfillment","cannotReturnOwn","getThen","GET_THEN_ERROR","tryThen","fulfillmentHandler","rejectionHandler","handleForeignThenable","thenable","sealed","fulfill","_reject","_label","handleOwnThenable","FULFILLED","REJECTED","handleMaybeThenable","maybeThenable","then$$","publishRejection","_onerror","publish","PENDING","_subscribers","subscribers","settled","detail","ErrorObject","tryCatch","TRY_CATCH_ERROR","hasCallback","succeeded","failed","initializePromise","resolver","nextId","Enumerator","_instanceConstructor","_input","_remaining","_enumerate","validationError","race","needsResolver","needsNew","P","promiseToString","cast","_isArray","scheduleFlush","browserWindow","browserGlobal","MutationObserver","WebKitMutationObserver","isNode","isWorker","Uint8ClampedArray","importScripts","_eachEntry","resolve$$","_then","_settledAt","_willSettleAt","state","enumerator","_setScheduler","_setAsap","_asap","getAttributeListener","eventTarget","setAttributeListener","EventTargetBase","descripter","CANCELED_FLAG","ORIGINAL_EVENT","wrapperPrototypeDefinition","freeze","stopPropagation","stopImmediatePropagation","preventDefault","cancelable","timeStamp","propertyDefinition","currentTarget","eventPhase","bubbles","Boolean","isTrusted","isSlowBuffer","readFloatLE","_isBuffer","localStorageMemory","encoding","FF","_ff","GG","_gg","HH","_hh","II","_ii","aa","bb","cc","dd","t","_blocksize","_digestsize","digestbytes","asBytes","asString","y","h","fmtShort","round","fmtLong","plural","long","tag","_timer","_timeout","_responseTimeout","option","deadline","retry","_fullfilledPromise","innerResolve","innerReject","use","ok","_okCallback","getHeader","abort","redirects","_maxRedirects","isObj","sortQuery","_timeoutError","errno","ct","links","link","parseLinks","statusType","info","redirect","clientError","serverError","accepted","noContent","badRequest","unauthorized","notAcceptable","forbidden","notFound","ERROR_CODES","parts","rel","cleanHeader","shouldStripCookie"],"mappings":"CAAA,SAAAA,EAAAC,GACA,gBAAAC,UAAA,gBAAAC,QACAA,OAAAD,QAAAD,IACA,kBAAAG,SAAAA,OAAAC,IACAD,UAAAH,GACA,gBAAAC,SACAA,QAAA,GAAAD,IAEAD,EAAA,GAAAC,KACCK,KAAA,WACD,mBCNA,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAN,OAGA,IAAAC,GAAAM,EAAAD,IACAE,EAAAF,EACAG,GAAA,EACAT,WAUA,OANAU,GAA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AAw+B,GAAAx+B,EAAAG,MAAA,SACA7K,EAAAkpC,EAAA,GAAAthD,MAAA,GAAA,GACAuhD,EAAAD,EAAA,GAAAr+B,MAAA,SAAA,GAAAjjB,MAAA,GAAA,EAEA,OADAzB,GAAAgjD,GAAAnpC,EACA7Z,QAYArC,EAAAslD,YAAA,SAAA/sC,EAAAgtC,GAQA,aAPAhtC,GAAA,sBACAA,GAAA,wBACAA,GAAA,2BACAA,GAAA,KACAgtC,SACAhtC,GAAA,OAEAA","file":"av-weapp-min.js","sourceRoot":"","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"AV\"] = factory();\n\telse\n\t\troot[\"AV\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// identity function for calling harmony imports with the correct context\n \t__webpack_require__.i = function(value) { return value; };\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 30);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 49fd826478e50efdbf60","// Underscore.js 1.8.3\n// http://underscorejs.org\n// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n// Underscore may be freely distributed under the MIT license.\n\n(function() {\n\n // Baseline setup\n // --------------\n\n // Establish the root object, `window` in the browser, or `exports` on the server.\n var root = this;\n\n // Save the previous value of the `_` variable.\n var previousUnderscore = root._;\n\n // Save bytes in the minified (but not gzipped) version:\n var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;\n\n // Create quick reference variables for speed access to core prototypes.\n var\n push = ArrayProto.push,\n slice = ArrayProto.slice,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty;\n\n // All **ECMAScript 5** native function implementations that we hope to use\n // are declared here.\n var\n nativeIsArray = Array.isArray,\n nativeKeys = Object.keys,\n nativeBind = FuncProto.bind,\n nativeCreate = Object.create;\n\n // Naked function reference for surrogate-prototype-swapping.\n var Ctor = function(){};\n\n // Create a safe reference to the Underscore object for use below.\n var _ = function(obj) {\n if (obj instanceof _) return obj;\n if (!(this instanceof _)) return new _(obj);\n this._wrapped = obj;\n };\n\n // Export the Underscore object for **Node.js**, with\n // backwards-compatibility for the old `require()` API. If we're in\n // the browser, add `_` as a global object.\n if (typeof exports !== 'undefined') {\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = _;\n }\n exports._ = _;\n } else {\n root._ = _;\n }\n\n // Current version.\n _.VERSION = '1.8.3';\n\n // Internal function that returns an efficient (for current engines) version\n // of the passed-in callback, to be repeatedly applied in other Underscore\n // functions.\n var optimizeCb = function(func, context, argCount) {\n if (context === void 0) return func;\n switch (argCount == null ? 3 : argCount) {\n case 1: return function(value) {\n return func.call(context, value);\n };\n case 2: return function(value, other) {\n return func.call(context, value, other);\n };\n case 3: return function(value, index, collection) {\n return func.call(context, value, index, collection);\n };\n case 4: return function(accumulator, value, index, collection) {\n return func.call(context, accumulator, value, index, collection);\n };\n }\n return function() {\n return func.apply(context, arguments);\n };\n };\n\n // A mostly-internal function to generate callbacks that can be applied\n // to each element in a collection, returning the desired result — either\n // identity, an arbitrary callback, a property matcher, or a property accessor.\n var cb = function(value, context, argCount) {\n if (value == null) return _.identity;\n if (_.isFunction(value)) return optimizeCb(value, context, argCount);\n if (_.isObject(value)) return _.matcher(value);\n return _.property(value);\n };\n _.iteratee = function(value, context) {\n return cb(value, context, Infinity);\n };\n\n // An internal function for creating assigner functions.\n var createAssigner = function(keysFunc, undefinedOnly) {\n return function(obj) {\n var length = arguments.length;\n if (length < 2 || obj == null) return obj;\n for (var index = 1; index < length; index++) {\n var source = arguments[index],\n keys = keysFunc(source),\n l = keys.length;\n for (var i = 0; i < l; i++) {\n var key = keys[i];\n if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];\n }\n }\n return obj;\n };\n };\n\n // An internal function for creating a new object that inherits from another.\n var baseCreate = function(prototype) {\n if (!_.isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n };\n\n var property = function(key) {\n return function(obj) {\n return obj == null ? void 0 : obj[key];\n };\n };\n\n // Helper for collection methods to determine whether a collection\n // should be iterated as an array or as an object\n // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength\n // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094\n var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;\n var getLength = property('length');\n var isArrayLike = function(collection) {\n var length = getLength(collection);\n return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;\n };\n\n // Collection Functions\n // --------------------\n\n // The cornerstone, an `each` implementation, aka `forEach`.\n // Handles raw objects in addition to array-likes. Treats all\n // sparse array-likes as if they were dense.\n _.each = _.forEach = function(obj, iteratee, context) {\n iteratee = optimizeCb(iteratee, context);\n var i, length;\n if (isArrayLike(obj)) {\n for (i = 0, length = obj.length; i < length; i++) {\n iteratee(obj[i], i, obj);\n }\n } else {\n var keys = _.keys(obj);\n for (i = 0, length = keys.length; i < length; i++) {\n iteratee(obj[keys[i]], keys[i], obj);\n }\n }\n return obj;\n };\n\n // Return the results of applying the iteratee to each element.\n _.map = _.collect = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n results = Array(length);\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n results[index] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Create a reducing function iterating left or right.\n function createReduce(dir) {\n // Optimized iterator function as using arguments.length\n // in the main function will deoptimize the, see #1991.\n function iterator(obj, iteratee, memo, keys, index, length) {\n for (; index >= 0 && index < length; index += dir) {\n var currentKey = keys ? keys[index] : index;\n memo = iteratee(memo, obj[currentKey], currentKey, obj);\n }\n return memo;\n }\n\n return function(obj, iteratee, memo, context) {\n iteratee = optimizeCb(iteratee, context, 4);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n index = dir > 0 ? 0 : length - 1;\n // Determine the initial value if none is provided.\n if (arguments.length < 3) {\n memo = obj[keys ? keys[index] : index];\n index += dir;\n }\n return iterator(obj, iteratee, memo, keys, index, length);\n };\n }\n\n // **Reduce** builds up a single result from a list of values, aka `inject`,\n // or `foldl`.\n _.reduce = _.foldl = _.inject = createReduce(1);\n\n // The right-associative version of reduce, also known as `foldr`.\n _.reduceRight = _.foldr = createReduce(-1);\n\n // Return the first value which passes a truth test. Aliased as `detect`.\n _.find = _.detect = function(obj, predicate, context) {\n var key;\n if (isArrayLike(obj)) {\n key = _.findIndex(obj, predicate, context);\n } else {\n key = _.findKey(obj, predicate, context);\n }\n if (key !== void 0 && key !== -1) return obj[key];\n };\n\n // Return all the elements that pass a truth test.\n // Aliased as `select`.\n _.filter = _.select = function(obj, predicate, context) {\n var results = [];\n predicate = cb(predicate, context);\n _.each(obj, function(value, index, list) {\n if (predicate(value, index, list)) results.push(value);\n });\n return results;\n };\n\n // Return all the elements for which a truth test fails.\n _.reject = function(obj, predicate, context) {\n return _.filter(obj, _.negate(cb(predicate)), context);\n };\n\n // Determine whether all of the elements match a truth test.\n // Aliased as `all`.\n _.every = _.all = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (!predicate(obj[currentKey], currentKey, obj)) return false;\n }\n return true;\n };\n\n // Determine if at least one element in the object matches a truth test.\n // Aliased as `any`.\n _.some = _.any = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (predicate(obj[currentKey], currentKey, obj)) return true;\n }\n return false;\n };\n\n // Determine if the array or object contains a given item (using `===`).\n // Aliased as `includes` and `include`.\n _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n if (typeof fromIndex != 'number' || guard) fromIndex = 0;\n return _.indexOf(obj, item, fromIndex) >= 0;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n var isFunc = _.isFunction(method);\n return _.map(obj, function(value) {\n var func = isFunc ? method : value[method];\n return func == null ? func : func.apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, _.property(key));\n };\n\n // Convenience version of a common use case of `filter`: selecting only objects\n // containing specific `key:value` pairs.\n _.where = function(obj, attrs) {\n return _.filter(obj, _.matcher(attrs));\n };\n\n // Convenience version of a common use case of `find`: getting the first object\n // containing specific `key:value` pairs.\n _.findWhere = function(obj, attrs) {\n return _.find(obj, _.matcher(attrs));\n };\n\n // Return the maximum element (or element-based computation).\n _.max = function(obj, iteratee, context) {\n var result = -Infinity, lastComputed = -Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value > result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed > lastComputed || computed === -Infinity && result === -Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iteratee, context) {\n var result = Infinity, lastComputed = Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value < result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed < lastComputed || computed === Infinity && result === Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Shuffle a collection, using the modern version of the\n // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).\n _.shuffle = function(obj) {\n var set = isArrayLike(obj) ? obj : _.values(obj);\n var length = set.length;\n var shuffled = Array(length);\n for (var index = 0, rand; index < length; index++) {\n rand = _.random(0, index);\n if (rand !== index) shuffled[index] = shuffled[rand];\n shuffled[rand] = set[index];\n }\n return shuffled;\n };\n\n // Sample **n** random values from a collection.\n // If **n** is not specified, returns a single random element.\n // The internal `guard` argument allows it to work with `map`.\n _.sample = function(obj, n, guard) {\n if (n == null || guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n return obj[_.random(obj.length - 1)];\n }\n return _.shuffle(obj).slice(0, Math.max(0, n));\n };\n\n // Sort the object's values by a criterion produced by an iteratee.\n _.sortBy = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value: value,\n index: index,\n criteria: iteratee(value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria;\n var b = right.criteria;\n if (a !== b) {\n if (a > b || a === void 0) return 1;\n if (a < b || b === void 0) return -1;\n }\n return left.index - right.index;\n }), 'value');\n };\n\n // An internal function used for aggregate \"group by\" operations.\n var group = function(behavior) {\n return function(obj, iteratee, context) {\n var result = {};\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index) {\n var key = iteratee(value, index, obj);\n behavior(result, value, key);\n });\n return result;\n };\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key].push(value); else result[key] = [value];\n });\n\n // Indexes the object's values by a criterion, similar to `groupBy`, but for\n // when you know that your index values will be unique.\n _.indexBy = group(function(result, value, key) {\n result[key] = value;\n });\n\n // Counts instances of an object that group by a certain criterion. Pass\n // either a string attribute to count by, or a function that returns the\n // criterion.\n _.countBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key]++; else result[key] = 1;\n });\n\n // Safely create a real, live array from anything iterable.\n _.toArray = function(obj) {\n if (!obj) return [];\n if (_.isArray(obj)) return slice.call(obj);\n if (isArrayLike(obj)) return _.map(obj, _.identity);\n return _.values(obj);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n if (obj == null) return 0;\n return isArrayLike(obj) ? obj.length : _.keys(obj).length;\n };\n\n // Split a collection into two arrays: one whose elements all satisfy the given\n // predicate, and one whose elements all do not satisfy the predicate.\n _.partition = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var pass = [], fail = [];\n _.each(obj, function(value, key, obj) {\n (predicate(value, key, obj) ? pass : fail).push(value);\n });\n return [pass, fail];\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head` and `take`. The **guard** check\n // allows it to work with `_.map`.\n _.first = _.head = _.take = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[0];\n return _.initial(array, array.length - n);\n };\n\n // Returns everything but the last entry of the array. Especially useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array.\n _.last = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[array.length - 1];\n return _.rest(array, Math.max(0, array.length - n));\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.\n // Especially useful on the arguments object. Passing an **n** will return\n // the rest N values in the array.\n _.rest = _.tail = _.drop = function(array, n, guard) {\n return slice.call(array, n == null || guard ? 1 : n);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, _.identity);\n };\n\n // Internal implementation of a recursive `flatten` function.\n var flatten = function(input, shallow, strict, startIndex) {\n var output = [], idx = 0;\n for (var i = startIndex || 0, length = getLength(input); i < length; i++) {\n var value = input[i];\n if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {\n //flatten current level of array or arguments object\n if (!shallow) value = flatten(value, shallow, strict);\n var j = 0, len = value.length;\n output.length += len;\n while (j < len) {\n output[idx++] = value[j++];\n }\n } else if (!strict) {\n output[idx++] = value;\n }\n }\n return output;\n };\n\n // Flatten out an array, either recursively (by default), or just one level.\n _.flatten = function(array, shallow) {\n return flatten(array, shallow, false);\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iteratee, context) {\n if (!_.isBoolean(isSorted)) {\n context = iteratee;\n iteratee = isSorted;\n isSorted = false;\n }\n if (iteratee != null) iteratee = cb(iteratee, context);\n var result = [];\n var seen = [];\n for (var i = 0, length = getLength(array); i < length; i++) {\n var value = array[i],\n computed = iteratee ? iteratee(value, i, array) : value;\n if (isSorted) {\n if (!i || seen !== computed) result.push(value);\n seen = computed;\n } else if (iteratee) {\n if (!_.contains(seen, computed)) {\n seen.push(computed);\n result.push(value);\n }\n } else if (!_.contains(result, value)) {\n result.push(value);\n }\n }\n return result;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(flatten(arguments, true, true));\n };\n\n // Produce an array that contains every item shared between all the\n // passed-in arrays.\n _.intersection = function(array) {\n var result = [];\n var argsLength = arguments.length;\n for (var i = 0, length = getLength(array); i < length; i++) {\n var item = array[i];\n if (_.contains(result, item)) continue;\n for (var j = 1; j < argsLength; j++) {\n if (!_.contains(arguments[j], item)) break;\n }\n if (j === argsLength) result.push(item);\n }\n return result;\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = flatten(arguments, true, true, 1);\n return _.filter(array, function(value){\n return !_.contains(rest, value);\n });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function() {\n return _.unzip(arguments);\n };\n\n // Complement of _.zip. Unzip accepts an array of arrays and groups\n // each array's elements on shared indices\n _.unzip = function(array) {\n var length = array && _.max(array, getLength).length || 0;\n var result = Array(length);\n\n for (var index = 0; index < length; index++) {\n result[index] = _.pluck(array, index);\n }\n return result;\n };\n\n // Converts lists into objects. Pass either a single array of `[key, value]`\n // pairs, or two parallel arrays of the same length -- one of keys, and one of\n // the corresponding values.\n _.object = function(list, values) {\n var result = {};\n for (var i = 0, length = getLength(list); i < length; i++) {\n if (values) {\n result[list[i]] = values[i];\n } else {\n result[list[i][0]] = list[i][1];\n }\n }\n return result;\n };\n\n // Generator function to create the findIndex and findLastIndex functions\n function createPredicateIndexFinder(dir) {\n return function(array, predicate, context) {\n predicate = cb(predicate, context);\n var length = getLength(array);\n var index = dir > 0 ? 0 : length - 1;\n for (; index >= 0 && index < length; index += dir) {\n if (predicate(array[index], index, array)) return index;\n }\n return -1;\n };\n }\n\n // Returns the first index on an array-like that passes a predicate test\n _.findIndex = createPredicateIndexFinder(1);\n _.findLastIndex = createPredicateIndexFinder(-1);\n\n // Use a comparator function to figure out the smallest index at which\n // an object should be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iteratee, context) {\n iteratee = cb(iteratee, context, 1);\n var value = iteratee(obj);\n var low = 0, high = getLength(array);\n while (low < high) {\n var mid = Math.floor((low + high) / 2);\n if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;\n }\n return low;\n };\n\n // Generator function to create the indexOf and lastIndexOf functions\n function createIndexFinder(dir, predicateFind, sortedIndex) {\n return function(array, item, idx) {\n var i = 0, length = getLength(array);\n if (typeof idx == 'number') {\n if (dir > 0) {\n i = idx >= 0 ? idx : Math.max(idx + length, i);\n } else {\n length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;\n }\n } else if (sortedIndex && idx && length) {\n idx = sortedIndex(array, item);\n return array[idx] === item ? idx : -1;\n }\n if (item !== item) {\n idx = predicateFind(slice.call(array, i, length), _.isNaN);\n return idx >= 0 ? idx + i : -1;\n }\n for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {\n if (array[idx] === item) return idx;\n }\n return -1;\n };\n }\n\n // Return the position of the first occurrence of an item in an array,\n // or -1 if the item is not included in the array.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);\n _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (stop == null) {\n stop = start || 0;\n start = 0;\n }\n step = step || 1;\n\n var length = Math.max(Math.ceil((stop - start) / step), 0);\n var range = Array(length);\n\n for (var idx = 0; idx < length; idx++, start += step) {\n range[idx] = start;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Determines whether to execute a function as a constructor\n // or a normal function with the provided arguments\n var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {\n if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);\n var self = baseCreate(sourceFunc.prototype);\n var result = sourceFunc.apply(self, args);\n if (_.isObject(result)) return result;\n return self;\n };\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if\n // available.\n _.bind = function(func, context) {\n if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');\n var args = slice.call(arguments, 2);\n var bound = function() {\n return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));\n };\n return bound;\n };\n\n // Partially apply a function by creating a version that has had some of its\n // arguments pre-filled, without changing its dynamic `this` context. _ acts\n // as a placeholder, allowing any combination of arguments to be pre-filled.\n _.partial = function(func) {\n var boundArgs = slice.call(arguments, 1);\n var bound = function() {\n var position = 0, length = boundArgs.length;\n var args = Array(length);\n for (var i = 0; i < length; i++) {\n args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];\n }\n while (position < arguments.length) args.push(arguments[position++]);\n return executeBound(func, bound, this, this, args);\n };\n return bound;\n };\n\n // Bind a number of an object's methods to that object. Remaining arguments\n // are the method names to be bound. Useful for ensuring that all callbacks\n // defined on an object belong to it.\n _.bindAll = function(obj) {\n var i, length = arguments.length, key;\n if (length <= 1) throw new Error('bindAll must be passed function names');\n for (i = 1; i < length; i++) {\n key = arguments[i];\n obj[key] = _.bind(obj[key], obj);\n }\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memoize = function(key) {\n var cache = memoize.cache;\n var address = '' + (hasher ? hasher.apply(this, arguments) : key);\n if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);\n return cache[address];\n };\n memoize.cache = {};\n return memoize;\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){\n return func.apply(null, args);\n }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack has\n // cleared.\n _.defer = _.partial(_.delay, _, 1);\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time. Normally, the throttled function will run\n // as much as it can, without ever going more than once per `wait` duration;\n // but if you'd like to disable the execution on the leading edge, pass\n // `{leading: false}`. To disable execution on the trailing edge, ditto.\n _.throttle = function(func, wait, options) {\n var context, args, result;\n var timeout = null;\n var previous = 0;\n if (!options) options = {};\n var later = function() {\n previous = options.leading === false ? 0 : _.now();\n timeout = null;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n };\n return function() {\n var now = _.now();\n if (!previous && options.leading === false) previous = now;\n var remaining = wait - (now - previous);\n context = this;\n args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(later, remaining);\n }\n return result;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being called for\n // N milliseconds. If `immediate` is passed, trigger the function on the\n // leading edge, instead of the trailing.\n _.debounce = function(func, wait, immediate) {\n var timeout, args, context, timestamp, result;\n\n var later = function() {\n var last = _.now() - timestamp;\n\n if (last < wait && last >= 0) {\n timeout = setTimeout(later, wait - last);\n } else {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n }\n }\n };\n\n return function() {\n context = this;\n args = arguments;\n timestamp = _.now();\n var callNow = immediate && !timeout;\n if (!timeout) timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n context = args = null;\n }\n\n return result;\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return _.partial(wrapper, func);\n };\n\n // Returns a negated version of the passed-in predicate.\n _.negate = function(predicate) {\n return function() {\n return !predicate.apply(this, arguments);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var args = arguments;\n var start = args.length - 1;\n return function() {\n var i = start;\n var result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n };\n\n // Returns a function that will only be executed on and after the Nth call.\n _.after = function(times, func) {\n return function() {\n if (--times < 1) {\n return func.apply(this, arguments);\n }\n };\n };\n\n // Returns a function that will only be executed up to (but not including) the Nth call.\n _.before = function(times, func) {\n var memo;\n return function() {\n if (--times > 0) {\n memo = func.apply(this, arguments);\n }\n if (times <= 1) func = null;\n return memo;\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = _.partial(_.before, 2);\n\n // Object Functions\n // ----------------\n\n // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.\n var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n function collectNonEnumProps(obj, keys) {\n var nonEnumIdx = nonEnumerableProps.length;\n var constructor = obj.constructor;\n var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;\n\n // Constructor is a special case.\n var prop = 'constructor';\n if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);\n\n while (nonEnumIdx--) {\n prop = nonEnumerableProps[nonEnumIdx];\n if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {\n keys.push(prop);\n }\n }\n }\n\n // Retrieve the names of an object's own properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = function(obj) {\n if (!_.isObject(obj)) return [];\n if (nativeKeys) return nativeKeys(obj);\n var keys = [];\n for (var key in obj) if (_.has(obj, key)) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve all the property names of an object.\n _.allKeys = function(obj) {\n if (!_.isObject(obj)) return [];\n var keys = [];\n for (var key in obj) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var values = Array(length);\n for (var i = 0; i < length; i++) {\n values[i] = obj[keys[i]];\n }\n return values;\n };\n\n // Returns the results of applying the iteratee to each element of the object\n // In contrast to _.map it returns an object\n _.mapObject = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = _.keys(obj),\n length = keys.length,\n results = {},\n currentKey;\n for (var index = 0; index < length; index++) {\n currentKey = keys[index];\n results[currentKey] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Convert an object into a list of `[key, value]` pairs.\n _.pairs = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var pairs = Array(length);\n for (var i = 0; i < length; i++) {\n pairs[i] = [keys[i], obj[keys[i]]];\n }\n return pairs;\n };\n\n // Invert the keys and values of an object. The values must be serializable.\n _.invert = function(obj) {\n var result = {};\n var keys = _.keys(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n result[obj[keys[i]]] = keys[i];\n }\n return result;\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = createAssigner(_.allKeys);\n\n // Assigns a given object with all the own properties in the passed-in object(s)\n // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n _.extendOwn = _.assign = createAssigner(_.keys);\n\n // Returns the first key on an object that passes a predicate test\n _.findKey = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = _.keys(obj), key;\n for (var i = 0, length = keys.length; i < length; i++) {\n key = keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n };\n\n // Return a copy of the object only containing the whitelisted properties.\n _.pick = function(object, oiteratee, context) {\n var result = {}, obj = object, iteratee, keys;\n if (obj == null) return result;\n if (_.isFunction(oiteratee)) {\n keys = _.allKeys(obj);\n iteratee = optimizeCb(oiteratee, context);\n } else {\n keys = flatten(arguments, false, false, 1);\n iteratee = function(value, key, obj) { return key in obj; };\n obj = Object(obj);\n }\n for (var i = 0, length = keys.length; i < length; i++) {\n var key = keys[i];\n var value = obj[key];\n if (iteratee(value, key, obj)) result[key] = value;\n }\n return result;\n };\n\n // Return a copy of the object without the blacklisted properties.\n _.omit = function(obj, iteratee, context) {\n if (_.isFunction(iteratee)) {\n iteratee = _.negate(iteratee);\n } else {\n var keys = _.map(flatten(arguments, false, false, 1), String);\n iteratee = function(value, key) {\n return !_.contains(keys, key);\n };\n }\n return _.pick(obj, iteratee, context);\n };\n\n // Fill in a given object with default properties.\n _.defaults = createAssigner(_.allKeys, true);\n\n // Creates an object that inherits from the given prototype object.\n // If additional properties are provided then they will be added to the\n // created object.\n _.create = function(prototype, props) {\n var result = baseCreate(prototype);\n if (props) _.extendOwn(result, props);\n return result;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Returns whether an object has a given set of `key:value` pairs.\n _.isMatch = function(object, attrs) {\n var keys = _.keys(attrs), length = keys.length;\n if (object == null) return !length;\n var obj = Object(object);\n for (var i = 0; i < length; i++) {\n var key = keys[i];\n if (attrs[key] !== obj[key] || !(key in obj)) return false;\n }\n return true;\n };\n\n\n // Internal recursive comparison function for `isEqual`.\n var eq = function(a, b, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) return a !== 0 || 1 / a === 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwrap any wrapped objects.\n if (a instanceof _) a = a._wrapped;\n if (b instanceof _) b = b._wrapped;\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case '[object RegExp]':\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return '' + a === '' + b;\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN\n if (+a !== +a) return +b !== +b;\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case '[object Date]':\n case '[object Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n }\n\n var areArrays = className === '[object Array]';\n if (!areArrays) {\n if (typeof a != 'object' || typeof b != 'object') return false;\n\n // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n var aCtor = a.constructor, bCtor = b.constructor;\n if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&\n _.isFunction(bCtor) && bCtor instanceof bCtor)\n && ('constructor' in a && 'constructor' in b)) {\n return false;\n }\n }\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) return bStack[length] === b;\n }\n\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n\n // Recursively compare objects and arrays.\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n if (length !== b.length) return false;\n // Deep compare the contents, ignoring non-numeric properties.\n while (length--) {\n if (!eq(a[length], b[length], aStack, bStack)) return false;\n }\n } else {\n // Deep compare objects.\n var keys = _.keys(a), key;\n length = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n if (_.keys(b).length !== length) return false;\n while (length--) {\n // Deep compare each member\n key = keys[length];\n if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return true;\n };\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (obj == null) return true;\n if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;\n return _.keys(obj).length === 0;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj.nodeType === 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) === '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n var type = typeof obj;\n return type === 'function' || type === 'object' && !!obj;\n };\n\n // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.\n _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {\n _['is' + name] = function(obj) {\n return toString.call(obj) === '[object ' + name + ']';\n };\n });\n\n // Define a fallback version of the method in browsers (ahem, IE < 9), where\n // there isn't any inspectable \"Arguments\" type.\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return _.has(obj, 'callee');\n };\n }\n\n // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,\n // IE 11 (#1621), and in Safari 8 (#1929).\n if (typeof /./ != 'function' && typeof Int8Array != 'object') {\n _.isFunction = function(obj) {\n return typeof obj == 'function' || false;\n };\n }\n\n // Is a given object a finite number?\n _.isFinite = function(obj) {\n return isFinite(obj) && !isNaN(parseFloat(obj));\n };\n\n // Is the given value `NaN`? (NaN is the only number which does not equal itself).\n _.isNaN = function(obj) {\n return _.isNumber(obj) && obj !== +obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) === '[object Boolean]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Shortcut function for checking if an object has a given property directly\n // on itself (in other words, not on a prototype).\n _.has = function(obj, key) {\n return obj != null && hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning the `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iteratees.\n _.identity = function(value) {\n return value;\n };\n\n // Predicate-generating functions. Often useful outside of Underscore.\n _.constant = function(value) {\n return function() {\n return value;\n };\n };\n\n _.noop = function(){};\n\n _.property = property;\n\n // Generates a function for a given object that returns a given property.\n _.propertyOf = function(obj) {\n return obj == null ? function(){} : function(key) {\n return obj[key];\n };\n };\n\n // Returns a predicate for checking whether an object has a given set of\n // `key:value` pairs.\n _.matcher = _.matches = function(attrs) {\n attrs = _.extendOwn({}, attrs);\n return function(obj) {\n return _.isMatch(obj, attrs);\n };\n };\n\n // Run a function **n** times.\n _.times = function(n, iteratee, context) {\n var accum = Array(Math.max(0, n));\n iteratee = optimizeCb(iteratee, context, 1);\n for (var i = 0; i < n; i++) accum[i] = iteratee(i);\n return accum;\n };\n\n // Return a random integer between min and max (inclusive).\n _.random = function(min, max) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n };\n\n // A (possibly faster) way to get the current timestamp as an integer.\n _.now = Date.now || function() {\n return new Date().getTime();\n };\n\n // List of HTML entities for escaping.\n var escapeMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`'\n };\n var unescapeMap = _.invert(escapeMap);\n\n // Functions for escaping and unescaping strings to/from HTML interpolation.\n var createEscaper = function(map) {\n var escaper = function(match) {\n return map[match];\n };\n // Regexes for identifying a key that needs to be escaped\n var source = '(?:' + _.keys(map).join('|') + ')';\n var testRegexp = RegExp(source);\n var replaceRegexp = RegExp(source, 'g');\n return function(string) {\n string = string == null ? '' : '' + string;\n return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;\n };\n };\n _.escape = createEscaper(escapeMap);\n _.unescape = createEscaper(unescapeMap);\n\n // If the value of the named `property` is a function then invoke it with the\n // `object` as context; otherwise, return it.\n _.result = function(object, property, fallback) {\n var value = object == null ? void 0 : object[property];\n if (value === void 0) {\n value = fallback;\n }\n return _.isFunction(value) ? value.call(object) : value;\n };\n\n // Generate a unique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = ++idCounter + '';\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /(.)^/;\n\n // Certain characters need to be escaped so that they can be put into a\n // string literal.\n var escapes = {\n \"'\": \"'\",\n '\\\\': '\\\\',\n '\\r': 'r',\n '\\n': 'n',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n var escaper = /\\\\|'|\\r|\\n|\\u2028|\\u2029/g;\n\n var escapeChar = function(match) {\n return '\\\\' + escapes[match];\n };\n\n // JavaScript micro-templating, similar to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n // NB: `oldSettings` only exists for backwards compatibility.\n _.template = function(text, settings, oldSettings) {\n if (!settings && oldSettings) settings = oldSettings;\n settings = _.defaults({}, settings, _.templateSettings);\n\n // Combine delimiters into one regular expression via alternation.\n var matcher = RegExp([\n (settings.escape || noMatch).source,\n (settings.interpolate || noMatch).source,\n (settings.evaluate || noMatch).source\n ].join('|') + '|$', 'g');\n\n // Compile the template source, escaping string literals appropriately.\n var index = 0;\n var source = \"__p+='\";\n text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {\n source += text.slice(index, offset).replace(escaper, escapeChar);\n index = offset + match.length;\n\n if (escape) {\n source += \"'+\\n((__t=(\" + escape + \"))==null?'':_.escape(__t))+\\n'\";\n } else if (interpolate) {\n source += \"'+\\n((__t=(\" + interpolate + \"))==null?'':__t)+\\n'\";\n } else if (evaluate) {\n source += \"';\\n\" + evaluate + \"\\n__p+='\";\n }\n\n // Adobe VMs need the match returned to produce the correct offest.\n return match;\n });\n source += \"';\\n\";\n\n // If a variable is not specified, place data values in local scope.\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = \"var __t,__p='',__j=Array.prototype.join,\" +\n \"print=function(){__p+=__j.call(arguments,'');};\\n\" +\n source + 'return __p;\\n';\n\n try {\n var render = new Function(settings.variable || 'obj', '_', source);\n } catch (e) {\n e.source = source;\n throw e;\n }\n\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n // Provide the compiled source as a convenience for precompilation.\n var argument = settings.variable || 'obj';\n template.source = 'function(' + argument + '){\\n' + source + '}';\n\n return template;\n };\n\n // Add a \"chain\" function. Start chaining a wrapped Underscore object.\n _.chain = function(obj) {\n var instance = _(obj);\n instance._chain = true;\n return instance;\n };\n\n // OOP\n // ---------------\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n\n // Helper function to continue chaining intermediate results.\n var result = function(instance, obj) {\n return instance._chain ? _(obj).chain() : obj;\n };\n\n // Add your own custom functions to the Underscore object.\n _.mixin = function(obj) {\n _.each(_.functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return result(this, func.apply(_, args));\n };\n });\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n var obj = this._wrapped;\n method.apply(obj, arguments);\n if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];\n return result(this, obj);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n _.each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n return result(this, method.apply(this._wrapped, arguments));\n };\n });\n\n // Extracts the result from a wrapped and chained object.\n _.prototype.value = function() {\n return this._wrapped;\n };\n\n // Provide unwrapping proxy for some methods used in engine operations\n // such as arithmetic and JSON stringification.\n _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;\n\n _.prototype.toString = function() {\n return '' + this._wrapped;\n };\n\n // AMD registration happens at the end for compatibility with AMD loaders\n // that may not enforce next-turn semantics on modules. Even though general\n // practice for AMD registration is to be anonymous, underscore registers\n // as a named module because, like jQuery, it is a base library that is\n // popular enough to be bundled in a third party lib, but not be part of\n // an AMD load request. Those cases could generate an error when an\n // anonymous define() is called outside of a loader request.\n if (typeof define === 'function' && define.amd) {\n define('underscore', [], function() {\n return _;\n });\n }\n}.call(this));\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/underscore/underscore.js\n// module id = 0\n// module chunks = 0","var _ = require('underscore');\nvar Promise = require('es6-promise').Promise;\n\nPromise._continueWhile = function(predicate, asyncFunction) {\n if (predicate()) {\n return asyncFunction().then(function() {\n return Promise._continueWhile(predicate, asyncFunction);\n });\n }\n return Promise.resolve();\n};\n\nmodule.exports = Promise;\n\n\n\n// WEBPACK FOOTER //\n// ./src/promise.js","const request = require('superagent');\nconst debug = require('debug')('leancloud:request');\nconst md5 = require('md5');\nconst Promise = require('./promise');\nconst Cache = require('./cache');\nconst AVError = require('./error');\nconst AV = require('./av');\nconst _ = require('underscore');\nconst {\n getSessionToken,\n} = require('./utils');\n\nlet getServerURLPromise;\n\n// 服务器请求的节点 host\nconst API_HOST = {\n cn: 'https://api.leancloud.cn',\n us: 'https://us-api.leancloud.cn',\n};\n\n// 计算 X-LC-Sign 的签名方法\nconst sign = (key, isMasterKey) => {\n const now = new Date().getTime();\n const signature = md5(now + key);\n if (isMasterKey) {\n return `${signature},${now},master`;\n }\n return `${signature},${now}`;\n};\n\nlet requestsCount = 0;\n\nconst ajax = (method, resourceUrl, data, headers = {}, onprogress) => {\n const count = requestsCount++;\n\n debug(`request(${count})`, method, resourceUrl, data, headers);\n\n return new Promise((resolve, reject) => {\n const req = request(method, resourceUrl)\n .set(headers)\n .send(data);\n if (onprogress) {\n req.on('progress', onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(`response(${count})`, res.status, res.body || res.text, res.header);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n return resolve(res.body);\n });\n });\n};\n\nconst setAppKey = (headers, signKey) => {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.applicationKey);\n } else {\n headers['X-LC-Key'] = AV.applicationKey;\n }\n};\n\nconst setHeaders = (authOptions = {}, signKey) => {\n const headers = {\n 'X-LC-Id': AV.applicationId,\n 'Content-Type': 'application/json;charset=UTF-8',\n };\n let useMasterKey = false;\n if (typeof authOptions.useMasterKey === 'boolean') {\n useMasterKey = authOptions.useMasterKey;\n } else if (typeof AV._useMasterKey === 'boolean') {\n useMasterKey = AV._useMasterKey;\n }\n if (useMasterKey) {\n if (AV.masterKey) {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.masterKey, true);\n } else {\n headers['X-LC-Key'] = `${AV.masterKey},master`;\n }\n } else {\n console.warn('masterKey is not set, fall back to use appKey');\n setAppKey(headers, signKey);\n }\n } else {\n setAppKey(headers, signKey);\n }\n if (AV.hookKey) {\n headers['X-LC-Hook-Key'] = AV.hookKey;\n }\n if (AV._config.applicationProduction !== null) {\n headers['X-LC-Prod'] = String(AV._config.applicationProduction);\n }\n headers[!process.env.CLIENT_PLATFORM ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent;\n\n return Promise.resolve().then(() => {\n // Pass the session token\n const sessionToken = getSessionToken(authOptions);\n if (sessionToken) {\n headers['X-LC-Session'] = sessionToken;\n } else if (!AV._config.disableCurrentUser) {\n return AV.User.currentAsync().then((currentUser) => {\n if (currentUser && currentUser._sessionToken) {\n headers['X-LC-Session'] = currentUser._sessionToken;\n }\n return headers;\n });\n }\n return headers;\n });\n};\n\nconst createApiUrl = (route, className, objectId, method, dataObject) => {\n // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉\n if (AV.serverURL) {\n AV._config.APIServerURL = AV.serverURL;\n console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.');\n }\n\n let apiURL = AV._config.APIServerURL || API_HOST.cn;\n\n if (apiURL.charAt(apiURL.length - 1) !== '/') {\n apiURL += '/';\n }\n apiURL += `1.1/${route}`;\n if (className) {\n apiURL += `/${className}`;\n }\n if (objectId) {\n apiURL += `/${objectId}`;\n }\n if ((route === 'users' || route === 'classes') && dataObject) {\n apiURL += '?';\n if (dataObject._fetchWhenSave) {\n delete dataObject._fetchWhenSave;\n apiURL += '&new=true';\n }\n if (dataObject._where) {\n apiURL += `&where=${encodeURIComponent(JSON.stringify(dataObject._where))}`;\n delete dataObject._where;\n }\n }\n\n if (method.toLowerCase() === 'get') {\n if (apiURL.indexOf('?') === -1) {\n apiURL += '?';\n }\n for (const k in dataObject) {\n if (typeof dataObject[k] === 'object') {\n dataObject[k] = JSON.stringify(dataObject[k]);\n }\n apiURL += `&${k}=${encodeURIComponent(dataObject[k])}`;\n }\n }\n\n return apiURL;\n};\n\nconst cacheServerURL = (serverURL, ttl) => {\n if (typeof ttl !== 'number') {\n ttl = 3600;\n }\n return Cache.setAsync('APIServerURL', serverURL, ttl * 1000);\n};\n\n// handle AV._request Error\nconst handleError = (error) => {\n return new Promise((resolve, reject) => {\n /**\n When API request need to redirect to the right location,\n can't use browser redirect by http status 307, as the reason of CORS,\n so API server response http status 410 and the param \"location\" for this case.\n */\n if (error.statusCode === 410) {\n cacheServerURL(error.response.api_server, error.response.ttl).then(() => {\n resolve(error.response.location);\n }).catch(reject);\n } else {\n let errorJSON = {\n code: error.code || -1,\n error: error.message || error.responseText\n };\n if (error.response && error.response.code) {\n errorJSON = error.response;\n } else if (error.responseText) {\n try {\n errorJSON = JSON.parse(error.responseText);\n } catch (e) {\n // If we fail to parse the error text, that's okay.\n }\n }\n\n // Transform the error into an instance of AVError by trying to parse\n // the error string as JSON.\n reject(new AVError(errorJSON.code, errorJSON.error));\n }\n });\n};\n\nconst setServerUrl = (serverURL) => {\n AV._config.APIServerURL = `https://${serverURL}`;\n\n // 根据新 URL 重新设置区域\n const newRegion = _.findKey(API_HOST, item => item === AV._config.APIServerURL);\n if (newRegion) {\n AV._config.region = newRegion;\n }\n};\n\nconst refreshServerUrlByRouter = () => {\n const url = `https://app-router.leancloud.cn/1/route?appId=${AV.applicationId}`;\n return ajax('get', url).then(servers => {\n if (servers.api_server) {\n setServerUrl(servers.api_server);\n return cacheServerURL(servers.api_server, servers.ttl);\n }\n }, error => {\n // bypass all non-4XX errors\n if (error.statusCode >= 400 && error.statusCode < 500) {\n throw error;\n }\n });\n};\n\nconst setServerUrlByRegion = (region = 'cn') => {\n getServerURLPromise = new Promise((resolve, reject) => {\n // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router\n if (AV._config.APIServerURL) {\n resolve();\n return;\n }\n // if not china server region, do not use router\n if (region === 'cn') {\n return Cache.getAsync('APIServerURL').then((serverURL) => {\n if (serverURL) {\n setServerUrl(serverURL);\n } else {\n return refreshServerUrlByRouter();\n }\n }).then(() => {\n resolve();\n }).catch((error) => {\n reject(error);\n });\n } else {\n AV._config.region = region;\n AV._config.APIServerURL = API_HOST[region];\n resolve();\n }\n });\n};\n\n/**\n * route is classes, users, login, etc.\n * objectId is null if there is no associated objectId.\n * method is the http method for the REST API.\n * dataObject is the payload as an object, or null if there is none.\n * @ignore\n */\nconst AVRequest = (route, className, objectId, method, dataObject = {}, authOptions) => {\n if (!AV.applicationId) {\n throw new Error('You must specify your applicationId using AV.init()');\n }\n\n if (!AV.applicationKey && !AV.masterKey) {\n throw new Error('You must specify a AppKey using AV.init()');\n }\n\n if (!getServerURLPromise) {\n return Promise.reject(new Error('Not initialized'));\n }\n return getServerURLPromise.then(() => {\n const apiURL = createApiUrl(route, className, objectId, method, dataObject);\n return setHeaders(authOptions, route !== 'bigquery').then(\n headers => ajax(method, apiURL, dataObject, headers)\n .then(\n null,\n res => handleError(res)\n .then(location => ajax(method, location, dataObject, headers))\n )\n );\n });\n};\n\nmodule.exports = {\n ajax,\n request: AVRequest,\n setServerUrlByRegion,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/request.js","const _ = require('underscore');\n\n/**\n * @class AV.Error\n */\n\nfunction AVError(code, message) {\n const error = new Error(message);\n error.code = code;\n return error;\n}\n\n_.extend(AVError, /** @lends AV.Error */ {\n /**\n * Error code indicating some error other than those enumerated here.\n * @constant\n */\n OTHER_CAUSE: -1,\n\n /**\n * Error code indicating that something has gone wrong with the server.\n * If you get this error code, it is AV's fault. Contact us at\n * https://avoscloud.com/help\n * @constant\n */\n INTERNAL_SERVER_ERROR: 1,\n\n /**\n * Error code indicating the connection to the AV servers failed.\n * @constant\n */\n CONNECTION_FAILED: 100,\n\n /**\n * Error code indicating the specified object doesn't exist.\n * @constant\n */\n OBJECT_NOT_FOUND: 101,\n\n /**\n * Error code indicating you tried to query with a datatype that doesn't\n * support it, like exact matching an array or object.\n * @constant\n */\n INVALID_QUERY: 102,\n\n /**\n * Error code indicating a missing or invalid classname. Classnames are\n * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the\n * only valid characters.\n * @constant\n */\n INVALID_CLASS_NAME: 103,\n\n /**\n * Error code indicating an unspecified object id.\n * @constant\n */\n MISSING_OBJECT_ID: 104,\n\n /**\n * Error code indicating an invalid key name. Keys are case-sensitive. They\n * must start with a letter, and a-zA-Z0-9_ are the only valid characters.\n * @constant\n */\n INVALID_KEY_NAME: 105,\n\n /**\n * Error code indicating a malformed pointer. You should not see this unless\n * you have been mucking about changing internal AV code.\n * @constant\n */\n INVALID_POINTER: 106,\n\n /**\n * Error code indicating that badly formed JSON was received upstream. This\n * either indicates you have done something unusual with modifying how\n * things encode to JSON, or the network is failing badly.\n * @constant\n */\n INVALID_JSON: 107,\n\n /**\n * Error code indicating that the feature you tried to access is only\n * available internally for testing purposes.\n * @constant\n */\n COMMAND_UNAVAILABLE: 108,\n\n /**\n * You must call AV.initialize before using the AV library.\n * @constant\n */\n NOT_INITIALIZED: 109,\n\n /**\n * Error code indicating that a field was set to an inconsistent type.\n * @constant\n */\n INCORRECT_TYPE: 111,\n\n /**\n * Error code indicating an invalid channel name. A channel name is either\n * an empty string (the broadcast channel) or contains only a-zA-Z0-9_\n * characters.\n * @constant\n */\n INVALID_CHANNEL_NAME: 112,\n\n /**\n * Error code indicating that push is misconfigured.\n * @constant\n */\n PUSH_MISCONFIGURED: 115,\n\n /**\n * Error code indicating that the object is too large.\n * @constant\n */\n OBJECT_TOO_LARGE: 116,\n\n /**\n * Error code indicating that the operation isn't allowed for clients.\n * @constant\n */\n OPERATION_FORBIDDEN: 119,\n\n /**\n * Error code indicating the result was not found in the cache.\n * @constant\n */\n CACHE_MISS: 120,\n\n /**\n * Error code indicating that an invalid key was used in a nested\n * JSONObject.\n * @constant\n */\n INVALID_NESTED_KEY: 121,\n\n /**\n * Error code indicating that an invalid filename was used for AVFile.\n * A valid file name contains only a-zA-Z0-9_. characters and is between 1\n * and 128 characters.\n * @constant\n */\n INVALID_FILE_NAME: 122,\n\n /**\n * Error code indicating an invalid ACL was provided.\n * @constant\n */\n INVALID_ACL: 123,\n\n /**\n * Error code indicating that the request timed out on the server. Typically\n * this indicates that the request is too expensive to run.\n * @constant\n */\n TIMEOUT: 124,\n\n /**\n * Error code indicating that the email address was invalid.\n * @constant\n */\n INVALID_EMAIL_ADDRESS: 125,\n\n /**\n * Error code indicating a missing content type.\n * @constant\n */\n MISSING_CONTENT_TYPE: 126,\n\n /**\n * Error code indicating a missing content length.\n * @constant\n */\n MISSING_CONTENT_LENGTH: 127,\n\n /**\n * Error code indicating an invalid content length.\n * @constant\n */\n INVALID_CONTENT_LENGTH: 128,\n\n /**\n * Error code indicating a file that was too large.\n * @constant\n */\n FILE_TOO_LARGE: 129,\n\n /**\n * Error code indicating an error saving a file.\n * @constant\n */\n FILE_SAVE_ERROR: 130,\n\n /**\n * Error code indicating an error deleting a file.\n * @constant\n */\n FILE_DELETE_ERROR: 153,\n\n /**\n * Error code indicating that a unique field was given a value that is\n * already taken.\n * @constant\n */\n DUPLICATE_VALUE: 137,\n\n /**\n * Error code indicating that a role's name is invalid.\n * @constant\n */\n INVALID_ROLE_NAME: 139,\n\n /**\n * Error code indicating that an application quota was exceeded. Upgrade to\n * resolve.\n * @constant\n */\n EXCEEDED_QUOTA: 140,\n\n /**\n * Error code indicating that a Cloud Code script failed.\n * @constant\n */\n SCRIPT_FAILED: 141,\n\n /**\n * Error code indicating that a Cloud Code validation failed.\n * @constant\n */\n VALIDATION_ERROR: 142,\n\n /**\n * Error code indicating that invalid image data was provided.\n * @constant\n */\n INVALID_IMAGE_DATA: 150,\n\n /**\n * Error code indicating an unsaved file.\n * @constant\n */\n UNSAVED_FILE_ERROR: 151,\n\n /**\n * Error code indicating an invalid push time.\n */\n INVALID_PUSH_TIME_ERROR: 152,\n\n /**\n * Error code indicating that the username is missing or empty.\n * @constant\n */\n USERNAME_MISSING: 200,\n\n /**\n * Error code indicating that the password is missing or empty.\n * @constant\n */\n PASSWORD_MISSING: 201,\n\n /**\n * Error code indicating that the username has already been taken.\n * @constant\n */\n USERNAME_TAKEN: 202,\n\n /**\n * Error code indicating that the email has already been taken.\n * @constant\n */\n EMAIL_TAKEN: 203,\n\n /**\n * Error code indicating that the email is missing, but must be specified.\n * @constant\n */\n EMAIL_MISSING: 204,\n\n /**\n * Error code indicating that a user with the specified email was not found.\n * @constant\n */\n EMAIL_NOT_FOUND: 205,\n\n /**\n * Error code indicating that a user object without a valid session could\n * not be altered.\n * @constant\n */\n SESSION_MISSING: 206,\n\n /**\n * Error code indicating that a user can only be created through signup.\n * @constant\n */\n MUST_CREATE_USER_THROUGH_SIGNUP: 207,\n\n /**\n * Error code indicating that an an account being linked is already linked\n * to another user.\n * @constant\n */\n ACCOUNT_ALREADY_LINKED: 208,\n\n /**\n * Error code indicating that a user cannot be linked to an account because\n * that account's id could not be found.\n * @constant\n */\n LINKED_ID_MISSING: 250,\n\n /**\n * Error code indicating that a user with a linked (e.g. Facebook) account\n * has an invalid session.\n * @constant\n */\n INVALID_LINKED_SESSION: 251,\n\n /**\n * Error code indicating that a service being linked (e.g. Facebook or\n * Twitter) is unsupported.\n * @constant\n */\n UNSUPPORTED_SERVICE: 252,\n /**\n * Error code indicating a real error code is unavailable because\n * we had to use an XDomainRequest object to allow CORS requests in\n * Internet Explorer, which strips the body from HTTP responses that have\n * a non-2XX status code.\n * @constant\n */\n X_DOMAIN_REQUEST: 602,\n});\n\nmodule.exports = AVError;\n\n\n\n// WEBPACK FOOTER //\n// ./src/error.js","const _ = require('underscore');\n\n// Helper function to check null or undefined.\nconst isNullOrUndefined = (x) => _.isNull(x) || _.isUndefined(x);\n\nconst ensureArray = target => {\n if (_.isArray(target)) {\n return target;\n }\n if (target === undefined || target === null) {\n return [];\n }\n return [target];\n};\n\nconst getSessionToken = (authOptions) => {\n if (authOptions.sessionToken) {\n return authOptions.sessionToken;\n }\n if (\n authOptions.user && typeof authOptions.user.getSessionToken === 'function'\n ) {\n return authOptions.user.getSessionToken();\n }\n};\n\nconst tap = interceptor => value => ((interceptor(value), value));\n\nmodule.exports = {\n isNullOrUndefined,\n ensureArray,\n getSessionToken,\n tap,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/index.js","/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n 'lightseagreen',\n 'forestgreen',\n 'goldenrod',\n 'dodgerblue',\n 'darkorchid',\n 'crimson'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/browser.js\n// module id = 5\n// module chunks = 0","const _ = require('underscore');\nconst userAgent = require('./ua');\nconst {\n isNullOrUndefined,\n} = require('./utils');\n\nconst AV = global.AV || {};\n\n// All internal configuration items\nAV._config = AV._config || {};\nconst AVConfig = AV._config;\n\n_.extend(AVConfig, {\n\n // 服务器节点地区,默认中国大陆\n region: 'cn',\n\n // 服务器的 URL,默认初始化时被设置为大陆节点地址\n APIServerURL: AVConfig.APIServerURL || '',\n\n // 禁用 currentUser,通常用于多用户环境\n disableCurrentUser: false,\n\n // Internal config can modifie the UserAgent\n userAgent,\n\n // set production environment or test environment\n // 1: production environment, 0: test environment, null: default environment\n applicationProduction: null,\n});\n\n/**\n * Contains all AV API classes and functions.\n * @namespace AV\n */\n\n// Helpers\n// -------\n\n// Shared empty constructor function to aid in prototype-chain creation.\nvar EmptyConstructor = function() {};\n\n// Helper function to correctly set up the prototype chain, for subclasses.\n// Similar to `goog.inherits`, but uses a hash of prototype properties and\n// class properties to be extended.\nvar inherits = function(parent, protoProps, staticProps) {\n var child;\n\n // The constructor function for the new subclass is either defined by you\n // (the \"constructor\" property in your `extend` definition), or defaulted\n // by us to simply call the parent's constructor.\n if (protoProps && protoProps.hasOwnProperty('constructor')) {\n child = protoProps.constructor;\n } else {\n /** @ignore */\n child = function(){ parent.apply(this, arguments); };\n }\n\n // Inherit class (static) properties from parent.\n _.extend(child, parent);\n\n // Set the prototype chain to inherit from `parent`, without calling\n // `parent`'s constructor function.\n EmptyConstructor.prototype = parent.prototype;\n child.prototype = new EmptyConstructor();\n\n // Add prototype properties (instance properties) to the subclass,\n // if supplied.\n if (protoProps) {\n _.extend(child.prototype, protoProps);\n }\n\n // Add static properties to the constructor function, if supplied.\n if (staticProps) {\n _.extend(child, staticProps);\n }\n\n // Correctly set child's `prototype.constructor`.\n child.prototype.constructor = child;\n\n // Set a convenience property in case the parent's prototype is\n // needed later.\n child.__super__ = parent.prototype;\n\n return child;\n};\n\n/**\n * Call this method to set production environment variable.\n * @function AV.setProduction\n * @param {Boolean} production True is production environment,and\n * it's true by default.\n */\nAV.setProduction = (production) => {\n if (!isNullOrUndefined(production)) {\n AVConfig.applicationProduction = production ? 1 : 0;\n } else {\n // change to default value\n AVConfig.applicationProduction = null;\n }\n};\n\n/**\n * Returns prefix for localStorage keys used by this instance of AV.\n * @param {String} path The relative suffix to append to it.\n * null or undefined is treated as the empty string.\n * @return {String} The full key name.\n * @private\n */\nAV._getAVPath = function(path) {\n if (!AV.applicationId) {\n throw new Error(\"You need to call AV.initialize before using AV.\");\n }\n if (!path) {\n path = \"\";\n }\n if (!_.isString(path)) {\n throw new Error(\"Tried to get a localStorage path that wasn't a String.\");\n }\n if (path[0] === \"/\") {\n path = path.substring(1);\n }\n return \"AV/\" + AV.applicationId + \"/\" + path;\n};\n\n/**\n * Returns the unique string for this app on this machine.\n * Gets reset when localStorage is cleared.\n * @private\n */\nAV._installationId = null;\nAV._getInstallationId = function() {\n // See if it's cached in RAM.\n if (AV._installationId) {\n return AV.Promise.resolve(AV._installationId);\n }\n\n // Try to get it from localStorage.\n var path = AV._getAVPath(\"installationId\");\n return AV.localStorage.getItemAsync(path).then(function(_installationId){\n AV._installationId = _installationId;\n if (!AV._installationId) {\n // It wasn't in localStorage, so create a new one.\n var hexOctet = function() {\n return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);\n };\n AV._installationId = (\n hexOctet() + hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + hexOctet() + hexOctet());\n return AV.localStorage.setItemAsync(path, AV._installationId);\n }\n else {\n return _installationId;\n }\n });\n};\n\nAV._parseDate = function(iso8601) {\n var regexp = new RegExp(\n \"^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})\" + \"T\" +\n \"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\" +\n \"(.([0-9]+))?\" + \"Z$\");\n var match = regexp.exec(iso8601);\n if (!match) {\n return null;\n }\n\n var year = match[1] || 0;\n var month = (match[2] || 1) - 1;\n var day = match[3] || 0;\n var hour = match[4] || 0;\n var minute = match[5] || 0;\n var second = match[6] || 0;\n var milli = match[8] || 0;\n\n return new Date(Date.UTC(year, month, day, hour, minute, second, milli));\n};\n\n// A self-propagating extend function.\nAV._extend = function(protoProps, classProps) {\n var child = inherits(this, protoProps, classProps);\n child.extend = this.extend;\n return child;\n};\n\n// Helper function to get a value from a Backbone object as a property\n// or as a function.\nAV._getValue = function(object, prop) {\n if (!(object && object[prop])) {\n return null;\n }\n return _.isFunction(object[prop]) ? object[prop]() : object[prop];\n};\n\n/**\n * Converts a value in a AV Object into the appropriate representation.\n * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object)\n * if seenObjects is falsey. Otherwise any AV.Objects not in\n * seenObjects will be fully embedded rather than encoded\n * as a pointer. This array will be used to prevent going into an infinite\n * loop because we have circular references. If \n * is set, then none of the AV Objects that are serialized can be dirty.\n * @private\n */\nAV._encode = function(value, seenObjects, disallowObjects) {\n if (value instanceof AV.Object) {\n if (disallowObjects) {\n throw new Error(\"AV.Objects not allowed here\");\n }\n if (!seenObjects || _.include(seenObjects, value) || !value._hasData) {\n return value._toPointer();\n }\n if (!value.dirty()) {\n seenObjects = seenObjects.concat(value);\n return AV._encode(value._toFullJSON(seenObjects),\n seenObjects,\n disallowObjects);\n }\n throw new Error(\"Tried to save an object with a pointer to a new, unsaved object.\");\n }\n if (value instanceof AV.ACL) {\n return value.toJSON();\n }\n if (_.isDate(value)) {\n return { \"__type\": \"Date\", \"iso\": value.toJSON() };\n }\n if (value instanceof AV.GeoPoint) {\n return value.toJSON();\n }\n if (_.isArray(value)) {\n return _.map(value, function(x) {\n return AV._encode(x, seenObjects, disallowObjects);\n });\n }\n if (_.isRegExp(value)) {\n return value.source;\n }\n if (value instanceof AV.Relation) {\n return value.toJSON();\n }\n if (value instanceof AV.Op) {\n return value.toJSON();\n }\n if (value instanceof AV.File) {\n if (!value.url() && !value.id) {\n throw new Error(\"Tried to save an object containing an unsaved file.\");\n }\n return value._toFullJSON();\n }\n if (_.isObject(value)) {\n return _.mapObject(value, (v, k) => AV._encode(v, seenObjects, disallowObjects));\n }\n return value;\n};\n\n/**\n * The inverse function of AV._encode.\n * @private\n */\nAV._decode = function(value, key) {\n if (!_.isObject(value) || _.isDate(value)) {\n return value;\n }\n if (_.isArray(value)) {\n return _.map(value, v => AV._decode(v));\n }\n if (value instanceof AV.Object) {\n return value;\n }\n if (value instanceof AV.File) {\n return value;\n }\n if (value instanceof AV.Op) {\n return value;\n }\n if (value instanceof AV.GeoPoint) {\n return value;\n }\n if (value instanceof AV.ACL) {\n return value;\n }\n if (key === 'ACL') {\n return new AV.ACL(value);\n }\n if (value.__op) {\n return AV.Op._decode(value);\n }\n var className;\n if (value.__type === \"Pointer\") {\n className = value.className;\n var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n if(Object.keys(value).length > 3) {\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n pointer._finishFetch(v, true);\n }else{\n pointer._finishFetch({ objectId: value.objectId }, false);\n }\n return pointer;\n }\n if (value.__type === \"Object\") {\n // It's an Object included in a query result.\n className = value.className;\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n object._finishFetch(v, true);\n return object;\n }\n if (value.__type === \"Date\") {\n return AV._parseDate(value.iso);\n }\n if (value.__type === \"GeoPoint\") {\n return new AV.GeoPoint({\n latitude: value.latitude,\n longitude: value.longitude\n });\n }\n if (value.__type === \"Relation\") {\n if (!key) throw new Error('key missing decoding a Relation');\n var relation = new AV.Relation(null, key);\n relation.targetClassName = value.className;\n return relation;\n }\n if (value.__type === 'File') {\n var file = new AV.File(value.name);\n const v = _.clone(value);\n delete v.__type;\n file._finishFetch(v);\n return file;\n }\n return _.mapObject(value, AV._decode);\n};\n\nAV._encodeObjectOrArray = function(value) {\n var encodeAVObject = function(object) {\n if (object && object._toFullJSON){\n object = object._toFullJSON([]);\n }\n\n return _.mapObject(object, function(value) {\n return AV._encode(value, []);\n });\n };\n\n if (_.isArray(value)) {\n return value.map(function(object) {\n return encodeAVObject(object);\n });\n } else {\n return encodeAVObject(value);\n }\n};\n\nAV._arrayEach = _.each;\n\n/**\n * Does a deep traversal of every item in object, calling func on every one.\n * @param {Object} object The object or array to traverse deeply.\n * @param {Function} func The function to call for every item. It will\n * be passed the item as an argument. If it returns a truthy value, that\n * value will replace the item in its parent container.\n * @returns {} the result of calling func on the top-level object itself.\n * @private\n */\nAV._traverse = function(object, func, seen) {\n if (object instanceof AV.Object) {\n seen = seen || [];\n if (_.indexOf(seen, object) >= 0) {\n // We've already visited this object in this call.\n return;\n }\n seen.push(object);\n AV._traverse(object.attributes, func, seen);\n return func(object);\n }\n if (object instanceof AV.Relation || object instanceof AV.File) {\n // Nothing needs to be done, but we don't want to recurse into the\n // object's parent infinitely, so we catch this case.\n return func(object);\n }\n if (_.isArray(object)) {\n _.each(object, function(child, index) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[index] = newChild;\n }\n });\n return func(object);\n }\n if (_.isObject(object)) {\n AV._each(object, function(child, key) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[key] = newChild;\n }\n });\n return func(object);\n }\n return func(object);\n};\n\n/**\n * This is like _.each, except:\n * * it doesn't work for so-called array-like objects,\n * * it does work for dictionaries with a \"length\" attribute.\n * @private\n */\nAV._objectEach = AV._each = function(obj, callback) {\n if (_.isObject(obj)) {\n _.each(_.keys(obj), function(key) {\n callback(obj[key], key);\n });\n } else {\n _.each(obj, callback);\n }\n};\n\nmodule.exports = AV;\n\n\n\n// WEBPACK FOOTER //\n// ./src/av.js","/**\n * Root reference for iframes.\n */\n\nvar root;\nif (typeof window !== 'undefined') { // Browser window\n root = window;\n} else if (typeof self !== 'undefined') { // Web Worker\n root = self;\n} else { // Other environments\n console.warn(\"Using browser-only version of superagent in non-browser environment\");\n root = this;\n}\n\nvar Emitter = require('component-emitter');\nvar RequestBase = require('./request-base');\nvar isObject = require('./is-object');\nvar isFunction = require('./is-function');\nvar ResponseBase = require('./response-base');\nvar shouldRetry = require('./should-retry');\n\n/**\n * Noop.\n */\n\nfunction noop(){};\n\n/**\n * Expose `request`.\n */\n\nvar request = exports = module.exports = function(method, url) {\n // callback\n if ('function' == typeof url) {\n return new exports.Request('GET', method).end(url);\n }\n\n // url first\n if (1 == arguments.length) {\n return new exports.Request('GET', method);\n }\n\n return new exports.Request(method, url);\n}\n\nexports.Request = Request;\n\n/**\n * Determine XHR.\n */\n\nrequest.getXHR = function () {\n if (root.XMLHttpRequest\n && (!root.location || 'file:' != root.location.protocol\n || !root.ActiveXObject)) {\n return new XMLHttpRequest;\n } else {\n try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}\n }\n throw Error(\"Browser-only verison of superagent could not find XHR\");\n};\n\n/**\n * Removes leading and trailing whitespace, added to support IE.\n *\n * @param {String} s\n * @return {String}\n * @api private\n */\n\nvar trim = ''.trim\n ? function(s) { return s.trim(); }\n : function(s) { return s.replace(/(^\\s*|\\s*$)/g, ''); };\n\n/**\n * Serialize the given `obj`.\n *\n * @param {Object} obj\n * @return {String}\n * @api private\n */\n\nfunction serialize(obj) {\n if (!isObject(obj)) return obj;\n var pairs = [];\n for (var key in obj) {\n pushEncodedKeyValuePair(pairs, key, obj[key]);\n }\n return pairs.join('&');\n}\n\n/**\n * Helps 'serialize' with serializing arrays.\n * Mutates the pairs array.\n *\n * @param {Array} pairs\n * @param {String} key\n * @param {Mixed} val\n */\n\nfunction pushEncodedKeyValuePair(pairs, key, val) {\n if (val != null) {\n if (Array.isArray(val)) {\n val.forEach(function(v) {\n pushEncodedKeyValuePair(pairs, key, v);\n });\n } else if (isObject(val)) {\n for(var subkey in val) {\n pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);\n }\n } else {\n pairs.push(encodeURIComponent(key)\n + '=' + encodeURIComponent(val));\n }\n } else if (val === null) {\n pairs.push(encodeURIComponent(key));\n }\n}\n\n/**\n * Expose serialization method.\n */\n\n request.serializeObject = serialize;\n\n /**\n * Parse the given x-www-form-urlencoded `str`.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseString(str) {\n var obj = {};\n var pairs = str.split('&');\n var pair;\n var pos;\n\n for (var i = 0, len = pairs.length; i < len; ++i) {\n pair = pairs[i];\n pos = pair.indexOf('=');\n if (pos == -1) {\n obj[decodeURIComponent(pair)] = '';\n } else {\n obj[decodeURIComponent(pair.slice(0, pos))] =\n decodeURIComponent(pair.slice(pos + 1));\n }\n }\n\n return obj;\n}\n\n/**\n * Expose parser.\n */\n\nrequest.parseString = parseString;\n\n/**\n * Default MIME type map.\n *\n * superagent.types.xml = 'application/xml';\n *\n */\n\nrequest.types = {\n html: 'text/html',\n json: 'application/json',\n xml: 'application/xml',\n urlencoded: 'application/x-www-form-urlencoded',\n 'form': 'application/x-www-form-urlencoded',\n 'form-data': 'application/x-www-form-urlencoded'\n};\n\n/**\n * Default serialization map.\n *\n * superagent.serialize['application/xml'] = function(obj){\n * return 'generated xml here';\n * };\n *\n */\n\n request.serialize = {\n 'application/x-www-form-urlencoded': serialize,\n 'application/json': JSON.stringify\n };\n\n /**\n * Default parsers.\n *\n * superagent.parse['application/xml'] = function(str){\n * return { object parsed from str };\n * };\n *\n */\n\nrequest.parse = {\n 'application/x-www-form-urlencoded': parseString,\n 'application/json': JSON.parse\n};\n\n/**\n * Parse the given header `str` into\n * an object containing the mapped fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseHeader(str) {\n var lines = str.split(/\\r?\\n/);\n var fields = {};\n var index;\n var line;\n var field;\n var val;\n\n lines.pop(); // trailing CRLF\n\n for (var i = 0, len = lines.length; i < len; ++i) {\n line = lines[i];\n index = line.indexOf(':');\n field = line.slice(0, index).toLowerCase();\n val = trim(line.slice(index + 1));\n fields[field] = val;\n }\n\n return fields;\n}\n\n/**\n * Check if `mime` is json or has +json structured syntax suffix.\n *\n * @param {String} mime\n * @return {Boolean}\n * @api private\n */\n\nfunction isJSON(mime) {\n return /[\\/+]json\\b/.test(mime);\n}\n\n/**\n * Initialize a new `Response` with the given `xhr`.\n *\n * - set flags (.ok, .error, etc)\n * - parse header\n *\n * Examples:\n *\n * Aliasing `superagent` as `request` is nice:\n *\n * request = superagent;\n *\n * We can use the promise-like API, or pass callbacks:\n *\n * request.get('/').end(function(res){});\n * request.get('/', function(res){});\n *\n * Sending data can be chained:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' })\n * .end(function(res){});\n *\n * Or passed to `.send()`:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' }, function(res){});\n *\n * Or passed to `.post()`:\n *\n * request\n * .post('/user', { name: 'tj' })\n * .end(function(res){});\n *\n * Or further reduced to a single call for simple cases:\n *\n * request\n * .post('/user', { name: 'tj' }, function(res){});\n *\n * @param {XMLHTTPRequest} xhr\n * @param {Object} options\n * @api private\n */\n\nfunction Response(req) {\n this.req = req;\n this.xhr = this.req.xhr;\n // responseText is accessible only if responseType is '' or 'text' and on older browsers\n this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')\n ? this.xhr.responseText\n : null;\n this.statusText = this.req.xhr.statusText;\n var status = this.xhr.status;\n // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request\n if (status === 1223) {\n status = 204;\n }\n this._setStatusProperties(status);\n this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());\n // getAllResponseHeaders sometimes falsely returns \"\" for CORS requests, but\n // getResponseHeader still works. so we get content-type even if getting\n // other headers fails.\n this.header['content-type'] = this.xhr.getResponseHeader('content-type');\n this._setHeaderProperties(this.header);\n\n if (null === this.text && req._responseType) {\n this.body = this.xhr.response;\n } else {\n this.body = this.req.method != 'HEAD'\n ? this._parseBody(this.text ? this.text : this.xhr.response)\n : null;\n }\n}\n\nResponseBase(Response.prototype);\n\n/**\n * Parse the given body `str`.\n *\n * Used for auto-parsing of bodies. Parsers\n * are defined on the `superagent.parse` object.\n *\n * @param {String} str\n * @return {Mixed}\n * @api private\n */\n\nResponse.prototype._parseBody = function(str){\n var parse = request.parse[this.type];\n if(this.req._parser) {\n return this.req._parser(this, str);\n }\n if (!parse && isJSON(this.type)) {\n parse = request.parse['application/json'];\n }\n return parse && str && (str.length || str instanceof Object)\n ? parse(str)\n : null;\n};\n\n/**\n * Return an `Error` representative of this response.\n *\n * @return {Error}\n * @api public\n */\n\nResponse.prototype.toError = function(){\n var req = this.req;\n var method = req.method;\n var url = req.url;\n\n var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';\n var err = new Error(msg);\n err.status = this.status;\n err.method = method;\n err.url = url;\n\n return err;\n};\n\n/**\n * Expose `Response`.\n */\n\nrequest.Response = Response;\n\n/**\n * Initialize a new `Request` with the given `method` and `url`.\n *\n * @param {String} method\n * @param {String} url\n * @api public\n */\n\nfunction Request(method, url) {\n var self = this;\n this._query = this._query || [];\n this.method = method;\n this.url = url;\n this.header = {}; // preserves header name case\n this._header = {}; // coerces header names to lowercase\n this.on('end', function(){\n var err = null;\n var res = null;\n\n try {\n res = new Response(self);\n } catch(e) {\n err = new Error('Parser is unable to parse the response');\n err.parse = true;\n err.original = e;\n // issue #675: return the raw response if the response parsing fails\n if (self.xhr) {\n // ie9 doesn't have 'response' property\n err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;\n // issue #876: return the http status code if the response parsing fails\n err.status = self.xhr.status ? self.xhr.status : null;\n err.statusCode = err.status; // backwards-compat only\n } else {\n err.rawResponse = null;\n err.status = null;\n }\n\n return self.callback(err);\n }\n\n self.emit('response', res);\n\n var new_err;\n try {\n if (!self._isResponseOK(res)) {\n new_err = new Error(res.statusText || 'Unsuccessful HTTP response');\n new_err.original = err;\n new_err.response = res;\n new_err.status = res.status;\n }\n } catch(e) {\n new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android\n }\n\n // #1000 don't catch errors from the callback to avoid double calling it\n if (new_err) {\n self.callback(new_err, res);\n } else {\n self.callback(null, res);\n }\n });\n}\n\n/**\n * Mixin `Emitter` and `RequestBase`.\n */\n\nEmitter(Request.prototype);\nRequestBase(Request.prototype);\n\n/**\n * Set Content-Type to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.xml = 'application/xml';\n *\n * request.post('/')\n * .type('xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * request.post('/')\n * .type('application/xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * @param {String} type\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.type = function(type){\n this.set('Content-Type', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Accept to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.json = 'application/json';\n *\n * request.get('/agent')\n * .accept('json')\n * .end(callback);\n *\n * request.get('/agent')\n * .accept('application/json')\n * .end(callback);\n *\n * @param {String} accept\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.accept = function(type){\n this.set('Accept', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Authorization field value with `user` and `pass`.\n *\n * @param {String} user\n * @param {String} [pass] optional in case of using 'bearer' as type\n * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.auth = function(user, pass, options){\n if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options\n options = pass;\n }\n if (!options) {\n options = {\n type: 'function' === typeof btoa ? 'basic' : 'auto',\n }\n }\n\n switch (options.type) {\n case 'basic':\n this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));\n break;\n\n case 'auto':\n this.username = user;\n this.password = pass;\n break;\n \n case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })\n this.set('Authorization', 'Bearer ' + user);\n break; \n }\n return this;\n};\n\n/**\n * Add query-string `val`.\n *\n * Examples:\n *\n * request.get('/shoes')\n * .query('size=10')\n * .query({ color: 'blue' })\n *\n * @param {Object|String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.query = function(val){\n if ('string' != typeof val) val = serialize(val);\n if (val) this._query.push(val);\n return this;\n};\n\n/**\n * Queue the given `file` as an attachment to the specified `field`,\n * with optional `options` (or filename).\n *\n * ``` js\n * request.post('/upload')\n * .attach('content', new Blob(['hey!'], { type: \"text/html\"}))\n * .end(callback);\n * ```\n *\n * @param {String} field\n * @param {Blob|File} file\n * @param {String|Object} options\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.attach = function(field, file, options){\n if (file) {\n if (this._data) {\n throw Error(\"superagent can't mix .send() and .attach()\");\n }\n\n this._getFormData().append(field, file, options || file.name);\n }\n return this;\n};\n\nRequest.prototype._getFormData = function(){\n if (!this._formData) {\n this._formData = new root.FormData();\n }\n return this._formData;\n};\n\n/**\n * Invoke the callback with `err` and `res`\n * and handle arity check.\n *\n * @param {Error} err\n * @param {Response} res\n * @api private\n */\n\nRequest.prototype.callback = function(err, res){\n // console.log(this._retries, this._maxRetries)\n if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) {\n return this._retry();\n }\n\n var fn = this._callback;\n this.clearTimeout();\n\n if (err) {\n if (this._maxRetries) err.retries = this._retries - 1;\n this.emit('error', err);\n }\n\n fn(err, res);\n};\n\n/**\n * Invoke callback with x-domain error.\n *\n * @api private\n */\n\nRequest.prototype.crossDomainError = function(){\n var err = new Error('Request has been terminated\\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');\n err.crossDomain = true;\n\n err.status = this.status;\n err.method = this.method;\n err.url = this.url;\n\n this.callback(err);\n};\n\n// This only warns, because the request is still likely to work\nRequest.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){\n console.warn(\"This is not supported in browser version of superagent\");\n return this;\n};\n\n// This throws, because it can't send/receive data as expected\nRequest.prototype.pipe = Request.prototype.write = function(){\n throw Error(\"Streaming is not supported in browser version of superagent\");\n};\n\n/**\n * Compose querystring to append to req.url\n *\n * @api private\n */\n\nRequest.prototype._appendQueryString = function(){\n var query = this._query.join('&');\n if (query) {\n this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;\n }\n\n if (this._sort) {\n var index = this.url.indexOf('?');\n if (index >= 0) {\n var queryArr = this.url.substring(index + 1).split('&');\n if (isFunction(this._sort)) {\n queryArr.sort(this._sort);\n } else {\n queryArr.sort();\n }\n this.url = this.url.substring(0, index) + '?' + queryArr.join('&');\n }\n }\n};\n\n/**\n * Check if `obj` is a host object,\n * we don't want to serialize these :)\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\nRequest.prototype._isHost = function _isHost(obj) {\n // Native objects stringify to [object File], [object Blob], [object FormData], etc.\n return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';\n}\n\n/**\n * Initiate request, invoking callback `fn(res)`\n * with an instanceof `Response`.\n *\n * @param {Function} fn\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.end = function(fn){\n if (this._endCalled) {\n console.warn(\"Warning: .end() was called twice. This is not supported in superagent\");\n }\n this._endCalled = true;\n\n // store callback\n this._callback = fn || noop;\n\n // querystring\n this._appendQueryString();\n\n return this._end();\n};\n\nRequest.prototype._end = function() {\n var self = this;\n var xhr = this.xhr = request.getXHR();\n var data = this._formData || this._data;\n\n this._setTimeouts();\n\n // state change\n xhr.onreadystatechange = function(){\n var readyState = xhr.readyState;\n if (readyState >= 2 && self._responseTimeoutTimer) {\n clearTimeout(self._responseTimeoutTimer);\n }\n if (4 != readyState) {\n return;\n }\n\n // In IE9, reads to any property (e.g. status) off of an aborted XHR will\n // result in the error \"Could not complete the operation due to error c00c023f\"\n var status;\n try { status = xhr.status } catch(e) { status = 0; }\n\n if (!status) {\n if (self.timedout || self._aborted) return;\n return self.crossDomainError();\n }\n self.emit('end');\n };\n\n // progress\n var handleProgress = function(direction, e) {\n if (e.total > 0) {\n e.percent = e.loaded / e.total * 100;\n }\n e.direction = direction;\n self.emit('progress', e);\n }\n if (this.hasListeners('progress')) {\n try {\n xhr.onprogress = handleProgress.bind(null, 'download');\n if (xhr.upload) {\n xhr.upload.onprogress = handleProgress.bind(null, 'upload');\n }\n } catch(e) {\n // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.\n // Reported here:\n // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context\n }\n }\n\n // initiate request\n try {\n if (this.username && this.password) {\n xhr.open(this.method, this.url, true, this.username, this.password);\n } else {\n xhr.open(this.method, this.url, true);\n }\n } catch (err) {\n // see #1149\n return this.callback(err);\n }\n\n // CORS\n if (this._withCredentials) xhr.withCredentials = true;\n\n // body\n if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {\n // serialize stuff\n var contentType = this._header['content-type'];\n var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];\n if (!serialize && isJSON(contentType)) {\n serialize = request.serialize['application/json'];\n }\n if (serialize) data = serialize(data);\n }\n\n // set header fields\n for (var field in this.header) {\n if (null == this.header[field]) continue;\n\n if (this.header.hasOwnProperty(field))\n xhr.setRequestHeader(field, this.header[field]);\n }\n\n if (this._responseType) {\n xhr.responseType = this._responseType;\n }\n\n // send stuff\n this.emit('request', this);\n\n // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)\n // We need null here if data is undefined\n xhr.send(typeof data !== 'undefined' ? data : null);\n return this;\n};\n\n/**\n * GET `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.get = function(url, data, fn){\n var req = request('GET', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.query(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * HEAD `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.head = function(url, data, fn){\n var req = request('HEAD', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * OPTIONS query to `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.options = function(url, data, fn){\n var req = request('OPTIONS', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * DELETE `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nfunction del(url, data, fn){\n var req = request('DELETE', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\nrequest['del'] = del;\nrequest['delete'] = del;\n\n/**\n * PATCH `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.patch = function(url, data, fn){\n var req = request('PATCH', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * POST `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.post = function(url, data, fn){\n var req = request('POST', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * PUT `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.put = function(url, data, fn){\n var req = request('PUT', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/client.js\n// module id = 7\n// module chunks = 0","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/global.js\n// module id = 8\n// module chunks = 0","class FormData {\n constructor() {\n this._entries = [];\n }\n\n append(name, value) {\n if (typeof name !== 'string') {\n throw new TypeError('FormData name must be a string');\n }\n if (typeof value !== 'string') {\n if (typeof value !== 'object' || typeof value.uri !== 'string') {\n throw new TypeError('FormData value must be a string or { uri: tempFilePath }')\n }\n }\n this._entries.push([name, value]);\n }\n\n set(name, value) {\n const entry = this.get(name);\n if (entry) {\n entry[1] = value;\n } else {\n this.append(name, value);\n }\n }\n\n delete(name) {\n this._entries = this._entries.filter(entry => entry[0] !== name);\n }\n\n entries() {\n return this._entries;\n }\n\n get(name) {\n return this._entries.find(entry => entry[0] === name);\n }\n\n getAll(name) {\n return this._entries.filter(entry => entry[0] === name);\n }\n\n has(name) {\n return this._entries.some(entry => entry[0] === name);\n }\n\n keys() {\n return this._entries.map(entry => entry[0]);\n }\n\n values() {\n return this._entries.map(entry => entry[1]);\n }\n}\n\nmodule.exports = FormData;\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/formdata.js","/**\n * @author Toru Nagashima\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n\n\"use strict\";\n\n/**\n * Creates a unique key.\n *\n * @param {string} name - A name to create.\n * @returns {symbol|string}\n * @private\n */\nvar createUniqueKey = exports.createUniqueKey = (typeof Symbol !== \"undefined\" ?\n Symbol :\n function createUniqueKey(name) {\n return \"[[\" + name + \"_\" + Math.random().toFixed(8).slice(2) + \"]]\";\n });\n\n/**\n * The key of listeners.\n *\n * @type {symbol|string}\n * @private\n */\nexports.LISTENERS = createUniqueKey(\"listeners\");\n\n/**\n * A value of kind for listeners which are registered in the capturing phase.\n *\n * @type {number}\n * @private\n */\nexports.CAPTURE = 1;\n\n/**\n * A value of kind for listeners which are registered in the bubbling phase.\n *\n * @type {number}\n * @private\n */\nexports.BUBBLE = 2;\n\n/**\n * A value of kind for listeners which are registered as an attribute.\n *\n * @type {number}\n * @private\n */\nexports.ATTRIBUTE = 3;\n\n/**\n * @typedef object ListenerNode\n * @property {function} listener - A listener function.\n * @property {number} kind - The kind of the listener.\n * @property {ListenerNode|null} next - The next node.\n * If this node is the last, this is `null`.\n */\n\n/**\n * Creates a node of singly linked list for a list of listeners.\n *\n * @param {function} listener - A listener function.\n * @param {number} kind - The kind of the listener.\n * @returns {ListenerNode} The created listener node.\n */\nexports.newNode = function newNode(listener, kind) {\n return {listener: listener, kind: kind, next: null};\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/event-target-shim/lib/commons.js\n// module id = 10\n// module chunks = 0","/**\n * Check if `obj` is an object.\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\n\nfunction isObject(obj) {\n return null !== obj && 'object' === typeof obj;\n}\n\nmodule.exports = isObject;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-object.js\n// module id = 11\n// module chunks = 0","class Storage {\n getItem(key) {\n return wx.getStorageSync(key);\n }\n\n setItem(key, value) {\n return wx.setStorageSync(key, value);\n }\n\n removeItem(key) {\n return this.setItem(key, '');\n }\n\n clear() {\n return wx.clearStorageSync();\n }\n}\n\nmodule.exports = new Storage();\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/localstorage.js","module.exports = {};\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/navigator.js","const assign = require('object-assign');\nconst EventTarget = require('event-target-shim');\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\nconst EVENTS = [\n 'open',\n 'error',\n 'message',\n 'close',\n];\n\nlet instance;\n\nfunction errorHandler(event) {\n // 安卓小程序会诡异地触发 onSocketError 回调\n // 通过比较 message 过滤掉\n if (event.message === \"\") return;\n if (instance) {\n instance._readyState = CLOSED;\n instance.dispatchEvent({\n type: 'error',\n message: event.errMsg,\n });\n }\n}\n\nclass WebSocket extends EventTarget(EVENTS) {\n constructor(url, protocal) {\n if (!url) {\n throw new TypeError('Failed to construct \\'WebSocket\\': url required');\n }\n if (protocal) {\n throw new Error('subprotocal not supported in weapp');\n }\n super();\n this._url = url;\n this._protocal = ''; // default value according to specs\n this._readyState = CONNECTING;\n if (instance) {\n instance.dispatchEvent({\n type: 'close'\n });\n }\n instance = this;\n \n wx.onSocketOpen(function (event) {\n if (instance) {\n instance._readyState = OPEN;\n instance.dispatchEvent({\n type: 'open'\n });\n }\n });\n wx.onSocketError(errorHandler);\n wx.onSocketMessage(function (event) {\n if (instance) {\n var {\n data,\n origin,\n ports,\n source,\n } = event;\n instance.dispatchEvent({\n data,\n origin,\n ports,\n source,\n type: 'message',\n });\n }\n });\n wx.onSocketClose(function (event) {\n if (instance) {\n instance._readyState = CLOSED;\n var {\n code,\n reason,\n wasClean,\n } = event;\n instance.dispatchEvent({\n code,\n reason,\n wasClean,\n type: 'close',\n });\n instance = null;\n }\n });\n \n wx.connectSocket({\n url,\n fail: (error) => setTimeout(() => errorHandler(error), 0),\n });\n }\n\n get url() {\n return this._url;\n }\n get protocal() {\n return this._protocal;\n }\n get readyState() {\n return this._readyState;\n }\n\n close() {\n if (this.readyState === CONNECTING) {\n console.warn('close WebSocket which is connecting might not work');\n }\n wx.closeSocket();\n }\n\n send(data) {\n if (this.readyState !== OPEN) {\n throw new Error('INVALID_STATE_ERR');\n }\n\n if (typeof data !== 'string') {\n throw new TypeError('only string typed data are supported');\n }\n\n wx.sendSocketMessage({\n data\n });\n }\n\n}\n\nassign(WebSocket, {\n CONNECTING,\n OPEN,\n CLOSING,\n CLOSED,\n});\n\nmodule.exports = WebSocket;\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/websocket.js","const assign = require('object-assign');\nconst EventTarget = require('event-target-shim');\nconst FormData = require('./formdata.js');\n\nconst UNSENT = 0;\nconst OPENED = 1;\nconst HEADERS_RECEIVED = 2;\nconst LOADING = 3;\nconst DONE = 4;\n\nconst REQUEST_EVENTS = [\n 'abort',\n 'error',\n 'load',\n 'loadstart',\n 'progress',\n 'timeout',\n 'loadend',\n 'readystatechange'\n];\n\nfunction successCallback(response) {\n this.status = response.statusCode;\n this.statusText = response.statusCode;\n let text = response.data;\n if (typeof text !== 'string') {\n text = JSON.stringify(text);\n }\n this.responseText = this.response = text;\n this.readyState = DONE;\n this.dispatchEvent({ type: 'readystatechange' });\n}\n\nclass XMLHttpRequest extends EventTarget(REQUEST_EVENTS) {\n\n constructor() {\n super();\n this.readyState = UNSENT;\n this._headers = {};\n }\n\n abort() {\n throw new Error('not supported in weapp');\n }\n getAllResponseHeaders() {\n console.warn('getAllResponseHeaders always returns \\'\\'');\n return '';\n }\n getResponseHeader(key) {\n if (key === 'content-type') {\n console.warn('get content-type always returns \\'application/json\\'');\n return 'application/json';\n }\n console.warn('getResponseHeader always returns \\'\\'');\n return '';\n }\n overrideMimeType() {\n throw new Error('not supported in weapp');\n }\n open(method, url, async = true) {\n if (this.readyState !== UNSENT) {\n throw new Error('request is already opened');\n }\n if (!async) {\n throw new Error('sync request is not supported');\n }\n this._method = method;\n this._url = url;\n this.readyState = OPENED;\n this.dispatchEvent({ type: 'readystatechange' });\n }\n setRequestHeader(header, value) {\n if (this.readyState !== OPENED) {\n throw new Error('request is not opened');\n }\n this._headers[header.toLowerCase()] = value;\n }\n send(data) {\n if (this.readyState !== OPENED) {\n throw new Error('request is not opened');\n }\n if (data instanceof FormData) {\n const entries = data.entries();\n const blobs = entries.filter(entry => typeof entry[1] !== 'string');\n if (blobs.length === 0) {\n throw new Error('Must specify a Blob field in FormData');\n }\n if (blobs.length > 1) {\n console.warn('Only the first Blob will be send in Weapp');\n }\n const restData = entries\n .filter(entry => typeof entry[1] === 'string')\n .reduce((result, entry) => assign(result, { [entry[0]]: entry[1] }), {});\n wx.uploadFile({\n url: this._url,\n name: blobs[0][0],\n filePath: blobs[0][1].uri,\n formData: restData,\n header: this._headers,\n success: successCallback.bind(this),\n fail: (error) => {\n this.status = 0;\n this.readyState = DONE;\n this.dispatchEvent({ type: 'readystatechange' });\n this.dispatchEvent({ type: 'error' });\n }\n })\n } else {\n wx.request({\n url: this._url,\n data: data || '',\n // method 的 value 居然必须为大写\n method: this._method.toUpperCase(),\n header: this._headers,\n success: successCallback.bind(this),\n fail: (error) => {\n this.status = 0;\n this.readyState = DONE;\n this.dispatchEvent({ type: 'readystatechange' });\n this.dispatchEvent({ type: 'error' });\n }\n });\n }\n }\n}\n\nassign(XMLHttpRequest, {\n UNSENT,\n OPENED,\n HEADERS_RECEIVED,\n LOADING,\n DONE,\n});\n\nmodule.exports = XMLHttpRequest;\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/xmlhttprequest.js","const storage = require('./localstorage');\nconst AV = require('./av');\n\nconst removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage);\n\nconst getCacheData = (cacheData, key) => {\n try {\n cacheData = JSON.parse(cacheData);\n } catch (e) {\n return null;\n }\n if (cacheData) {\n const expired = cacheData.expiredAt && cacheData.expiredAt < Date.now();\n if (!expired) {\n return cacheData.value;\n }\n return removeAsync(key).then(() => null);\n }\n return null;\n};\n\nexports.getAsync = (key) => {\n key = `${AV.applicationId}/${key}`;\n return storage.getItemAsync(key)\n .then(cache => getCacheData(cache, key));\n};\n\nexports.setAsync = (key, value, ttl) => {\n const cache = { value };\n if (typeof ttl === 'number') {\n cache.expiredAt = Date.now() + ttl;\n }\n return storage.setItemAsync(\n `${AV.applicationId}/${key}`,\n JSON.stringify(cache)\n );\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cache.js","var _ = require('underscore');\nvar Promise = require('./promise');\nvar localStorage = require('./utils/localstorage');\n\nvar syncApiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nif (!localStorage.async) {\n // wrap sync apis with async ones.\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] === 'function') {\n localStorage[apiName + 'Async'] = function() {\n return Promise.resolve(localStorage[apiName].apply(localStorage, arguments));\n };\n }\n });\n} else {\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] !== 'function') {\n localStorage[apiName] = function() {\n const error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.');\n error.code = 'SYNC_API_NOT_AVAILABLE';\n throw error;\n };\n }\n });\n}\n\nmodule.exports = localStorage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/localstorage.js","module.exports = '2.1.4';\n\n\n\n// WEBPACK FOOTER //\n// ./src/version.js","var charenc = {\n // UTF-8 encoding\n utf8: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n }\n },\n\n // Binary encoding\n bin: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n for (var bytes = [], i = 0; i < str.length; i++)\n bytes.push(str.charCodeAt(i) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n for (var str = [], i = 0; i < bytes.length; i++)\n str.push(String.fromCharCode(bytes[i]));\n return str.join('');\n }\n }\n};\n\nmodule.exports = charenc;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/charenc/charenc.js\n// module id = 19\n// module chunks = 0","/**\n * @author Toru Nagashima\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n\n\"use strict\";\n\n//-----------------------------------------------------------------------------\n// Requirements\n//-----------------------------------------------------------------------------\n\nvar Commons = require(\"./commons\");\nvar CustomEventTarget = require(\"./custom-event-target\");\nvar EventWrapper = require(\"./event-wrapper\");\nvar LISTENERS = Commons.LISTENERS;\nvar CAPTURE = Commons.CAPTURE;\nvar BUBBLE = Commons.BUBBLE;\nvar ATTRIBUTE = Commons.ATTRIBUTE;\nvar newNode = Commons.newNode;\nvar defineCustomEventTarget = CustomEventTarget.defineCustomEventTarget;\nvar createEventWrapper = EventWrapper.createEventWrapper;\nvar STOP_IMMEDIATE_PROPAGATION_FLAG =\n EventWrapper.STOP_IMMEDIATE_PROPAGATION_FLAG;\n\n//-----------------------------------------------------------------------------\n// Constants\n//-----------------------------------------------------------------------------\n\n/**\n * A flag which shows there is the native `EventTarget` interface object.\n *\n * @type {boolean}\n * @private\n */\nvar HAS_EVENTTARGET_INTERFACE = (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n);\n\n//-----------------------------------------------------------------------------\n// Public Interface\n//-----------------------------------------------------------------------------\n\n/**\n * An implementation for `EventTarget` interface.\n *\n * @constructor\n * @public\n */\nvar EventTarget = module.exports = function EventTarget() {\n if (this instanceof EventTarget) {\n // this[LISTENERS] is a Map.\n // Its key is event type.\n // Its value is ListenerNode object or null.\n //\n // interface ListenerNode {\n // var listener: Function\n // var kind: CAPTURE|BUBBLE|ATTRIBUTE\n // var next: ListenerNode|null\n // }\n Object.defineProperty(this, LISTENERS, {value: Object.create(null)});\n }\n else if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(EventTarget, arguments[0]);\n }\n else if (arguments.length > 0) {\n var types = Array(arguments.length);\n for (var i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i];\n }\n\n // To use to extend with attribute listener properties.\n // e.g.\n // class MyCustomObject extends EventTarget(\"message\", \"error\") {\n // //...\n // }\n return defineCustomEventTarget(EventTarget, types);\n }\n else {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n};\n\nEventTarget.prototype = Object.create(\n (HAS_EVENTTARGET_INTERFACE ? window.EventTarget : Object).prototype,\n {\n constructor: {\n value: EventTarget,\n writable: true,\n configurable: true\n },\n\n addEventListener: {\n value: function addEventListener(type, listener, capture) {\n if (listener == null) {\n return false;\n }\n if (typeof listener !== \"function\" && typeof listener !== \"object\") {\n throw new TypeError(\"\\\"listener\\\" is not an object.\");\n }\n\n var kind = (capture ? CAPTURE : BUBBLE);\n var node = this[LISTENERS][type];\n if (node == null) {\n this[LISTENERS][type] = newNode(listener, kind);\n return true;\n }\n\n var prev = null;\n while (node != null) {\n if (node.listener === listener && node.kind === kind) {\n // Should ignore a duplicated listener.\n return false;\n }\n prev = node;\n node = node.next;\n }\n\n prev.next = newNode(listener, kind);\n return true;\n },\n configurable: true,\n writable: true\n },\n\n removeEventListener: {\n value: function removeEventListener(type, listener, capture) {\n if (listener == null) {\n return false;\n }\n\n var kind = (capture ? CAPTURE : BUBBLE);\n var prev = null;\n var node = this[LISTENERS][type];\n while (node != null) {\n if (node.listener === listener && node.kind === kind) {\n if (prev == null) {\n this[LISTENERS][type] = node.next;\n }\n else {\n prev.next = node.next;\n }\n return true;\n }\n\n prev = node;\n node = node.next;\n }\n\n return false;\n },\n configurable: true,\n writable: true\n },\n\n dispatchEvent: {\n value: function dispatchEvent(event) {\n // If listeners aren't registered, terminate.\n var node = this[LISTENERS][event.type];\n if (node == null) {\n return true;\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n var wrapped = createEventWrapper(event, this);\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n while (node != null) {\n if (typeof node.listener === \"function\") {\n node.listener.call(this, wrapped);\n }\n else if (node.kind !== ATTRIBUTE && typeof node.listener.handleEvent === \"function\") {\n node.listener.handleEvent(wrapped);\n }\n\n if (wrapped[STOP_IMMEDIATE_PROPAGATION_FLAG]) {\n break;\n }\n node = node.next;\n }\n\n return !wrapped.defaultPrevented;\n },\n configurable: true,\n writable: true\n }\n }\n);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/event-target-shim/lib/event-target.js\n// module id = 20\n// module chunks = 0","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/object-assign/index.js\n// module id = 21\n// module chunks = 0","var polyfill = require('./index.js').polyfill;\nwindow = window || {};\npolyfill();\npolyfill(window);\ntry {\n localStorage = localStorage || require('./localstorage.js');\n} catch (e) {}\ntry {\n XMLHttpRequest = XMLHttpRequest || require('./xmlhttprequest.js');\n} catch (e) {}\ntry {\n FormData = FormData || require('./formdata.js');\n} catch (e) {}\ntry {\n WebSocket = WebSocket || require('./websocket.js');\n} catch (e) {}\ntry {\n navigator = navigator || require('./navigator.js');\n} catch (e) {}\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/auto-polyfill.js","/*!\n * LeanCloud JavaScript SDK\n * https://leancloud.cn\n *\n * Copyright 2016 LeanCloud.cn, Inc.\n * The LeanCloud JavaScript SDK is freely distributable under the MIT license.\n */\n\nconst AV = require('./av');\n\nAV._ = require('underscore');\nAV.version = require('./version');\nAV.Promise = require('./promise');\nAV.localStorage = require('./localstorage');\nAV.Cache = require('./cache');\nAV.Error = require('./error');\n\nrequire('./init');\nrequire('./event')(AV);\nrequire('./geopoint')(AV);\nrequire('./acl')(AV);\nrequire('./op')(AV);\nrequire('./relation')(AV);\nrequire('./file')(AV);\nrequire('./object')(AV);\nrequire('./role')(AV);\nrequire('./user')(AV);\nrequire('./query')(AV);\nrequire('./cloudfunction')(AV);\nrequire('./push')(AV);\nrequire('./status')(AV);\nrequire('./search')(AV);\nrequire('./insight')(AV);\n\nmodule.exports = AV;\n\n/**\n * Options to controll the authentication for an operation\n * @typedef {Object} AuthOptions\n * @property {String} [sessionToken] Specify a user to excute the operation as.\n * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided.\n * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set.\n */\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","var localStorage = require('./localstorage.js');\nvar XMLHttpRequest = require('./xmlhttprequest.js');\nvar FormData = require('./formdata.js');\nvar WebSocket = require('./websocket.js');\nvar navigator = require('./navigator');\n\nmodule.exports = {\n polyfill(target = global || window) {\n if (typeof target !== 'object') {\n throw new Error('polyfill target is not an Object');\n }\n const polyfills = {\n localStorage,\n XMLHttpRequest,\n FormData,\n WebSocket,\n Object,\n navigator,\n };\n for (let k in polyfills) {\n if (!target[k]) target[k] = polyfills[k];\n }\n },\n localStorage,\n XMLHttpRequest,\n FormData,\n WebSocket,\n}\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/index.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var PUBLIC_KEY = \"*\";\n\n /**\n * Creates a new ACL.\n * If no argument is given, the ACL has no permissions for anyone.\n * If the argument is a AV.User, the ACL will have read and write\n * permission for only that user.\n * If the argument is any other JSON object, that object will be interpretted\n * as a serialized ACL created with toJSON().\n * @see AV.Object#setACL\n * @class\n *\n *

An ACL, or Access Control List can be added to any\n * AV.Object to restrict access to only a subset of users\n * of your application.

\n */\n AV.ACL = function(arg1) {\n var self = this;\n self.permissionsById = {};\n if (_.isObject(arg1)) {\n if (arg1 instanceof AV.User) {\n self.setReadAccess(arg1, true);\n self.setWriteAccess(arg1, true);\n } else {\n if (_.isFunction(arg1)) {\n throw new Error('AV.ACL() called with a function. Did you forget ()?');\n }\n AV._objectEach(arg1, function(accessList, userId) {\n if (!_.isString(userId)) {\n throw new Error('Tried to create an ACL with an invalid userId.');\n }\n self.permissionsById[userId] = {};\n AV._objectEach(accessList, function(allowed, permission) {\n if (permission !== \"read\" && permission !== \"write\") {\n throw new Error('Tried to create an ACL with an invalid permission type.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('Tried to create an ACL with an invalid permission value.');\n }\n self.permissionsById[userId][permission] = allowed;\n });\n });\n }\n }\n };\n\n /**\n * Returns a JSON-encoded version of the ACL.\n * @return {Object}\n */\n AV.ACL.prototype.toJSON = function() {\n return _.clone(this.permissionsById);\n };\n\n AV.ACL.prototype._setAccess = function(accessType, userId, allowed) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n if (!_.isString(userId)) {\n throw new Error('userId must be a string.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('allowed must be either true or false.');\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n if (!allowed) {\n // The user already doesn't have this permission, so no action needed.\n return;\n } else {\n permissions = {};\n this.permissionsById[userId] = permissions;\n }\n }\n\n if (allowed) {\n this.permissionsById[userId][accessType] = true;\n } else {\n delete permissions[accessType];\n if (_.isEmpty(permissions)) {\n delete this.permissionsById[userId];\n }\n }\n };\n\n AV.ACL.prototype._getAccess = function(accessType, userId) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n return false;\n }\n return permissions[accessType] ? true : false;\n };\n\n /**\n * Set whether the given user is allowed to read this object.\n * @param userId An instance of AV.User or its objectId.\n * @param {Boolean} allowed Whether that user should have read access.\n */\n AV.ACL.prototype.setReadAccess = function(userId, allowed) {\n this._setAccess(\"read\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to read this object.\n * Even if this returns false, the user may still be able to access it if\n * getPublicReadAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getReadAccess = function(userId) {\n return this._getAccess(\"read\", userId);\n };\n\n /**\n * Set whether the given user id is allowed to write this object.\n * @param userId An instance of AV.User or its objectId, or a AV.Role..\n * @param {Boolean} allowed Whether that user should have write access.\n */\n AV.ACL.prototype.setWriteAccess = function(userId, allowed) {\n this._setAccess(\"write\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to write this object.\n * Even if this returns false, the user may still be able to write it if\n * getPublicWriteAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getWriteAccess = function(userId) {\n return this._getAccess(\"write\", userId);\n };\n\n /**\n * Set whether the public is allowed to read this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicReadAccess = function(allowed) {\n this.setReadAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to read this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicReadAccess = function() {\n return this.getReadAccess(PUBLIC_KEY);\n };\n\n /**\n * Set whether the public is allowed to write this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicWriteAccess = function(allowed) {\n this.setWriteAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to write this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicWriteAccess = function() {\n return this.getWriteAccess(PUBLIC_KEY);\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to read this object. Even if this returns false, the role may\n * still be able to write it if a parent role has read access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has read access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleReadAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getReadAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to write this object. Even if this returns false, the role may\n * still be able to write it if a parent role has write access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has write access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleWriteAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getWriteAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to read this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can read this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleReadAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setReadAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to write this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can write this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleWriteAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setWriteAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/acl.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * Contains functions for calling and declaring\n *

\n * Some functions are only available from Cloud Code.\n *

\n *\n * @namespace\n */\n AV.Cloud = AV.Cloud || {};\n\n _.extend(AV.Cloud, /** @lends AV.Cloud */ {\n /**\n * Makes a call to a cloud function.\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n run: function(name, data, options) {\n var request = AVRequest('functions', name, null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response\n * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object}\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result of the function.\n */\n rpc: function(name, data, options) {\n if (_.isArray(data)) {\n return Promise.reject(new Error('Can\\'t pass Array as the param of rpc function in JavaScript SDK.'));\n }\n\n return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Make a call to request server date time.\n * @return {Promise.} A promise that will be resolved with the result\n * of the function.\n * @since 0.5.9\n */\n getServerDate: function() {\n var request = AVRequest(\"date\", null, null, 'GET');\n\n return request.then(function(resp) {\n return AV._decode(resp);\n });\n },\n\n /**\n * Makes a call to request a sms code for operation verification.\n * @param {Object} data The mobile phone number string or a JSON\n * object that contains mobilePhoneNumber,template,op,ttl,name etc.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n requestSmsCode: function(data){\n if(_.isString(data)) {\n data = { mobilePhoneNumber: data };\n }\n if(!data.mobilePhoneNumber) {\n throw new Error('Missing mobilePhoneNumber.');\n }\n var request = AVRequest(\"requestSmsCode\", null, null, 'POST',\n data);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode\n * @param {String} code The sms code sent by AV.Cloud.requestSmsCode\n * @param {phone} phone The mobile phoner number(optional).\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifySmsCode: function(code, phone){\n if(!code)\n throw new Error('Missing sms code.');\n var params = {};\n if(_.isString(phone)) {\n params['mobilePhoneNumber'] = phone;\n }\n\n var request = AVRequest(\"verifySmsCode\", code, null, 'POST',\n params);\n return request;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cloudfunction.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var eventSplitter = /\\s+/;\n var slice = Array.prototype.slice;\n\n /**\n * @class\n *\n *

AV.Events is a fork of Backbone's Events module, provided for your\n * convenience.

\n *\n *

A module that can be mixed in to any object in order to provide\n * it with custom events. You may bind callback functions to an event\n * with `on`, or remove these functions with `off`.\n * Triggering an event fires all callbacks in the order that `on` was\n * called.\n *\n * @private\n * @example\n * var object = {};\n * _.extend(object, AV.Events);\n * object.on('expand', function(){ alert('expanded'); });\n * object.trigger('expand');

\n *\n */\n AV.Events = {\n /**\n * Bind one or more space separated events, `events`, to a `callback`\n * function. Passing `\"all\"` will bind the callback to all events fired.\n */\n on: function(events, callback, context) {\n\n var calls, event, node, tail, list;\n if (!callback) {\n return this;\n }\n events = events.split(eventSplitter);\n calls = this._callbacks || (this._callbacks = {});\n\n // Create an immutable callback list, allowing traversal during\n // modification. The tail is an empty object that will always be used\n // as the next node.\n event = events.shift();\n while (event) {\n list = calls[event];\n node = list ? list.tail : {};\n node.next = tail = {};\n node.context = context;\n node.callback = callback;\n calls[event] = {tail: tail, next: list ? list.next : node};\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Remove one or many callbacks. If `context` is null, removes all callbacks\n * with that function. If `callback` is null, removes all callbacks for the\n * event. If `events` is null, removes all bound callbacks for all events.\n */\n off: function(events, callback, context) {\n var event, calls, node, tail, cb, ctx;\n\n // No events, or removing *all* events.\n if (!(calls = this._callbacks)) {\n return;\n }\n if (!(events || callback || context)) {\n delete this._callbacks;\n return this;\n }\n\n // Loop through the listed events and contexts, splicing them out of the\n // linked list of callbacks if appropriate.\n events = events ? events.split(eventSplitter) : _.keys(calls);\n event = events.shift();\n while (event) {\n node = calls[event];\n delete calls[event];\n if (!node || !(callback || context)) {\n continue;\n }\n // Create a new list, omitting the indicated callbacks.\n tail = node.tail;\n node = node.next;\n while (node !== tail) {\n cb = node.callback;\n ctx = node.context;\n if ((callback && cb !== callback) || (context && ctx !== context)) {\n this.on(event, cb, ctx);\n }\n node = node.next;\n }\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Trigger one or many events, firing all bound callbacks. Callbacks are\n * passed the same arguments as `trigger` is, apart from the event name\n * (unless you're listening on `\"all\"`, which will cause your callback to\n * receive the true name of the event as the first argument).\n */\n trigger: function(events) {\n var event, node, calls, tail, args, all, rest;\n if (!(calls = this._callbacks)) {\n return this;\n }\n all = calls.all;\n events = events.split(eventSplitter);\n rest = slice.call(arguments, 1);\n\n // For each event, walk through the linked list of callbacks twice,\n // first to trigger the event, then to trigger any `\"all\"` callbacks.\n event = events.shift();\n while (event) {\n node = calls[event];\n if (node) {\n tail = node.tail;\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, rest);\n }\n }\n node = all;\n if (node) {\n tail = node.tail;\n args = [event].concat(rest);\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, args);\n }\n }\n event = events.shift();\n }\n\n return this;\n }\n };\n\n /**\n * @function\n */\n AV.Events.bind = AV.Events.on;\n\n /**\n * @function\n */\n AV.Events.unbind = AV.Events.off;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/event.js","const _ = require('underscore');\nconst cos = require('./uploader/cos');\nconst qiniu = require('./uploader/qiniu');\nconst s3 = require('./uploader/s3');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\nconst { tap } = require('./utils');\nconst debug = require('debug')('leancloud:file');\nconst parseBase64 = require('./utils/parse-base64');\n\nmodule.exports = function(AV) {\n\n // 挂载一些配置\n let avConfig = AV._config;\n\n const hexOctet = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);\n\n // port from browserify path module\n // since react-native packager won't shim node modules.\n const extname = (path) => {\n return path.match(/^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/)[4];\n };\n\n const b64Digit = (number) => {\n if (number < 26) {\n return String.fromCharCode(65 + number);\n }\n if (number < 52) {\n return String.fromCharCode(97 + (number - 26));\n }\n if (number < 62) {\n return String.fromCharCode(48 + (number - 52));\n }\n if (number === 62) {\n return '+';\n }\n if (number === 63) {\n return '/';\n }\n throw new Error('Tried to encode large digit ' + number + ' in base64.');\n };\n\n var encodeBase64 = function(array) {\n var chunks = [];\n chunks.length = Math.ceil(array.length / 3);\n _.times(chunks.length, function(i) {\n var b1 = array[i * 3];\n var b2 = array[i * 3 + 1] || 0;\n var b3 = array[i * 3 + 2] || 0;\n\n var has2 = (i * 3 + 1) < array.length;\n var has3 = (i * 3 + 2) < array.length;\n\n chunks[i] = [\n b64Digit((b1 >> 2) & 0x3F),\n b64Digit(((b1 << 4) & 0x30) | ((b2 >> 4) & 0x0F)),\n has2 ? b64Digit(((b2 << 2) & 0x3C) | ((b3 >> 6) & 0x03)) : \"=\",\n has3 ? b64Digit(b3 & 0x3F) : \"=\"\n ].join(\"\");\n });\n return chunks.join(\"\");\n };\n\n /**\n * An AV.File is a local representation of a file that is saved to the AV\n * cloud.\n * @param name {String} The file's name. This will change to a unique value\n * once the file has finished saving.\n * @param data {Array} The data for the file, as either:\n * 1. an Array of byte value Numbers, or\n * 2. an Object like { base64: \"...\" } with a base64-encoded String.\n * 3. a File object selected with a file upload control. (3) only works\n * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.\n * 4.a Buffer object in Node.js runtime.\n *\n * For example:
\n   * var fileUploadControl = $(\"#profilePhotoFileUpload\")[0];\n   * if (fileUploadControl.files.length > 0) {\n   *   var file = fileUploadControl.files[0];\n   *   var name = \"photo.jpg\";\n   *   var file = new AV.File(name, file);\n   *   file.save().then(function() {\n   *     // The file has been saved to AV.\n   *   }, function(error) {\n   *     // The file either could not be read, or could not be saved to AV.\n   *   });\n   * }
\n *\n * @class\n * @param [mimeType] {String} Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n */\n AV.File = function(name, data, mimeType) {\n\n this.attributes = {\n name,\n url: '',\n metaData: {},\n // 用来存储转换后要上传的 base64 String\n base64: '',\n };\n\n if (_.isString(data)) {\n throw new TypeError(\"Creating an AV.File from a String is not yet supported.\");\n }\n if (_.isArray(data)) {\n this.attributes.metaData.size = data.length;\n data = { base64: encodeBase64(data) };\n }\n\n this._extName = '';\n this._data = data;\n\n let owner;\n if (data && data.owner) {\n owner = data.owner;\n } else if (!AV._config.disableCurrentUser) {\n try {\n owner = AV.User.current();\n } catch (error) {\n if ('SYNC_API_NOT_AVAILABLE' === error.code) {\n console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().');\n } else {\n throw error;\n }\n }\n }\n \n this.attributes.metaData.owner = owner ? owner.id : 'unknown';\n\n this.set('mime_type', mimeType);\n };\n\n /**\n * Creates a fresh AV.File object with exists url for saving to AVOS Cloud.\n * @param {String} name the file name\n * @param {String} url the file url.\n * @param {Object} [metaData] the file metadata object.\n * @param {String} [type] Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n * @return {AV.File} the file object\n */\n AV.File.withURL = function(name, url, metaData, type) {\n if (!name || !url){\n throw new Error(\"Please provide file name and url\");\n }\n var file = new AV.File(name, null, type);\n //copy metaData properties to file.\n if (metaData){\n for(var prop in metaData){\n if (!file.attributes.metaData[prop])\n file.attributes.metaData[prop] = metaData[prop];\n }\n }\n file.attributes.url = url;\n //Mark the file is from external source.\n file.attributes.metaData.__source = 'external';\n return file;\n };\n\n /**\n * Creates a file object with exists objectId.\n * @param {String} objectId The objectId string\n * @return {AV.File} the file object\n */\n AV.File.createWithoutData = function(objectId) {\n var file = new AV.File();\n file.id = objectId;\n return file;\n };\n\n AV.File.prototype = {\n className: '_File',\n\n _toFullJSON(seenObjects) {\n var json = _.clone(this.attributes);\n AV._objectEach(json, function(val, key) {\n json[key] = AV._encode(val, seenObjects);\n });\n AV._objectEach(this._operations, function(val, key) {\n json[key] = val;\n });\n\n if (_.has(this, \"id\")) {\n json.objectId = this.id;\n }\n _(['createdAt', 'updatedAt']).each((key) => {\n if (_.has(this, key)) {\n const val = this[key];\n json[key] = _.isDate(val) ? val.toJSON() : val;\n }\n });\n json.__type = \"File\";\n return json;\n },\n\n toJSON() {\n const json = this._toFullJSON();\n // add id and keep __type for backward compatible\n if (_.has(this, 'id')) {\n json.id = this.id;\n }\n return json;\n },\n\n /**\n * Returns the ACL for this file.\n * @returns {AV.ACL} An instance of AV.ACL.\n */\n getACL: function() {\n return this._acl;\n },\n\n /**\n * Sets the ACL to be used for this file.\n * @param {AV.ACL} acl An instance of AV.ACL.\n */\n setACL: function(acl) {\n if (!(acl instanceof AV.ACL)) {\n return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.');\n }\n this._acl = acl;\n },\n\n /**\n * Gets the name of the file. Before save is called, this is the filename\n * given by the user. After save is called, that name gets prefixed with a\n * unique identifier.\n */\n name: function() {\n return this.get('name');\n },\n\n /**\n * Gets the url of the file. It is only available after you save the file or\n * after you get the file from a AV.Object.\n * @return {String}\n */\n url: function() {\n return this.get('url');\n },\n\n /**\n * Gets the attributs of the file object.\n * @param {String} The attribute name which want to get.\n * @returns {Any}\n */\n get: function(attrName) {\n switch (attrName) {\n case 'objectId':\n return this.id;\n case 'url':\n case 'name':\n case 'mime_type':\n case 'metaData':\n case 'createdAt':\n case 'updatedAt':\n return this.attributes[attrName];\n default:\n return this.attributes.metaData[attrName];\n }\n },\n\n /**\n * Set the metaData of the file object.\n * @param {Object} Object is an key value Object for setting metaData.\n * @param {String} attr is an optional metadata key.\n * @param {Object} value is an optional metadata value.\n * @returns {String|Number|Array|Object}\n */\n set: function(...args) {\n const set = (attrName, value) => {\n switch (attrName) {\n case 'name':\n case 'url':\n case 'mime_type':\n case 'base64':\n case 'metaData':\n this.attributes[attrName] = value;\n break;\n default:\n // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面\n this.attributes.metaData[attrName] = value;\n break;\n }\n };\n\n switch (args.length) {\n case 1:\n // 传入一个 Object\n for (var k in args[0]) {\n set(k, args[0][k]);\n }\n break;\n case 2:\n set(args[0], args[1]);\n break;\n }\n },\n\n /**\n *

Returns the file's metadata JSON object if no arguments is given.Returns the\n * metadata value if a key is given.Set metadata value if key and value are both given.

\n *

\n    *  var metadata = file.metaData(); //Get metadata JSON object.\n    *  var size = file.metaData('size');  // Get the size metadata value.\n    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.\n    *

\n * @return {Object} The file's metadata JSON object.\n * @param {String} attr an optional metadata key.\n * @param {Object} value an optional metadata value.\n **/\n metaData: function(attr, value) {\n if (attr && value) {\n this.attributes.metaData[attr] = value;\n return this;\n } else if (attr && !value) {\n return this.attributes.metaData[attr];\n } else {\n return this.attributes.metaData;\n }\n },\n\n /**\n * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。\n * @return {String} 缩略图URL\n * @param {Number} width 宽度,单位:像素\n * @param {Number} heigth 高度,单位:像素\n * @param {Number} quality 质量,1-100的数字,默认100\n * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。\n * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。\n */\n\n thumbnailURL: function(width, height, quality, scaleToFit, fmt) {\n const url = this.attributes.url;\n if (!url) {\n throw new Error('Invalid url.');\n }\n if (!width || !height || width <= 0 || height <= 0 ) {\n throw new Error('Invalid width or height value.');\n }\n quality = quality || 100;\n scaleToFit = !scaleToFit ? true : scaleToFit;\n if (quality <= 0 || quality > 100) {\n throw new Error('Invalid quality value.');\n }\n fmt = fmt || 'png';\n const mode = scaleToFit ? 2: 1;\n return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt;\n },\n\n /**\n * Returns the file's size.\n * @return {Number} The file's size in bytes.\n **/\n size: function() {\n return this.metaData().size;\n },\n\n /**\n * Returns the file's owner.\n * @return {String} The file's owner id.\n */\n ownerId: function() {\n return this.metaData().owner;\n },\n\n /**\n * Destroy the file.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n if (!this.id) {\n return Promise.reject(new Error('The file id is not eixsts.'));\n }\n var request = AVRequest(\"files\", null, this.id, 'DELETE', null, options);\n return request;\n },\n\n /**\n * Request Qiniu upload token\n * @param {string} type\n * @return {Promise} Resolved with the response\n * @private\n */\n _fileToken(type, route = 'fileTokens') {\n let name = this.attributes.name;\n\n let extName = extname(name);\n if (!extName && this._extName) {\n name += this._extName;\n extName = this._extName;\n }\n // Create 16-bits uuid as qiniu key.\n const key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName;\n const data = {\n key,\n name,\n ACL: this._acl,\n mime_type: type,\n metaData: this.attributes.metaData,\n };\n this._qiniu_key = key;\n return AVRequest(route, null, null, 'POST', data);\n },\n\n /**\n * @callback UploadProgressCallback\n * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes\n */\n /**\n * Saves the file to the AV cloud.\n * @param {Object} [options]\n * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。\n * @return {Promise} Promise that is resolved when the save finishes.\n */\n save(options) {\n if (this.id) {\n throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.');\n }\n if (!this._previousSave) {\n if (this._data) {\n let mimeType = this.get('mime_type');\n this._previousSave = this._fileToken(mimeType).then(uploadInfo => {\n if (uploadInfo.mime_type) {\n mimeType = uploadInfo.mime_type;\n this.set('mime_type', mimeType);\n }\n this._token = uploadInfo.token;\n return Promise.resolve().then(() => {\n const data = this._data;\n if (data && data.base64) {\n return parseBase64(data.base64, mimeType);\n }\n if (data && data.blob) {\n if (!data.blob.type && mimeType) {\n data.blob.type = mimeType;\n }\n if (!data.blob.name) {\n data.blob.name = this.get('name');\n }\n if (process.env.CLIENT_PLATFORM === 'ReactNative' || process.env.CLIENT_PLATFORM === 'Weapp') {\n this._extName = extname(data.blob.uri);\n }\n return data.blob;\n }\n if (typeof File !== \"undefined\" && data instanceof File) {\n if (data.size) {\n this.attributes.metaData.size = data.size;\n }\n if (data.name) {\n this._extName = extname(data.name);\n }\n return data;\n }\n if (typeof Buffer !== \"undefined\" && Buffer.isBuffer(data)) {\n this.attributes.metaData.size = data.length;\n return data;\n }\n throw new TypeError('malformed file data');\n }).then(data => {\n let uploadPromise;\n switch (uploadInfo.provider) {\n case 's3':\n uploadPromise = s3(uploadInfo, data, this, options);\n break;\n case 'qcloud':\n uploadPromise = cos(uploadInfo, data, this, options);\n break;\n case 'qiniu':\n default:\n uploadPromise = qiniu(uploadInfo, data, this, options);\n break;\n }\n return uploadPromise.then(\n tap(() => this._callback(true)),\n (error) => {\n this._callback(false);\n throw error;\n }\n );\n });\n });\n } else if (this.attributes.url && this.attributes.metaData.__source === 'external') {\n // external link file.\n const data = {\n name: this.attributes.name,\n ACL: this._acl,\n metaData: this.attributes.metaData,\n mime_type: this.mimeType,\n url: this.attributes.url,\n };\n this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then((response) => {\n this.attributes.name = response.name;\n this.attributes.url = response.url;\n this.id = response.objectId;\n if (response.size) {\n this.attributes.metaData.size = response.size;\n }\n return this;\n });\n }\n }\n return this._previousSave;\n },\n\n _callback(success) {\n AVRequest('fileCallback', null, null, 'post', {\n token: this._token,\n result: success,\n }).catch(debug);\n delete this._token;\n delete this._data;\n },\n\n /**\n * fetch the file from server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option.\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(options) {\n var options = null;\n\n var request = AVRequest('files', null, this.id, 'GET', options);\n return request.then(this._finishFetch.bind(this));\n },\n _finishFetch: function(response) {\n var value = AV.Object.prototype.parse(response);\n value.attributes = {\n name: value.name,\n url: value.url,\n mime_type: value.mime_type,\n bucket: value.bucket,\n };\n value.attributes.metaData = value.metaData || {};\n value.id = value.objectId;\n // clean\n delete value.objectId;\n delete value.metaData;\n delete value.url;\n delete value.name;\n delete value.mime_type;\n delete value.bucket;\n _.extend(this, value);\n return this;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/file.js","var _ = require('underscore');\n\n/*global navigator: false */\nmodule.exports = function(AV) {\n /**\n * Creates a new GeoPoint with any of the following forms:
\n * @example\n * new GeoPoint(otherGeoPoint)\n * new GeoPoint(30, 30)\n * new GeoPoint([30, 30])\n * new GeoPoint({latitude: 30, longitude: 30})\n * new GeoPoint() // defaults to (0, 0)\n * @class\n *\n *

Represents a latitude / longitude point that may be associated\n * with a key in a AVObject or used as a reference point for geo queries.\n * This allows proximity-based queries on the key.

\n *\n *

Only one key in a class may contain a GeoPoint.

\n *\n *

Example:

\n   *   var point = new AV.GeoPoint(30.0, -20.0);\n   *   var object = new AV.Object(\"PlaceObject\");\n   *   object.set(\"location\", point);\n   *   object.save();

\n */\n AV.GeoPoint = function(arg1, arg2) {\n if (_.isArray(arg1)) {\n AV.GeoPoint._validate(arg1[0], arg1[1]);\n this.latitude = arg1[0];\n this.longitude = arg1[1];\n } else if (_.isObject(arg1)) {\n AV.GeoPoint._validate(arg1.latitude, arg1.longitude);\n this.latitude = arg1.latitude;\n this.longitude = arg1.longitude;\n } else if (_.isNumber(arg1) && _.isNumber(arg2)) {\n AV.GeoPoint._validate(arg1, arg2);\n this.latitude = arg1;\n this.longitude = arg2;\n } else {\n this.latitude = 0;\n this.longitude = 0;\n }\n\n // Add properties so that anyone using Webkit or Mozilla will get an error\n // if they try to set values that are out of bounds.\n var self = this;\n if (this.__defineGetter__ && this.__defineSetter__) {\n // Use _latitude and _longitude to actually store the values, and add\n // getters and setters for latitude and longitude.\n this._latitude = this.latitude;\n this._longitude = this.longitude;\n this.__defineGetter__(\"latitude\", function() {\n return self._latitude;\n });\n this.__defineGetter__(\"longitude\", function() {\n return self._longitude;\n });\n this.__defineSetter__(\"latitude\", function(val) {\n AV.GeoPoint._validate(val, self.longitude);\n self._latitude = val;\n });\n this.__defineSetter__(\"longitude\", function(val) {\n AV.GeoPoint._validate(self.latitude, val);\n self._longitude = val;\n });\n }\n };\n\n /**\n * @lends AV.GeoPoint.prototype\n * @property {float} latitude North-south portion of the coordinate, in range\n * [-90, 90]. Throws an exception if set out of range in a modern browser.\n * @property {float} longitude East-west portion of the coordinate, in range\n * [-180, 180]. Throws if set out of range in a modern browser.\n */\n\n /**\n * Throws an exception if the given lat-long is out of bounds.\n * @private\n */\n AV.GeoPoint._validate = function(latitude, longitude) {\n if (latitude < -90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" < -90.0.\");\n }\n if (latitude > 90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" > 90.0.\");\n }\n if (longitude < -180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" < -180.0.\");\n }\n if (longitude > 180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" > 180.0.\");\n }\n };\n\n /**\n * Creates a GeoPoint with the user's current location, if available.\n * @return {Promise.}\n */\n AV.GeoPoint.current = () => new AV.Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(function(location) {\n resolve(new AV.GeoPoint({\n latitude: location.coords.latitude,\n longitude: location.coords.longitude\n }));\n }, reject);\n });\n\n AV.GeoPoint.prototype = {\n /**\n * Returns a JSON representation of the GeoPoint, suitable for AV.\n * @return {Object}\n */\n toJSON: function() {\n AV.GeoPoint._validate(this.latitude, this.longitude);\n return {\n \"__type\": \"GeoPoint\",\n latitude: this.latitude,\n longitude: this.longitude\n };\n },\n\n /**\n * Returns the distance from this GeoPoint to another in radians.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n radiansTo: function(point) {\n var d2r = Math.PI / 180.0;\n var lat1rad = this.latitude * d2r;\n var long1rad = this.longitude * d2r;\n var lat2rad = point.latitude * d2r;\n var long2rad = point.longitude * d2r;\n var deltaLat = lat1rad - lat2rad;\n var deltaLong = long1rad - long2rad;\n var sinDeltaLatDiv2 = Math.sin(deltaLat / 2);\n var sinDeltaLongDiv2 = Math.sin(deltaLong / 2);\n // Square of half the straight line chord distance between both points.\n var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) +\n (Math.cos(lat1rad) * Math.cos(lat2rad) *\n sinDeltaLongDiv2 * sinDeltaLongDiv2));\n a = Math.min(1.0, a);\n return 2 * Math.asin(Math.sqrt(a));\n },\n\n /**\n * Returns the distance from this GeoPoint to another in kilometers.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n kilometersTo: function(point) {\n return this.radiansTo(point) * 6371.0;\n },\n\n /**\n * Returns the distance from this GeoPoint to another in miles.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n milesTo: function(point) {\n return this.radiansTo(point) * 3958.8;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/geopoint.js","require('weapp-polyfill/auto-polyfill');\n\nmodule.exports = require('./index');\n\n\n\n// WEBPACK FOOTER //\n// ./src/index-weapp.js","const AV = require('./av');\nconst request = require('./request');\n\nconst initialize = (appId, appKey, masterKey, hookKey) => {\n if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) {\n console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.');\n }\n AV.applicationId = appId;\n AV.applicationKey = appKey;\n AV.masterKey = masterKey;\n if (!process.env.CLIENT_PLATFORM) {\n AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY;\n }\n AV._useMasterKey = false;\n};\n\nconst masterKeyWarn = () => {\n console.warn('MasterKey is not supposed to be used in browser.');\n};\n\n/**\n * Call this method first to set up your authentication tokens for AV.\n * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .\n * @function AV.init\n * @param {Object} options\n * @param {String} options.appId application id\n * @param {String} options.appKey application key\n * @param {String} options.masterKey application master key\n*/\n\nAV.init = (...args) => {\n if (args.length === 1) {\n const options = args[0];\n if (typeof options === 'object') {\n if (process.env.CLIENT_PLATFORM && options.masterKey) {\n masterKeyWarn();\n }\n initialize(options.appId, options.appKey, options.masterKey, options.hookKey);\n request.setServerUrlByRegion(options.region);\n } else {\n throw new Error('AV.init(): Parameter is not correct.');\n }\n } else {\n // 兼容旧版本的初始化方法\n if (process.env.CLIENT_PLATFORM && args[3]) {\n masterKeyWarn();\n }\n initialize(...args);\n request.setServerUrlByRegion('cn');\n }\n};\n\n// If we're running in node.js, allow using the master key.\nif (!process.env.CLIENT_PLATFORM) {\n AV.Cloud = AV.Cloud || {};\n /**\n * Switches the LeanCloud SDK to using the Master key. The Master key grants\n * priveleged access to the data in LeanCloud and can be used to bypass ACLs and\n * other restrictions that are applied to the client SDKs.\n *

Available in Cloud Code and Node.js only.\n *

\n */\n AV.Cloud.useMasterKey = function() {\n AV._useMasterKey = true;\n };\n}\n\n// 兼容老版本的初始化方法\nAV.initialize = AV.init;\n\n\n\n// WEBPACK FOOTER //\n// ./src/init.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * 包含了使用了 LeanCloud\n * 离线数据分析功能的函数。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @namespace\n */\n AV.Insight = AV.Insight || {};\n\n _.extend(AV.Insight, /** @lends AV.Insight */ {\n\n /**\n * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用\n * AV.Insight.JobQuery 查询任务状态和结果。\n * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
\n     *                   { \"sql\" : \"select count(*) as c,gender from _User group by gender\",\n     *                     \"saveAs\": {\n     *                         \"className\" : \"UserGender\",\n     *                         \"limit\": 1\n     *                      }\n     *                   }\n     *                  
\n * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n startJob: function(jobConfig, options) {\n if(!jobConfig || !jobConfig.sql) {\n throw new Error('Please provide the sql to run the job.');\n }\n var data = {\n jobConfig: jobConfig,\n appId: AV.applicationId\n };\n var request = AVRequest(\"bigquery\", 'jobs', null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).id;\n });\n },\n\n /**\n * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成\n * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息,\n * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。\n *\n */\n on: function(event, cb) {\n }\n });\n\n /**\n * 创建一个对象,用于查询 Insight 任务状态和结果。\n * @class\n * @param {String} id 任务 id\n * @since 0.5.5\n */\n AV.Insight.JobQuery = function(id, className) {\n if(!id) {\n throw new Error('Please provide the job id.');\n }\n this.id = id;\n this.className = className;\n this._skip = 0;\n this._limit = 100;\n };\n\n AV.Insight.JobQuery.prototype = {\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n this._limit = n;\n return this;\n },\n\n /**\n * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数,\n * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间\n * startTime、endTime 等信息。\n *\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n *\n */\n find: function(options) {\n var params = {\n skip: this._skip,\n limit: this._limit\n };\n\n var request = AVRequest(\"bigquery\", 'jobs', this.id, \"GET\",\n params, options);\n var self = this;\n return request.then(function(response) {\n if(response.error) {\n return AV.Promise.reject(new AVError(response.code, response.error));\n }\n return AV.Promise.resolve(response);\n });\n }\n\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/insight.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst utils = require('./utils');\n\nconst RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt'];\nconst checkReservedKey = key => {\n if (RESERVED_KEYS.indexOf(key) !== -1) {\n throw new Error(`key[${key}] is reserved`);\n }\n};\n\n// AV.Object is analogous to the Java AVObject.\n// It also implements the same interface as a Backbone model.\n\nmodule.exports = function(AV) {\n /**\n * Creates a new model with defined attributes. A client id (cid) is\n * automatically generated and assigned for you.\n *\n *

You won't normally call this method directly. It is recommended that\n * you use a subclass of AV.Object instead, created by calling\n * extend.

\n *\n *

However, if you don't want to use a subclass, or aren't sure which\n * subclass is appropriate, you can use this form:

\n   *     var object = new AV.Object(\"ClassName\");\n   * 
\n * That is basically equivalent to:
\n   *     var MyClass = AV.Object.extend(\"ClassName\");\n   *     var object = new MyClass();\n   * 

\n *\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @see AV.Object.extend\n *\n * @class\n *\n *

The fundamental unit of AV data, which implements the Backbone Model\n * interface.

\n */\n AV.Object = function(attributes, options) {\n // Allow new AV.Object(\"ClassName\") as a shortcut to _create.\n if (_.isString(attributes)) {\n return AV.Object._create.apply(this, arguments);\n }\n\n attributes = attributes || {};\n if (options && options.parse) {\n attributes = this.parse(attributes);\n attributes = this._mergeMagicFields(attributes);\n }\n var defaults = AV._getValue(this, 'defaults');\n if (defaults) {\n attributes = _.extend({}, defaults, attributes);\n }\n if (options && options.collection) {\n this.collection = options.collection;\n }\n\n this._serverData = {}; // The last known data for this object from cloud.\n this._opSetQueue = [{}]; // List of sets of changes to the data.\n this._flags = {};\n this.attributes = {}; // The best estimate of this's current data.\n\n this._hashedJSON = {}; // Hash of values of containers at last save.\n this._escapedAttributes = {};\n this.cid = _.uniqueId('c');\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this.set(attributes, { silent: true });\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this._hasData = true;\n this._previousAttributes = _.clone(this.attributes);\n this.initialize.apply(this, arguments);\n };\n\n /**\n * @lends AV.Object.prototype\n * @property {String} id The objectId of the AV Object.\n */\n\n /**\n * Saves the given list of AV.Object.\n * If any error is encountered, stops and calls the error handler.\n *\n *
\n   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {\n   *     // All the objects were saved.\n   *   }, function(error) {\n   *     // An error occurred while saving one of the objects.\n   *   });\n   *\n   * @param {Array} list A list of AV.Object.\n   */\n  AV.Object.saveAll = function(list, options) {\n    return AV.Object._deepSaveAsync(list, null, options);\n  };\n\n  /**\n   * Fetch the given list of AV.Object.\n   *\n   * @param {AV.Object[]} objects A list of AV.Object\n   * @param {AuthOptions} options\n   * @return {Promise.} The given list of AV.Object, updated\n   */\n\n  AV.Object.fetchAll = (objects, options) =>\n    AV.Promise.resolve().then(() =>\n      AVRequest('batch', null, null, 'POST', {\n        requests: _.map(objects, object => {\n          if (!object.className) throw new Error('object must have className to fetch');\n          if (!object.id) throw new Error('object must have id to fetch');\n          if (object.dirty()) throw new Error('object is modified but not saved');\n          return {\n            method: 'GET',\n            path: `/1.1/classes/${object.className}/${object.id}`,\n          };\n        }),\n      }, options)\n    ).then(function(response) {\n      _.forEach(objects, function(object, i) {\n        if (response[i].success) {\n          object._finishFetch(\n            object.parse(response[i].success));\n        } else {\n          const error = new Error(response[i].error.error);\n          error.code = response[i].error.code;\n          throw error;\n        }\n      });\n      return objects;\n    });\n\n  // Attach all inheritable methods to the AV.Object prototype.\n  _.extend(AV.Object.prototype, AV.Events,\n           /** @lends AV.Object.prototype */ {\n    _fetchWhenSave: false,\n\n    /**\n     * Initialize is an empty function by default. Override it with your own\n     * initialization logic.\n     */\n    initialize: function(){},\n\n   /**\n     * Set whether to enable fetchWhenSave option when updating object.\n     * When set true, SDK would fetch the latest object after saving.\n     * Default is false.\n     *\n     * @deprecated use AV.Object#save with options.fetchWhenSave instead\n     * @param {boolean} enable  true to enable fetchWhenSave option.\n     */\n    fetchWhenSave: function(enable){\n      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');\n      if (!_.isBoolean(enable)) {\n        throw new Error('Expect boolean value for fetchWhenSave');\n      }\n      this._fetchWhenSave = enable;\n    },\n\n   /**\n    * Returns the object's objectId.\n    * @return {String} the objectId.\n    */\n    getObjectId: function() {\n      return this.id;\n    },\n\n   /**\n    * Returns the object's createdAt attribute.\n    * @return {Date}\n    */\n    getCreatedAt: function() {\n      return this.createdAt || this.get('createdAt');\n    },\n\n   /**\n    * Returns the object's updatedAt attribute.\n    * @return {Date}\n    */\n    getUpdatedAt: function() {\n      return this.updatedAt || this.get('updatedAt');\n    },\n\n    /**\n     * Returns a JSON version of the object suitable for saving to AV.\n     * @return {Object}\n     */\n    toJSON: function() {\n      var json = this._toFullJSON();\n      AV._arrayEach([\"__type\", \"className\"],\n                       function(key) { delete json[key]; });\n      return json;\n    },\n\n    _toFullJSON: function(seenObjects) {\n      var json = _.clone(this.attributes);\n      AV._objectEach(json, function(val, key) {\n        json[key] = AV._encode(val, seenObjects);\n      });\n      AV._objectEach(this._operations, function(val, key) {\n        json[key] = val;\n      });\n\n      if (_.has(this, \"id\")) {\n        json.objectId = this.id;\n      }\n      _(['createdAt', 'updatedAt']).each((key) => {\n        if (_.has(this, key)) {\n          const val = this[key];\n          json[key] = _.isDate(val) ? val.toJSON() : val;\n        }\n      });\n      json.__type = \"Object\";\n      json.className = this.className;\n      return json;\n    },\n\n    /**\n     * Updates _hashedJSON to reflect the current state of this object.\n     * Adds any changed hash values to the set of pending changes.\n     * @private\n     */\n    _refreshCache: function() {\n      var self = this;\n      if (self._refreshingCache) {\n        return;\n      }\n      self._refreshingCache = true;\n      AV._objectEach(this.attributes, function(value, key) {\n        if (value instanceof AV.Object) {\n          value._refreshCache();\n        } else if (_.isObject(value)) {\n          if (self._resetCacheForKey(key)) {\n            self.set(key, new AV.Op.Set(value), { silent: true });\n          }\n        }\n      });\n      delete self._refreshingCache;\n    },\n\n    /**\n     * Returns true if this object has been modified since its last\n     * save/refresh.  If an attribute is specified, it returns true only if that\n     * particular attribute has been modified since the last save/refresh.\n     * @param {String} attr An attribute name (optional).\n     * @return {Boolean}\n     */\n    dirty: function(attr) {\n      this._refreshCache();\n\n      var currentChanges = _.last(this._opSetQueue);\n\n      if (attr) {\n        return (currentChanges[attr] ? true : false);\n      }\n      if (!this.id) {\n        return true;\n      }\n      if (_.keys(currentChanges).length > 0) {\n        return true;\n      }\n      return false;\n    },\n\n    /**\n     * Gets a Pointer referencing this Object.\n     * @private\n     */\n    _toPointer: function() {\n      // if (!this.id) {\n      //   throw new Error(\"Can't serialize an unsaved AV.Object\");\n      // }\n      return { __type: \"Pointer\",\n               className: this.className,\n               objectId: this.id };\n    },\n\n    /**\n     * Gets the value of an attribute.\n     * @param {String} attr The string name of an attribute.\n     */\n    get: function(attr) {\n      switch (attr) {\n        case 'objectId':\n          return this.id;\n        case 'createdAt':\n        case 'updatedAt':\n          return this[attr];\n        default:\n          return this.attributes[attr];\n      }\n    },\n\n    /**\n     * Gets a relation on the given class for the attribute.\n     * @param {String} attr The attribute to get the relation for.\n     * @return {AV.Relation}\n     */\n    relation: function(attr) {\n      var value = this.get(attr);\n      if (value) {\n        if (!(value instanceof AV.Relation)) {\n          throw new Error(\"Called relation() on non-relation field \" + attr);\n        }\n        value._ensureParentAndKey(this, attr);\n        return value;\n      } else {\n        return new AV.Relation(this, attr);\n      }\n    },\n\n    /**\n     * Gets the HTML-escaped value of an attribute.\n     */\n    escape: function(attr) {\n      var html = this._escapedAttributes[attr];\n      if (html) {\n        return html;\n      }\n      var val = this.attributes[attr];\n      var escaped;\n      if (utils.isNullOrUndefined(val)) {\n        escaped = '';\n      } else {\n        escaped = _.escape(val.toString());\n      }\n      this._escapedAttributes[attr] = escaped;\n      return escaped;\n    },\n\n    /**\n     * Returns true if the attribute contains a value that is not\n     * null or undefined.\n     * @param {String} attr The string name of the attribute.\n     * @return {Boolean}\n     */\n    has: function(attr) {\n      return !utils.isNullOrUndefined(this.attributes[attr]);\n    },\n\n    /**\n     * Pulls \"special\" fields like objectId, createdAt, etc. out of attrs\n     * and puts them on \"this\" directly.  Removes them from attrs.\n     * @param attrs - A dictionary with the data for this AV.Object.\n     * @private\n     */\n    _mergeMagicFields: function(attrs) {\n      // Check for changes of magic fields.\n      var model = this;\n      var specialFields = [\"objectId\", \"createdAt\", \"updatedAt\"];\n      AV._arrayEach(specialFields, function(attr) {\n        if (attrs[attr]) {\n          if (attr === \"objectId\") {\n            model.id = attrs[attr];\n          } else if ((attr === \"createdAt\" || attr === \"updatedAt\") &&\n                     !_.isDate(attrs[attr])) {\n            model[attr] = AV._parseDate(attrs[attr]);\n          } else { \n            model[attr] = attrs[attr]; \n          }\n          delete attrs[attr];\n        }\n      });\n      return attrs;\n    },\n\n    /**\n     * Returns the json to be sent to the server.\n     * @private\n     */\n    _startSave: function() {\n      this._opSetQueue.push({});\n    },\n\n    /**\n     * Called when a save fails because of an error. Any changes that were part\n     * of the save need to be merged with changes made after the save. This\n     * might throw an exception is you do conflicting operations. For example,\n     * if you do:\n     *   object.set(\"foo\", \"bar\");\n     *   object.set(\"invalid field name\", \"baz\");\n     *   object.save();\n     *   object.increment(\"foo\");\n     * then this will throw when the save fails and the client tries to merge\n     * \"bar\" with the +1.\n     * @private\n     */\n    _cancelSave: function() {\n      var self = this;\n      var failedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      var nextChanges = _.first(this._opSetQueue);\n      AV._objectEach(failedChanges, function(op, key) {\n        var op1 = failedChanges[key];\n        var op2 = nextChanges[key];\n        if (op1 && op2) {\n          nextChanges[key] = op2._mergeWithPrevious(op1);\n        } else if (op1) {\n          nextChanges[key] = op1;\n        }\n      });\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a save completes successfully. This merges the changes that\n     * were saved into the known server data, and overrides it with any data\n     * sent directly from the server.\n     * @private\n     */\n    _finishSave: function(serverData) {\n      // Grab a copy of any object referenced by this object. These instances\n      // may have already been fetched, and we don't want to lose their data.\n      // Note that doing it like this means we will unify separate copies of the\n      // same object, but that's a risk we have to take.\n      var fetchedObjects = {};\n      AV._traverse(this.attributes, function(object) {\n        if (object instanceof AV.Object && object.id && object._hasData) {\n          fetchedObjects[object.id] = object;\n        }\n      });\n\n      var savedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      this._applyOpSet(savedChanges, this._serverData);\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n\n        // Look for any objects that might have become unfetched and fix them\n        // by replacing their values with the previously observed values.\n        var fetched = AV._traverse(self._serverData[key], function(object) {\n          if (object instanceof AV.Object && fetchedObjects[object.id]) {\n            return fetchedObjects[object.id];\n          }\n        });\n        if (fetched) {\n          self._serverData[key] = fetched;\n        }\n      });\n      this._rebuildAllEstimatedData();\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a fetch or login is complete to set the known server data to\n     * the given object.\n     * @private\n     */\n    _finishFetch: function(serverData, hasData) {\n      // Clear out any changes the user might have made previously.\n      this._opSetQueue = [{}];\n\n      // Bring in all the new server data.\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n      });\n\n      // Refresh the attributes.\n      this._rebuildAllEstimatedData();\n\n      // Clear out the cache of mutable containers.\n      this._refreshCache();\n      this._opSetQueue = [{}];\n\n      this._hasData = hasData;\n    },\n\n    /**\n     * Applies the set of AV.Op in opSet to the object target.\n     * @private\n     */\n    _applyOpSet: function(opSet, target) {\n      var self = this;\n      AV._objectEach(opSet, function(change, key) {\n        target[key] = change._estimate(target[key], self, key);\n        if (target[key] === AV.Op._UNSET) {\n          delete target[key];\n        }\n      });\n    },\n\n    /**\n     * Replaces the cached value for key with the current value.\n     * Returns true if the new value is different than the old value.\n     * @private\n     */\n    _resetCacheForKey: function(key) {\n      var value = this.attributes[key];\n      if (_.isObject(value) &&\n          !(value instanceof AV.Object) &&\n          !(value instanceof AV.File)) {\n\n        value = value.toJSON ? value.toJSON() : value;\n        var json = JSON.stringify(value);\n        if (this._hashedJSON[key] !== json) {\n          var wasSet = !! this._hashedJSON[key];\n          this._hashedJSON[key] = json;\n          return wasSet;\n        }\n      }\n      return false;\n    },\n\n    /**\n     * Populates attributes[key] by starting with the last known data from the\n     * server, and applying all of the local changes that have been made to that\n     * key since then.\n     * @private\n     */\n    _rebuildEstimatedDataForKey: function(key) {\n      var self = this;\n      delete this.attributes[key];\n      if (this._serverData[key]) {\n        this.attributes[key] = this._serverData[key];\n      }\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        var op = opSet[key];\n        if (op) {\n          self.attributes[key] = op._estimate(self.attributes[key], self, key);\n          if (self.attributes[key] === AV.Op._UNSET) {\n            delete self.attributes[key];\n          } else {\n            self._resetCacheForKey(key);\n          }\n        }\n      });\n    },\n\n    /**\n     * Populates attributes by starting with the last known data from the\n     * server, and applying all of the local changes that have been made since\n     * then.\n     * @private\n     */\n    _rebuildAllEstimatedData: function() {\n      var self = this;\n\n      var previousAttributes = _.clone(this.attributes);\n\n      this.attributes = _.clone(this._serverData);\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        self._applyOpSet(opSet, self.attributes);\n        AV._objectEach(opSet, function(op, key) {\n          self._resetCacheForKey(key);\n        });\n      });\n\n      // Trigger change events for anything that changed because of the fetch.\n      AV._objectEach(previousAttributes, function(oldValue, key) {\n        if (self.attributes[key] !== oldValue) {\n          self.trigger('change:' + key, self, self.attributes[key], {});\n        }\n      });\n      AV._objectEach(this.attributes, function(newValue, key) {\n        if (!_.has(previousAttributes, key)) {\n          self.trigger('change:' + key, self, newValue, {});\n        }\n      });\n    },\n\n    /**\n     * Sets a hash of model attributes on the object, firing\n     * \"change\" unless you choose to silence it.\n     *\n     * 

You can call it with an object containing keys and values, or with one\n * key and value. For example:

\n     *   gameTurn.set({\n     *     player: player1,\n     *     diceRoll: 2\n     *   }, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"currentPlayer\", player2, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"finished\", true);

\n *\n * @param {String} key The key to set.\n * @param {Any} value The value to give it.\n * @param {Object} [options]\n * @param {Boolean} [options.silent]\n * @return {AV.Object} self if succeeded, throws if the value is not valid.\n * @see AV.Object#validate\n */\n set: function(key, value, options) {\n var attrs;\n if (_.isObject(key) || utils.isNullOrUndefined(key)) {\n attrs = _.mapObject(key, function(v, k) {\n checkReservedKey(k);\n return AV._decode(v, k);\n });\n options = value;\n } else {\n attrs = {};\n checkReservedKey(key);\n attrs[key] = AV._decode(value, key);\n }\n\n // Extract attributes and options.\n options = options || {};\n if (!attrs) {\n return this;\n }\n if (attrs instanceof AV.Object) {\n attrs = attrs.attributes;\n }\n\n // If the unset option is used, every attribute should be a Unset.\n if (options.unset) {\n AV._objectEach(attrs, function(unused_value, key) {\n attrs[key] = new AV.Op.Unset();\n });\n }\n\n // Apply all the attributes to get the estimated values.\n var dataToValidate = _.clone(attrs);\n var self = this;\n AV._objectEach(dataToValidate, function(value, key) {\n if (value instanceof AV.Op) {\n dataToValidate[key] = value._estimate(self.attributes[key],\n self, key);\n if (dataToValidate[key] === AV.Op._UNSET) {\n delete dataToValidate[key];\n }\n }\n });\n\n // Run validation.\n this._validate(attrs, options);\n\n options.changes = {};\n var escaped = this._escapedAttributes;\n var prev = this._previousAttributes || {};\n\n // Update attributes.\n AV._arrayEach(_.keys(attrs), function(attr) {\n var val = attrs[attr];\n\n // If this is a relation object we need to set the parent correctly,\n // since the location where it was parsed does not have access to\n // this object.\n if (val instanceof AV.Relation) {\n val.parent = self;\n }\n\n if (!(val instanceof AV.Op)) {\n val = new AV.Op.Set(val);\n }\n\n // See if this change will actually have any effect.\n var isRealChange = true;\n if (val instanceof AV.Op.Set &&\n _.isEqual(self.attributes[attr], val.value)) {\n isRealChange = false;\n }\n\n if (isRealChange) {\n delete escaped[attr];\n if (options.silent) {\n self._silent[attr] = true;\n } else {\n options.changes[attr] = true;\n }\n }\n\n var currentChanges = _.last(self._opSetQueue);\n currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]);\n self._rebuildEstimatedDataForKey(attr);\n\n if (isRealChange) {\n self.changed[attr] = self.attributes[attr];\n if (!options.silent) {\n self._pending[attr] = true;\n }\n } else {\n delete self.changed[attr];\n delete self._pending[attr];\n }\n });\n\n if (!options.silent) {\n this.change(options);\n }\n return this;\n },\n\n /**\n * Remove an attribute from the model, firing \"change\" unless\n * you choose to silence it. This is a noop if the attribute doesn't\n * exist.\n */\n unset: function(attr, options) {\n options = options || {};\n options.unset = true;\n return this.set(attr, null, options);\n },\n\n /**\n * Atomically increments the value of the given attribute the next time the\n * object is saved. If no amount is specified, 1 is used by default.\n *\n * @param attr {String} The key.\n * @param amount {Number} The amount to increment by.\n */\n increment: function(attr, amount) {\n if (_.isUndefined(amount) || _.isNull(amount)) {\n amount = 1;\n }\n return this.set(attr, new AV.Op.Increment(amount));\n },\n\n /**\n * Atomically add an object to the end of the array associated with a given\n * key.\n * @param attr {String} The key.\n * @param item {} The item to add.\n */\n add: function(attr, item) {\n return this.set(attr, new AV.Op.Add(utils.ensureArray(item)));\n },\n\n /**\n * Atomically add an object to the array associated with a given key, only\n * if it is not already present in the array. The position of the insert is\n * not guaranteed.\n *\n * @param attr {String} The key.\n * @param item {} The object to add.\n */\n addUnique: function(attr, item) {\n return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item)));\n },\n\n /**\n * Atomically remove all instances of an object from the array associated\n * with a given key.\n *\n * @param attr {String} The key.\n * @param item {} The object to remove.\n */\n remove: function(attr, item) {\n return this.set(attr, new AV.Op.Remove(utils.ensureArray(item)));\n },\n\n /**\n * Returns an instance of a subclass of AV.Op describing what kind of\n * modification has been performed on this field since the last time it was\n * saved. For example, after calling object.increment(\"x\"), calling\n * object.op(\"x\") would return an instance of AV.Op.Increment.\n *\n * @param attr {String} The key.\n * @returns {AV.Op} The operation, or undefined if none.\n */\n op: function(attr) {\n return _.last(this._opSetQueue)[attr];\n },\n\n /**\n * Clear all attributes on the model, firing \"change\" unless\n * you choose to silence it.\n */\n clear: function(options) {\n options = options || {};\n options.unset = true;\n var keysToClear = _.extend(this.attributes, this._operations);\n return this.set(keysToClear, options);\n },\n\n /**\n * Returns a JSON-encoded set of operations to be sent with the next save\n * request.\n * @private\n */\n _getSaveJSON: function() {\n var json = _.clone(_.first(this._opSetQueue));\n AV._objectEach(json, function(op, key) {\n json[key] = op.toJSON();\n });\n return json;\n },\n\n /**\n * Returns true if this object can be serialized for saving.\n * @private\n */\n _canBeSerialized: function() {\n return AV.Object._canBeSerializedAsValue(this.attributes);\n },\n\n /**\n * Fetch the model from the server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * triggering a \"change\" event.\n * @param {Object} fetchOptions Optional options to set 'keys' and\n * 'include' option.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(fetchOptions = {}, options) {\n if (_.isArray(fetchOptions.keys)) {\n fetchOptions.keys = fetchOptions.keys.join(',');\n }\n if (_.isArray(fetchOptions.include)) {\n fetchOptions.include = fetchOptions.include.join(',');\n }\n\n var self = this;\n var request = AVRequest('classes', this.className, this.id, 'GET',\n fetchOptions, options);\n return request.then(function(response) {\n self._finishFetch(self.parse(response), true);\n return self;\n });\n },\n\n /**\n * Set a hash of model attributes, and save the model to the server.\n * updatedAt will be updated when the request returns.\n * You can either call it as:
\n     *   object.save();
\n * or
\n     *   object.save(null, options);
\n * or
\n     *   object.save(attrs, options);
\n * or
\n     *   object.save(key, value, options);
\n *\n * For example,
\n     *   gameTurn.save({\n     *     player: \"Jake Cutter\",\n     *     diceRoll: 2\n     *   }).then(function(gameTurnAgain) {\n     *     // The save was successful.\n     *   }, function(error) {\n     *     // The save failed.  Error is an instance of AVError.\n     *   });
\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded\n * @param {AV.Query} options.query Save object only when it matches the query\n * @return {AV.Promise} A promise that is fulfilled when the save\n * completes.\n * @see AVError\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n\n options = _.clone(options) || {};\n if (options.wait) {\n current = _.clone(this.attributes);\n }\n\n var setOptions = _.clone(options) || {};\n if (setOptions.wait) {\n setOptions.silent = true;\n }\n if (attrs) {\n this.set(attrs, setOptions);\n }\n\n var model = this;\n\n // If there is any unsaved child, save it first.\n model._refreshCache();\n\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(model.attributes,\n unsavedChildren,\n unsavedFiles);\n if (unsavedChildren.length + unsavedFiles.length > 0) {\n return AV.Object._deepSaveAsync(this.attributes, model, options).then(function() {\n return model.save(null, options);\n });\n }\n\n this._startSave();\n this._saving = (this._saving || 0) + 1;\n\n this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve();\n this._allPreviousSaves = this._allPreviousSaves.catch(e => {}).then(function() {\n var method = model.id ? 'PUT' : 'POST';\n\n var json = model._getSaveJSON();\n\n if(model._fetchWhenSave){\n //Sepcial-case fetchWhenSave when updating object.\n json._fetchWhenSave = true;\n }\n\n if (options.fetchWhenSave) {\n json._fetchWhenSave = true;\n }\n if (options.query) {\n var queryJSON;\n if (typeof options.query.toJSON === 'function') {\n queryJSON = options.query.toJSON();\n if (queryJSON) {\n json._where = queryJSON.where;\n }\n }\n if (!json._where) {\n var error = new Error('options.query is not an AV.Query');\n throw error;\n }\n }\n\n _.extend(json, model._flags);\n\n var route = \"classes\";\n var className = model.className;\n if (model.className === \"_User\" && !model.id) {\n // Special-case user sign-up.\n route = \"users\";\n className = null;\n }\n //hook makeRequest in options.\n var makeRequest = options._makeRequest || AVRequest;\n var request = makeRequest(route, className, model.id, method, json, options);\n\n request = request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n if (options.wait) {\n serverAttrs = _.extend(attrs || {}, serverAttrs);\n }\n model._finishSave(serverAttrs);\n if (options.wait) {\n model.set(current, setOptions);\n }\n return model;\n\n }, function(error) {\n model._cancelSave();\n throw error;\n });\n\n return request;\n });\n return this._allPreviousSaves;\n },\n\n /**\n * Destroy this model on the server if it was already persisted.\n * Optimistically removes the model from its collection, if it has one.\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} [options.wait] wait for the server to respond\n * before removal.\n *\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n options = options || {};\n var model = this;\n\n var triggerDestroy = function() {\n model.trigger('destroy', model, model.collection, options);\n };\n\n if (!this.id) {\n return triggerDestroy();\n }\n\n if (!options.wait) {\n triggerDestroy();\n }\n\n var request =\n AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options);\n return request.then(function() {\n if (options.wait) {\n triggerDestroy();\n }\n return model;\n });\n },\n\n /**\n * Converts a response into the hash of attributes to be set on the model.\n * @ignore\n */\n parse: function(resp) {\n var output = _.clone(resp);\n _([\"createdAt\", \"updatedAt\"]).each(function(key) {\n if (output[key]) {\n output[key] = AV._parseDate(output[key]);\n }\n });\n if (!output.updatedAt) {\n output.updatedAt = output.createdAt;\n }\n return output;\n },\n\n /**\n * Creates a new model with identical attributes to this one.\n * @return {AV.Object}\n */\n clone: function() {\n return new this.constructor(this.attributes);\n },\n\n /**\n * Returns true if this object has never been saved to AV.\n * @return {Boolean}\n */\n isNew: function() {\n return !this.id;\n },\n\n /**\n * Call this method to manually fire a `\"change\"` event for this model and\n * a `\"change:attribute\"` event for each changed attribute.\n * Calling this will cause all objects observing the model to update.\n */\n change: function(options) {\n options = options || {};\n var changing = this._changing;\n this._changing = true;\n\n // Silent changes become pending changes.\n var self = this;\n AV._objectEach(this._silent, function(attr) {\n self._pending[attr] = true;\n });\n\n // Silent changes are triggered.\n var changes = _.extend({}, options.changes, this._silent);\n this._silent = {};\n AV._objectEach(changes, function(unused_value, attr) {\n self.trigger('change:' + attr, self, self.get(attr), options);\n });\n if (changing) {\n return this;\n }\n\n // This is to get around lint not letting us make a function in a loop.\n var deleteChanged = function(value, attr) {\n if (!self._pending[attr] && !self._silent[attr]) {\n delete self.changed[attr];\n }\n };\n\n // Continue firing `\"change\"` events while there are pending changes.\n while (!_.isEmpty(this._pending)) {\n this._pending = {};\n this.trigger('change', this, options);\n // Pending and silent changes still remain.\n AV._objectEach(this.changed, deleteChanged);\n self._previousAttributes = _.clone(this.attributes);\n }\n\n this._changing = false;\n return this;\n },\n\n /**\n * Determine if the model has changed since the last \"change\"\n * event. If you specify an attribute name, determine if that attribute\n * has changed.\n * @param {String} attr Optional attribute name\n * @return {Boolean}\n */\n hasChanged: function(attr) {\n if (!arguments.length) {\n return !_.isEmpty(this.changed);\n }\n return this.changed && _.has(this.changed, attr);\n },\n\n /**\n * Returns an object containing all the attributes that have changed, or\n * false if there are no changed attributes. Useful for determining what\n * parts of a view need to be updated and/or what attributes need to be\n * persisted to the server. Unset attributes will be set to undefined.\n * You can also pass an attributes object to diff against the model,\n * determining if there *would be* a change.\n */\n changedAttributes: function(diff) {\n if (!diff) {\n return this.hasChanged() ? _.clone(this.changed) : false;\n }\n var changed = {};\n var old = this._previousAttributes;\n AV._objectEach(diff, function(diffVal, attr) {\n if (!_.isEqual(old[attr], diffVal)) {\n changed[attr] = diffVal;\n }\n });\n return changed;\n },\n\n /**\n * Gets the previous value of an attribute, recorded at the time the last\n * \"change\" event was fired.\n * @param {String} attr Name of the attribute to get.\n */\n previous: function(attr) {\n if (!arguments.length || !this._previousAttributes) {\n return null;\n }\n return this._previousAttributes[attr];\n },\n\n /**\n * Gets all of the attributes of the model at the time of the previous\n * \"change\" event.\n * @return {Object}\n */\n previousAttributes: function() {\n return _.clone(this._previousAttributes);\n },\n\n /**\n * Checks if the model is currently in a valid state. It's only possible to\n * get into an *invalid* state if you're using silent changes.\n * @return {Boolean}\n */\n isValid: function() {\n try {\n this.validate(this.attributes);\n } catch (error) {\n return false;\n }\n return true;\n },\n\n /**\n * You should not call this function directly unless you subclass\n * AV.Object, in which case you can override this method\n * to provide additional validation on set and\n * save. Your implementation should throw an Error if\n * the attrs is invalid\n *\n * @param {Object} attrs The current data to validate.\n * @see AV.Object#set\n */\n validate: function(attrs) {\n if (_.has(attrs, \"ACL\") && !(attrs.ACL instanceof AV.ACL)) {\n throw new AVError(AVError.OTHER_CAUSE,\n \"ACL must be a AV.ACL.\");\n }\n },\n\n /**\n * Run validation against a set of incoming attributes, returning `true`\n * if all is well. If a specific `error` callback has been passed,\n * call that instead of firing the general `\"error\"` event.\n * @private\n */\n _validate: function(attrs, options) {\n if (options.silent || !this.validate) {\n return;\n }\n attrs = _.extend({}, this.attributes, attrs);\n this.validate(attrs);\n },\n\n /**\n * Returns the ACL for this object.\n * @returns {AV.ACL} An instance of AV.ACL.\n * @see AV.Object#get\n */\n getACL: function() {\n return this.get(\"ACL\");\n },\n\n /**\n * Sets the ACL to be used for this object.\n * @param {AV.ACL} acl An instance of AV.ACL.\n * @param {Object} options Optional Backbone-like options object to be\n * passed in to set.\n * @return {Boolean} Whether the set passed validation.\n * @see AV.Object#set\n */\n setACL: function(acl, options) {\n return this.set(\"ACL\", acl, options);\n },\n\n disableBeforeHook: function() {\n this.ignoreHook('beforeSave');\n this.ignoreHook('beforeUpdate');\n this.ignoreHook('beforeDelete');\n },\n\n disableAfterHook: function() {\n this.ignoreHook('afterSave');\n this.ignoreHook('afterUpdate');\n this.ignoreHook('afterDelete');\n },\n\n ignoreHook: function(hookName) {\n if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) {\n console.trace('Unsupported hookName: ' + hookName);\n }\n\n if (!AV.hookKey) {\n console.trace('ignoreHook required hookKey');\n }\n\n if (!this._flags.__ignore_hooks) {\n this._flags.__ignore_hooks = [];\n }\n\n this._flags.__ignore_hooks.push(hookName);\n }\n });\n\n /**\n * Creates an instance of a subclass of AV.Object for the give classname\n * and id.\n * @param {String} className The name of the AV class backing this model.\n * @param {String} id The object id of this model.\n * @return {AV.Object} A new subclass instance of AV.Object.\n */\n AV.Object.createWithoutData = function(className, id, hasData){\n var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n result.id = id;\n result._hasData = hasData;\n return result;\n };\n /**\n * Delete objects in batch.\n * @param {AV.Object[]} objects The AV.Object array to be deleted.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n AV.Object.destroyAll = function(objects, options = {}){\n if (!objects || objects.length === 0){\n\t\t return AV.Promise.resolve();\n }\n const objectsByClassNameAndFlags = _.groupBy(objects, object => JSON.stringify({\n className: object.className,\n flags: object._flags\n }));\n const body = {\n requests: _.map(objectsByClassNameAndFlags, objects => {\n const ids = _.map(objects, 'id').join(',');\n return {\n method: 'DELETE',\n path: `/1.1/classes/${objects[0].className}/${ids}`,\n body: objects[0]._flags\n }\n })\n };\n return AVRequest('batch', null, null, 'POST', body, options);\n };\n\n /**\n * Returns the appropriate subclass for making new instances of the given\n * className string.\n * @private\n */\n AV.Object._getSubclass = function(className) {\n if (!_.isString(className)) {\n throw new Error('AV.Object._getSubclass requires a string argument.');\n }\n var ObjectClass = AV.Object._classMap[className];\n if (!ObjectClass) {\n ObjectClass = AV.Object.extend(className);\n AV.Object._classMap[className] = ObjectClass;\n }\n return ObjectClass;\n };\n\n /**\n * Creates an instance of a subclass of AV.Object for the given classname.\n * @private\n */\n AV.Object._create = function(className, attributes, options, noDefaultACL) {\n var ObjectClass = AV.Object._getSubclass(className);\n return new ObjectClass(attributes, options, noDefaultACL);\n };\n\n // Set up a map of className to class so that we can create new instances of\n // AV Objects from JSON automatically.\n AV.Object._classMap = {};\n\n AV.Object._extend = AV._extend;\n\n /**\n * Creates a new model with defined attributes,\n * It's the same with\n *
\n   *   new AV.Object(attributes, options);\n   *  
\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @return {AV.Object}\n * @since v0.4.4\n * @see AV.Object\n * @see AV.Object.extend\n */\n AV.Object['new'] = function(attributes, options){\n return new AV.Object(attributes, options);\n };\n\n /**\n * Creates a new subclass of AV.Object for the given AV class name.\n *\n *

Every extension of a AV class will inherit from the most recent\n * previous extension of that class. When a AV.Object is automatically\n * created by parsing JSON, it will use the most recent extension of that\n * class.

\n *\n *

You should call either:

\n   *     var MyClass = AV.Object.extend(\"MyClass\", {\n   *         Instance properties\n   *     }, {\n   *         Class properties\n   *     });
\n * or, for Backbone compatibility:
\n   *     var MyClass = AV.Object.extend({\n   *         className: \"MyClass\",\n   *         Other instance properties\n   *     }, {\n   *         Class properties\n   *     });

\n *\n * @param {String} className The name of the AV class backing this model.\n * @param {Object} protoProps Instance properties to add to instances of the\n * class returned from this method.\n * @param {Object} classProps Class properties to add the class returned from\n * this method.\n * @return {Class} A new subclass of AV.Object.\n */\n AV.Object.extend = function(className, protoProps, classProps) {\n // Handle the case with only two args.\n if (!_.isString(className)) {\n if (className && _.has(className, \"className\")) {\n return AV.Object.extend(className.className, className, protoProps);\n } else {\n throw new Error(\n \"AV.Object.extend's first argument should be the className.\");\n }\n }\n\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n className = \"_User\";\n }\n\n var NewClassObject = null;\n if (_.has(AV.Object._classMap, className)) {\n var OldClassObject = AV.Object._classMap[className];\n // This new subclass has been told to extend both from \"this\" and from\n // OldClassObject. This is multiple inheritance, which isn't supported.\n // For now, let's just pick one.\n if (protoProps || classProps) {\n NewClassObject = OldClassObject._extend(protoProps, classProps);\n } else {\n return OldClassObject;\n }\n } else {\n protoProps = protoProps || {};\n protoProps._className = className;\n NewClassObject = this._extend(protoProps, classProps);\n }\n // Extending a subclass should reuse the classname automatically.\n NewClassObject.extend = function(arg0) {\n if (_.isString(arg0) || (arg0 && _.has(arg0, \"className\"))) {\n return AV.Object.extend.apply(NewClassObject, arguments);\n }\n var newArguments = [className].concat(_.toArray(arguments));\n return AV.Object.extend.apply(NewClassObject, newArguments);\n };\n NewClassObject['new'] = function(attributes, options){\n return new NewClassObject(attributes, options);\n };\n AV.Object._classMap[className] = NewClassObject;\n return NewClassObject;\n };\n\n // ES6 class syntax support\n Object.defineProperty(AV.Object.prototype, 'className', {\n get: function(){\n const className = this._className || this.constructor._LCClassName || this.constructor.name;\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n return \"_User\";\n }\n return className;\n },\n });\n\n /**\n * Register a class.\n * If a subclass of AV.Object is defined with your own implement\n * rather then AV.Object.extend, the subclass must be registered.\n * @param {Function} klass A subclass of AV.Object\n * @param {String} [name] Specify the name of the class. Useful when the class might be uglified.\n * @example\n * class Person extend AV.Object {}\n * AV.Object.register(Person);\n */\n AV.Object.register = (klass, name) => {\n if (!(klass.prototype instanceof AV.Object)) {\n throw new Error('registered class is not a subclass of AV.Object');\n }\n const className = name || klass.name;\n if (!className.length) {\n throw new Error('registered class must be named');\n }\n if (name) {\n klass._LCClassName = name;\n }\n AV.Object._classMap[className] = klass;\n };\n\n AV.Object._findUnsavedChildren = function(object, children, files) {\n AV._traverse(object, function(object) {\n if (object instanceof AV.Object) {\n object._refreshCache();\n if (object.dirty()) {\n children.push(object);\n }\n return;\n }\n\n if (object instanceof AV.File) {\n if (!object.url() && !object.id) {\n files.push(object);\n }\n return;\n }\n });\n };\n\n AV.Object._canBeSerializedAsValue = function(object) {\n var canBeSerializedAsValue = true;\n\n if (object instanceof AV.Object || object instanceof AV.File) {\n canBeSerializedAsValue = !!object.id;\n\n } else if (_.isArray(object)) {\n AV._arrayEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n\n } else if (_.isObject(object)) {\n AV._objectEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n }\n\n return canBeSerializedAsValue;\n };\n\n AV.Object._deepSaveAsync = function(object, model, options) {\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles);\n if(model) {\n unsavedChildren = _.filter(unsavedChildren, function(object) {\n return object != model;\n });\n }\n\n var promise = AV.Promise.resolve();\n _.each(unsavedFiles, function(file) {\n promise = promise.then(function() {\n return file.save();\n });\n });\n\n var objects = _.uniq(unsavedChildren);\n var remaining = _.uniq(objects);\n\n return promise.then(function() {\n return AV.Promise._continueWhile(function() {\n return remaining.length > 0;\n }, function() {\n\n // Gather up all the objects that can be saved in this batch.\n var batch = [];\n var newRemaining = [];\n AV._arrayEach(remaining, function(object) {\n // Limit batches to 20 objects.\n if (batch.length > 20) {\n newRemaining.push(object);\n return;\n }\n\n if (object._canBeSerialized()) {\n batch.push(object);\n } else {\n newRemaining.push(object);\n }\n });\n remaining = newRemaining;\n\n // If we can't save any objects, there must be a circular reference.\n if (batch.length === 0) {\n return AV.Promise.reject(\n new AVError(AVError.OTHER_CAUSE,\n \"Tried to save a batch with a cycle.\"));\n }\n\n // Reserve a spot in every object's save queue.\n var readyToStart = AV.Promise.resolve(_.map(batch, function(object) {\n return object._allPreviousSaves || AV.Promise.resolve();\n }));\n\n // Save a single batch, whether previous saves succeeded or failed.\n const bathSavePromise = readyToStart.then(() =>\n AVRequest(\"batch\", null, null, \"POST\", {\n requests: _.map(batch, function(object) {\n var json = object._getSaveJSON();\n _.extend(json, object._flags);\n var method = \"POST\";\n\n var path = \"/1.1/classes/\" + object.className;\n if (object.id) {\n path = path + \"/\" + object.id;\n method = \"PUT\";\n }\n\n object._startSave();\n\n return {\n method: method,\n path: path,\n body: json\n };\n })\n\n }, options).then(function(response) {\n var error;\n AV._arrayEach(batch, function(object, i) {\n if (response[i].success) {\n object._finishSave(\n object.parse(response[i].success));\n } else {\n error = error || response[i].error;\n object._cancelSave();\n }\n });\n if (error) {\n return AV.Promise.reject(\n new AVError(error.code, error.error));\n }\n\n })\n );\n AV._arrayEach(batch, function(object) {\n object._allPreviousSaves = bathSavePromise;\n });\n return bathSavePromise;\n });\n }).then(function() {\n return object;\n });\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/object.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n\n /**\n * @private\n * @class\n * A AV.Op is an atomic operation that can be applied to a field in a\n * AV.Object. For example, calling object.set(\"foo\", \"bar\")\n * is an example of a AV.Op.Set. Calling object.unset(\"foo\")\n * is a AV.Op.Unset. These operations are stored in a AV.Object and\n * sent to the server as part of object.save() operations.\n * Instances of AV.Op should be immutable.\n *\n * You should not create subclasses of AV.Op or instantiate AV.Op\n * directly.\n */\n AV.Op = function() {\n this._initialize.apply(this, arguments);\n };\n\n AV.Op.prototype = {\n _initialize: function() {}\n };\n\n _.extend(AV.Op, {\n /**\n * To create a new Op, call AV.Op._extend();\n * @private\n */\n _extend: AV._extend,\n\n // A map of __op string to decoder function.\n _opDecoderMap: {},\n\n /**\n * Registers a function to convert a json object with an __op field into an\n * instance of a subclass of AV.Op.\n * @private\n */\n _registerDecoder: function(opName, decoder) {\n AV.Op._opDecoderMap[opName] = decoder;\n },\n\n /**\n * Converts a json object into an instance of a subclass of AV.Op.\n * @private\n */\n _decode: function(json) {\n var decoder = AV.Op._opDecoderMap[json.__op];\n if (decoder) {\n return decoder(json);\n } else {\n return undefined;\n }\n }\n });\n\n /*\n * Add a handler for Batch ops.\n */\n AV.Op._registerDecoder(\"Batch\", function(json) {\n var op = null;\n AV._arrayEach(json.ops, function(nextOp) {\n nextOp = AV.Op._decode(nextOp);\n op = nextOp._mergeWithPrevious(op);\n });\n return op;\n });\n\n /**\n * @private\n * @class\n * A Set operation indicates that either the field was changed using\n * AV.Object.set, or it is a mutable container that was detected as being\n * changed.\n */\n AV.Op.Set = AV.Op._extend(/** @lends AV.Op.Set.prototype */ {\n _initialize: function(value) {\n this._value = value;\n },\n\n /**\n * Returns the new value of this field after the set.\n */\n value: function() {\n return this._value;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return AV._encode(this.value());\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return this.value();\n }\n });\n\n /**\n * A sentinel value that is returned by AV.Op.Unset._estimate to\n * indicate the field should be deleted. Basically, if you find _UNSET as a\n * value in your object, you should remove that key.\n */\n AV.Op._UNSET = {};\n\n /**\n * @private\n * @class\n * An Unset operation indicates that this field has been deleted from the\n * object.\n */\n AV.Op.Unset = AV.Op._extend(/** @lends AV.Op.Unset.prototype */ {\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Delete\" };\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return AV.Op._UNSET;\n }\n });\n\n AV.Op._registerDecoder(\"Delete\", function(json) {\n return new AV.Op.Unset();\n });\n\n /**\n * @private\n * @class\n * An Increment is an atomic operation where the numeric value for the field\n * will be increased by a given amount.\n */\n AV.Op.Increment = AV.Op._extend(\n /** @lends AV.Op.Increment.prototype */ {\n\n _initialize: function(amount) {\n this._amount = amount;\n },\n\n /**\n * Returns the amount to increment by.\n * @return {Number} the amount to increment by.\n */\n amount: function() {\n return this._amount;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Increment\", amount: this._amount };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.amount());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(previous.value() + this.amount());\n } else if (previous instanceof AV.Op.Increment) {\n return new AV.Op.Increment(this.amount() + previous.amount());\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return this.amount();\n }\n return oldValue + this.amount();\n }\n });\n\n AV.Op._registerDecoder(\"Increment\", function(json) {\n return new AV.Op.Increment(json.amount);\n });\n\n /**\n * @private\n * @class\n * Add is an atomic operation where the given objects will be appended to the\n * array that is stored in this field.\n */\n AV.Op.Add = AV.Op._extend(/** @lends AV.Op.Add.prototype */ {\n _initialize: function(objects) {\n this._objects = objects;\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Add\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Add) {\n return new AV.Op.Add(previous.objects().concat(this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n return oldValue.concat(this.objects());\n }\n }\n });\n\n AV.Op._registerDecoder(\"Add\", function(json) {\n return new AV.Op.Add(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * AddUnique is an atomic operation where the given items will be appended to\n * the array that is stored in this field only if they were not already\n * present in the array.\n */\n AV.Op.AddUnique = AV.Op._extend(\n /** @lends AV.Op.AddUnique.prototype */ {\n\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"AddUnique\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.AddUnique) {\n return new AV.Op.AddUnique(this._estimate(previous.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n // We can't just take the _.uniq(_.union(...)) of oldValue and\n // this.objects, because the uniqueness may not apply to oldValue\n // (especially if the oldValue was set via .set())\n var newValue = _.clone(oldValue);\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n var matchingObj = _.find(newValue, function(anObj) {\n return (anObj instanceof AV.Object) && (anObj.id === obj.id);\n });\n if (!matchingObj) {\n newValue.push(obj);\n } else {\n var index = _.indexOf(newValue, matchingObj);\n newValue[index] = obj;\n }\n } else if (!_.contains(newValue, obj)) {\n newValue.push(obj);\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddUnique\", function(json) {\n return new AV.Op.AddUnique(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * Remove is an atomic operation where the given objects will be removed from\n * the array that is stored in this field.\n */\n AV.Op.Remove = AV.Op._extend(/** @lends AV.Op.Remove.prototype */ {\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be removed from the array.\n * @return {Array} The objects to be removed from the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Remove\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return previous;\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Remove) {\n return new AV.Op.Remove(_.union(previous.objects(), this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return [];\n } else {\n var newValue = _.difference(oldValue, this.objects());\n // If there are saved AV Objects being removed, also remove them.\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n newValue = _.reject(newValue, function(other) {\n return (other instanceof AV.Object) && (other.id === obj.id);\n });\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"Remove\", function(json) {\n return new AV.Op.Remove(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * A Relation operation indicates that the field is an instance of\n * AV.Relation, and objects are being added to, or removed from, that\n * relation.\n */\n AV.Op.Relation = AV.Op._extend(\n /** @lends AV.Op.Relation.prototype */ {\n\n _initialize: function(adds, removes) {\n this._targetClassName = null;\n\n var self = this;\n\n var pointerToId = function(object) {\n if (object instanceof AV.Object) {\n if (!object.id) {\n throw new Error('You can\\'t add an unsaved AV.Object to a relation.');\n }\n if (!self._targetClassName) {\n self._targetClassName = object.className;\n }\n if (self._targetClassName !== object.className) {\n throw new Error(\"Tried to create a AV.Relation with 2 different types: \" +\n self._targetClassName + \" and \" + object.className + \".\");\n }\n return object.id;\n }\n return object;\n };\n\n this.relationsToAdd = _.uniq(_.map(adds, pointerToId));\n this.relationsToRemove = _.uniq(_.map(removes, pointerToId));\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being added to the\n * relation.\n * @return {Array}\n */\n added: function() {\n var self = this;\n return _.map(this.relationsToAdd, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being removed from\n * the relation.\n * @return {Array}\n */\n removed: function() {\n var self = this;\n return _.map(this.relationsToRemove, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n var adds = null;\n var removes = null;\n var self = this;\n var idToPointer = function(id) {\n return { __type: 'Pointer',\n className: self._targetClassName,\n objectId: id };\n };\n var pointers = null;\n if (this.relationsToAdd.length > 0) {\n pointers = _.map(this.relationsToAdd, idToPointer);\n adds = { \"__op\": \"AddRelation\", \"objects\": pointers };\n }\n\n if (this.relationsToRemove.length > 0) {\n pointers = _.map(this.relationsToRemove, idToPointer);\n removes = { \"__op\": \"RemoveRelation\", \"objects\": pointers };\n }\n\n if (adds && removes) {\n return { \"__op\": \"Batch\", \"ops\": [adds, removes]};\n }\n\n return adds || removes || {};\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n throw new Error('You can\\'t modify a relation after deleting it.');\n } else if (previous instanceof AV.Op.Relation) {\n if (previous._targetClassName &&\n previous._targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be of class \" + previous._targetClassName +\n \", but \" + this._targetClassName + \" was passed in.\");\n }\n var newAdd = _.union(_.difference(previous.relationsToAdd,\n this.relationsToRemove),\n this.relationsToAdd);\n var newRemove = _.union(_.difference(previous.relationsToRemove,\n this.relationsToAdd),\n this.relationsToRemove);\n\n var newRelation = new AV.Op.Relation(newAdd, newRemove);\n newRelation._targetClassName = this._targetClassName;\n return newRelation;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue, object, key) {\n if (!oldValue) {\n var relation = new AV.Relation(object, key);\n relation.targetClassName = this._targetClassName;\n } else if (oldValue instanceof AV.Relation) {\n if (this._targetClassName) {\n if (oldValue.targetClassName) {\n if (oldValue.targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be a \" + oldValue.targetClassName +\n \", but a \" + this._targetClassName + \" was passed in.\");\n }\n } else {\n oldValue.targetClassName = this._targetClassName;\n }\n }\n return oldValue;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddRelation\", function(json) {\n return new AV.Op.Relation(AV._decode(json.objects), []);\n });\n AV.Op._registerDecoder(\"RemoveRelation\", function(json) {\n return new AV.Op.Relation([], AV._decode(json.objects));\n });\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/op.js","const AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n AV.Installation = AV.Object.extend(\"_Installation\");\n\n /**\n * @namespace\n */\n AV.Push = AV.Push || {};\n\n /**\n * Sends a push notification.\n * @param {Object} data The data of the push notification.\n * @param {String[]} [data.channels] An Array of channels to push to.\n * @param {Date} [data.push_time] A Date object for when to send the push.\n * @param {Date} [data.expiration_time] A Date object for when to expire\n * the push.\n * @param {Number} [data.expiration_interval] The seconds from now to expire the push.\n * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {Date} data.data The data to send as part of the push\n * @param {AuthOptions} [options]\n * @return {Promise}\n */\n AV.Push.send = function(data, options) {\n if (data.where) {\n data.where = data.where.toJSON().where;\n }\n\n if(data.where && data.cql){\n throw new Error(\"Both where and cql can't be set\");\n }\n\n if (data.push_time) {\n data.push_time = data.push_time.toJSON();\n }\n\n if (data.expiration_time) {\n data.expiration_time = data.expiration_time.toJSON();\n }\n\n if (data.expiration_time && data.expiration_time_interval) {\n throw new Error(\"Both expiration_time and expiration_time_interval can't be set\");\n }\n\n var request = AVRequest('push', null, null, 'POST', data, options);\n return request;\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/push.js","const _ = require('underscore');\nconst debug = require('debug')('leancloud:query');\nconst Promise = require('./promise');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst { ensureArray } = require('./utils');\n\nconst requires = (value, message) => {\n if (value === undefined) {\n throw new Error(message);\n }\n};\n\n// AV.Query is a way to create a list of AV.Objects.\nmodule.exports = function(AV) {\n /**\n * Creates a new AV.Query for the given AV.Object subclass.\n * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string.\n * @class\n *\n *

AV.Query defines a query that is used to fetch AV.Objects. The\n * most common use case is finding all objects that match a query through the\n * find method. For example, this sample code fetches all objects\n * of class MyClass. It calls a different function depending on\n * whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.find().then(function(results) {\n   *   // results is an array of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to retrieve a single object whose id is\n * known, through the get method. For example, this sample code fetches an\n * object of class MyClass and id myId. It calls a\n * different function depending on whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.get(myId).then(function(object) {\n   *   // object is an instance of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to count the number of objects that match\n * the query without retrieving all of those objects. For example, this\n * sample code counts the number of objects of the class MyClass\n *

\n   * var query = new AV.Query(MyClass);\n   * query.count().then(function(number) {\n   *   // There are number instances of MyClass.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n */\n AV.Query = function(objectClass) {\n if (_.isString(objectClass)) {\n objectClass = AV.Object._getSubclass(objectClass);\n }\n\n this.objectClass = objectClass;\n\n this.className = objectClass.prototype.className;\n\n this._where = {};\n this._include = [];\n this._select = [];\n this._limit = -1; // negative limit means, do not send a limit\n this._skip = 0;\n this._extraOptions = {};\n };\n\n /**\n * Constructs a AV.Query that is the OR of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.or(query1, query2, query3);
\n *\n * will create a compoundQuery that is an or of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to OR.\n * @return {AV.Query} The query that is the OR of the passed in queries.\n */\n AV.Query.or = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._orQuery(queries);\n return query;\n };\n\n /**\n * Constructs a AV.Query that is the AND of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.and(query1, query2, query3);
\n *\n * will create a compoundQuery that is an 'and' of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to AND.\n * @return {AV.Query} The query that is the AND of the passed in queries.\n */\n AV.Query.and = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._andQuery(queries);\n return query;\n };\n\n /**\n * Retrieves a list of AVObjects that satisfy the CQL.\n * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n *\n * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n * @param {Array} pvalues An array contains placeholder values.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n AV.Query.doCloudQuery = function(cql, pvalues, options) {\n var params = { cql: cql };\n if(_.isArray(pvalues)){\n params.pvalues = pvalues;\n } else {\n options = pvalues;\n }\n\n var request = AVRequest('cloudQuery', null, null, 'GET', params, options);\n return request.then(function(response) {\n //query to process results.\n var query = new AV.Query(response.className);\n var results = _.map(response.results, function(json) {\n var obj = query._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(query._processResult(json), true);\n }\n return obj;\n });\n return {\n results: results,\n count: response.count,\n className: response.className\n };\n });\n };\n\n AV.Query._extend = AV._extend;\n\n AV.Query.prototype = {\n //hook to iterate result. Added by dennis.\n _processResult: function(obj){\n return obj;\n },\n\n /**\n * Constructs an AV.Object whose id is already known by fetching data from\n * the server.\n *\n * @param {String} objectId The id of the object to be fetched.\n * @param {AuthOptions} options\n * @return {Promise.}\n */\n get: function(objectId, options) {\n if(!objectId) {\n var errorObject = new AVError(AVError.OBJECT_NOT_FOUND,\n \"Object not found.\");\n throw errorObject;\n }\n\n var self = this;\n\n var obj = self._newObject();\n obj.id = objectId;\n\n var queryJSON = self.toJSON();\n var fetchOptions = {};\n\n if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;\n if (queryJSON.include) fetchOptions.include = queryJSON.include;\n\n return obj.fetch(fetchOptions, options);\n },\n\n /**\n * Returns a JSON representation of this query.\n * @return {Object}\n */\n toJSON: function() {\n var params = {\n where: this._where\n };\n\n if (this._include.length > 0) {\n params.include = this._include.join(\",\");\n }\n if (this._select.length > 0) {\n params.keys = this._select.join(\",\");\n }\n if (this._limit >= 0) {\n params.limit = this._limit;\n }\n if (this._skip > 0) {\n params.skip = this._skip;\n }\n if (this._order !== undefined) {\n params.order = this._order;\n }\n\n AV._objectEach(this._extraOptions, function(v, k) {\n params[k] = v;\n });\n\n return params;\n },\n\n _newObject: function(response){\n var obj;\n if (response && response.className) {\n obj = new AV.Object(response.className);\n } else {\n obj = new this.objectClass();\n }\n return obj;\n },\n _createRequest(params = this.toJSON(), options) {\n if (JSON.stringify(params).length > 2000) {\n const body = {\n requests: [{\n method: 'GET',\n path: `/1.1/classes/${this.className}`,\n params,\n }],\n };\n return AVRequest('batch', null, null, 'POST', body, options)\n .then(response => {\n const result = response[0];\n if (result.success) {\n return result.success;\n }\n const error = new Error(result.error.error || 'Unknown batch error');\n error.code = result.error.code;\n throw error;\n });\n }\n return AVRequest('classes', this.className, null, \"GET\", params, options);\n },\n\n _parseResponse(response) {\n return _.map(response.results, (json) => {\n var obj = this._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(this._processResult(json), true);\n }\n return obj;\n });\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find(options) {\n const request = this._createRequest(undefined, options);\n return request.then(this._parseResponse.bind(this));\n },\n\n /**\n * scan a Query. masterKey required.\n *\n * @since 2.1.0\n * @param {object} [options]\n * @param {string} [options.orderedBy] specify the key to sort\n * @param {number} [options.batchSize] specify the batch size for each request\n * @param {AuthOptions} [authOptions]\n * @return {AsyncIterator.}\n * @example const scan = new AV.Query(TestClass).scan({\n * orderedBy: 'objectId',\n * batchSize: 10,\n * }, {\n * useMasterKey: true,\n * });\n * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next()));\n * getTen().then(results => {\n * // results are fisrt 10 instances of TestClass\n * return getTen();\n * }).then(results => {\n * // 11 - 20\n * });\n */\n scan({\n orderedBy,\n batchSize,\n } = {}, authOptions) {\n const condition = this.toJSON();\n debug('scan %O', condition);\n if (condition.order) {\n console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.');\n delete condition.order;\n }\n if (condition.skip) {\n console.warn('The skip option of the query is ignored for Query#scan.');\n delete condition.skip;\n }\n if (condition.limit) {\n console.warn('The limit option of the query is ignored for Query#scan.');\n delete condition.limit;\n }\n if (orderedBy) condition.scan_key = orderedBy;\n if (batchSize) condition.limit = batchSize;\n let promise = Promise.resolve([]);\n let cursor;\n let done = false;\n return {\n next: () => {\n promise = promise.then((remainResults) => {\n if (done) return [];\n if (remainResults.length > 1) return remainResults;\n // no cursor means we have reached the end\n // except for the first time\n if (!cursor && remainResults.length !== 0) {\n done = true;\n return remainResults;\n }\n // when only 1 item left in queue\n // start the next request to see if it is the last one\n return AVRequest(\n 'scan/classes',\n this.className,\n null,\n 'GET',\n cursor ? _.extend({}, condition, { cursor }) : condition,\n authOptions\n ).then(response => {\n cursor = response.cursor;\n return this._parseResponse(response);\n }).then(results => {\n if (!results.length) done = true;\n return remainResults.concat(results);\n });\n });\n return promise\n .then(remainResults => remainResults.shift())\n .then(result => ({\n value: result,\n done,\n }));\n },\n };\n },\n\n /**\n * Delete objects retrieved by this query.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n destroyAll: function(options){\n var self = this;\n return self.find(options).then(function(objects){\n return AV.Object.destroyAll(objects, options);\n });\n },\n\n /**\n * Counts the number of objects that match this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the count when\n * the query completes.\n */\n count: function(options) {\n var params = this.toJSON();\n params.limit = 0;\n params.count = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return response.count;\n });\n },\n\n /**\n * Retrieves at most one AV.Object that satisfies this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the object when\n * the query completes.\n */\n first: function(options) {\n var self = this;\n\n var params = this.toJSON();\n params.limit = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return _.map(response.results, function(json) {\n var obj = self._newObject();\n if (obj._finishFetch) {\n obj._finishFetch(self._processResult(json), true);\n }\n return obj;\n })[0];\n });\n },\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n requires(n, 'undefined is not a valid skip value');\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n requires(n, 'undefined is not a valid limit value');\n this._limit = n;\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that the AV.Object must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n equalTo: function(key, value) {\n requires(key, 'undefined is not a valid key');\n requires(value, 'undefined is not a valid value');\n this._where[key] = AV._encode(value);\n return this;\n },\n\n /**\n * Helper for condition queries\n * @private\n */\n _addCondition: function(key, condition, value) {\n requires(key, 'undefined is not a valid condition key');\n requires(condition, 'undefined is not a valid condition');\n requires(value, 'undefined is not a valid condition value');\n\n // Check if we already have a condition\n if (!this._where[key]) {\n this._where[key] = {};\n }\n this._where[key][condition] = AV._encode(value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular\n * array key's length to be equal to the provided value.\n * @param {String} key The array key to check.\n * @param value The length value.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n sizeEqualTo: function(key, value) {\n this._addCondition(key, \"$size\", value);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be not equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that must not be equalled.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notEqualTo: function(key, value) {\n this._addCondition(key, \"$ne\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThan: function(key, value) {\n this._addCondition(key, \"$lt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThan: function(key, value) {\n this._addCondition(key, \"$gt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$lte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$gte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containedIn: function(key, values) {\n this._addCondition(key, \"$in\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * not be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notContainedIn: function(key, values) {\n this._addCondition(key, \"$nin\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * contain each one of the provided list of values.\n * @param {String} key The key to check. This key's value must be an array.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containsAll: function(key, values) {\n this._addCondition(key, \"$all\", values);\n return this;\n },\n\n\n /**\n * Add a constraint for finding objects that contain the given key.\n * @param {String} key The key that should exist.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n exists: function(key) {\n this._addCondition(key, \"$exists\", true);\n return this;\n },\n\n /**\n * Add a constraint for finding objects that do not contain a given key.\n * @param {String} key The key that should not exist\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotExist: function(key) {\n this._addCondition(key, \"$exists\", false);\n return this;\n },\n\n /**\n * Add a regular expression constraint for finding string values that match\n * the provided regular expression.\n * This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {RegExp} regex The regular expression pattern to match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matches: function(key, regex, modifiers) {\n this._addCondition(key, \"$regex\", regex);\n if (!modifiers) { modifiers = \"\"; }\n // Javascript regex options support mig as inline options but store them\n // as properties of the object. We support mi & should migrate them to\n // modifiers\n if (regex.ignoreCase) { modifiers += 'i'; }\n if (regex.multiline) { modifiers += 'm'; }\n\n if (modifiers && modifiers.length) {\n this._addCondition(key, \"$options\", modifiers);\n }\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value matches a AV.Query\n * constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$inQuery\", queryJSON);\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not matches a\n * AV.Query constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$notInQuery\", queryJSON);\n return this;\n },\n\n\n /**\n * Add a constraint that requires that a key's value matches a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * matched.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$select\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not match a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * excluded.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$dontSelect\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add constraint that at least one of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _orQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$or = queryJSON;\n return this;\n },\n\n /**\n * Add constraint that both of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _andQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$and = queryJSON;\n return this;\n },\n\n\n /**\n * Converts a string into a regex that matches it.\n * Surrounding with \\Q .. \\E does this, we just need to escape \\E's in\n * the text separately.\n * @private\n */\n _quote: function(s) {\n return \"\\\\Q\" + s.replace(\"\\\\E\", \"\\\\E\\\\\\\\E\\\\Q\") + \"\\\\E\";\n },\n\n /**\n * Add a constraint for finding string values that contain a provided\n * string. This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} substring The substring that the value must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n contains: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that start with a provided\n * string. This query will use the backend index, so it will be fast even\n * for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} prefix The substring that the value must start with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n startsWith: function(key, value) {\n this._addCondition(key, \"$regex\", \"^\" + this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that end with a provided\n * string. This will be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} suffix The substring that the value must end with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n endsWith: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value) + \"$\");\n return this;\n },\n\n /**\n * Sorts the results in ascending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n ascending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = key;\n return this;\n },\n\n /**\n * Also sorts the results in ascending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addAscending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',' + key;\n else\n this._order = key;\n return this;\n },\n\n /**\n * Sorts the results in descending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n descending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = \"-\" + key;\n return this;\n },\n\n /**\n * Also sorts the results in descending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addDescending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',-' + key;\n else\n this._order = '-' + key;\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n near: function(key, point) {\n if (!(point instanceof AV.GeoPoint)) {\n // Try to cast it to a GeoPoint, so that near(\"loc\", [20,30]) works.\n point = new AV.GeoPoint(point);\n }\n this._addCondition(key, \"$nearSphere\", point);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param maxDistance Maximum distance (in radians) of results to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinRadians: function(key, point, distance) {\n this.near(key, point);\n this._addCondition(key, \"$maxDistance\", distance);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 3958.8 miles.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in miles) of results to\n * return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinMiles: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 3958.8);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 6371.0 kilometers.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in kilometers) of results\n * to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinKilometers: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 6371.0);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's\n * coordinates be contained within a given rectangular geographic bounding\n * box.\n * @param {String} key The key to be constrained.\n * @param {AV.GeoPoint} southwest\n * The lower-left inclusive corner of the box.\n * @param {AV.GeoPoint} northeast\n * The upper-right inclusive corner of the box.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinGeoBox: function(key, southwest, northeast) {\n if (!(southwest instanceof AV.GeoPoint)) {\n southwest = new AV.GeoPoint(southwest);\n }\n if (!(northeast instanceof AV.GeoPoint)) {\n northeast = new AV.GeoPoint(northeast);\n }\n this._addCondition(key, '$within', { '$box': [southwest, northeast] });\n return this;\n },\n\n /**\n * Include nested AV.Objects for the provided key. You can use dot\n * notation to specify which fields in the included object are also fetch.\n * @param {String[]} keys The name of the key to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n include: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._include = this._include.concat(ensureArray(keys))\n });\n return this;\n },\n\n /**\n * Restrict the fields of the returned AV.Objects to include only the\n * provided keys. If this is called multiple times, then all of the keys\n * specified in each of the calls will be included.\n * @param {String[]} keys The names of the keys to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n select: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._select = this._select.concat(ensureArray(keys));\n });\n return this;\n },\n\n /**\n * Iterates over each result of a query, calling a callback for each one. If\n * the callback returns a promise, the iteration will not continue until\n * that promise has been fulfilled. If the callback returns a rejected\n * promise, then iteration will stop with that error. The items are\n * processed in an unspecified order. The query may not have any sort order,\n * and may not use limit or skip.\n * @param callback {Function} Callback that will be called with each result\n * of the query.\n * @return {Promise} A promise that will be fulfilled once the\n * iteration has completed.\n */\n each: function(callback, options = {}) {\n\n if (this._order || this._skip || (this._limit >= 0)) {\n var error =\n new Error(\"Cannot iterate on a query with sort, skip, or limit.\");\n return AV.Promise.reject(error);\n }\n\n var query = new AV.Query(this.objectClass);\n // We can override the batch size from the options.\n // This is undocumented, but useful for testing.\n query._limit = options.batchSize || 100;\n query._where = _.clone(this._where);\n query._include = _.clone(this._include);\n\n query.ascending('objectId');\n\n var finished = false;\n return AV.Promise._continueWhile(function() {\n return !finished;\n\n }, function() {\n return query.find(options).then(function(results) {\n var callbacksDone = AV.Promise.resolve();\n _.each(results, function(result) {\n callbacksDone = callbacksDone.then(function() {\n return callback(result);\n });\n });\n\n return callbacksDone.then(function() {\n if (results.length >= query._limit) {\n query.greaterThan(\"objectId\", results[results.length - 1].id);\n } else {\n finished = true;\n }\n });\n });\n });\n }\n };\n\n AV.FriendShipQuery = AV.Query._extend({\n _objectClass: AV.User,\n _newObject: function(){\n return new AV.User();\n },\n _processResult: function(json){\n if(json && json[this._friendshipTag]) {\n var user = json[this._friendshipTag];\n if(user.__type === 'Pointer' && user.className === '_User'){\n delete user.__type;\n delete user.className;\n }\n return user;\n } else {\n return null;\n }\n },\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/query.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n /**\n * Creates a new Relation for the given parent object and key. This\n * constructor should rarely be used directly, but rather created by\n * {@link AV.Object#relation}.\n * @param {AV.Object} parent The parent of this relation.\n * @param {String} key The key for this relation on the parent.\n * @see AV.Object#relation\n * @class\n *\n *

\n * A class that is used to access all of the children of a many-to-many\n * relationship. Each instance of AV.Relation is associated with a\n * particular parent object and key.\n *

\n */\n AV.Relation = function(parent, key) {\n if (! _.isString(key)) {\n throw new TypeError('key must be a string');\n }\n this.parent = parent;\n this.key = key;\n this.targetClassName = null;\n };\n\n /**\n * Creates a query that can be used to query the parent objects in this relation.\n * @param {String} parentClass The parent class or name.\n * @param {String} relationKey The relation field key in parent.\n * @param {AV.Object} child The child object.\n * @return {AV.Query}\n */\n AV.Relation.reverseQuery = function(parentClass, relationKey, child){\n var query = new AV.Query(parentClass);\n query.equalTo(relationKey, child._toPointer());\n return query;\n };\n\n AV.Relation.prototype = {\n /**\n * Makes sure that this relation has the right parent and key.\n * @private\n */\n _ensureParentAndKey: function(parent, key) {\n this.parent = this.parent || parent;\n this.key = this.key || key;\n if (this.parent !== parent) {\n throw new Error(\"Internal Error. Relation retrieved from two different Objects.\");\n }\n if (this.key !== key) {\n throw new Error(\"Internal Error. Relation retrieved from two different keys.\");\n }\n },\n\n /**\n * Adds a AV.Object or an array of AV.Objects to the relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to add.\n */\n add: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation(objects, []);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Removes a AV.Object or an array of AV.Objects from this relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to remove.\n */\n remove: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation([], objects);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Returns a JSON version of the object suitable for saving to disk.\n * @return {Object}\n */\n toJSON: function() {\n return { \"__type\": \"Relation\", \"className\": this.targetClassName };\n },\n\n /**\n * Returns a AV.Query that is limited to objects in this\n * relation.\n * @return {AV.Query}\n */\n query: function() {\n var targetClass;\n var query;\n if (!this.targetClassName) {\n targetClass = AV.Object._getSubclass(this.parent.className);\n query = new AV.Query(targetClass);\n query._extraOptions.redirectClassNameForKey = this.key;\n } else {\n targetClass = AV.Object._getSubclass(this.targetClassName);\n query = new AV.Query(targetClass);\n }\n query._addCondition(\"$relatedTo\", \"object\", this.parent._toPointer());\n query._addCondition(\"$relatedTo\", \"key\", this.key);\n\n return query;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/relation.js","const _ = require('underscore');\nconst AVError = require('./error');\n\nmodule.exports = function(AV) {\n AV.Role = AV.Object.extend(\"_Role\", /** @lends AV.Role.prototype */ {\n // Instance Methods\n\n /**\n * Represents a Role on the AV server. Roles represent groupings of\n * Users for the purposes of granting permissions (e.g. specifying an ACL\n * for an Object). Roles are specified by their sets of child users and\n * child roles, all of which are granted any permissions that the parent\n * role has.\n *\n *

Roles must have a name (which cannot be changed after creation of the\n * role), and must specify an ACL.

\n * An AV.Role is a local representation of a role persisted to the AV\n * cloud.\n * @class AV.Role\n * @param {String} name The name of the Role to create.\n * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL\n * `{'*': { read: true }}` will be used.\n */\n constructor: function(name, acl, noDefaultACL) {\n if (_.isString(name)) {\n AV.Object.prototype.constructor.call(this, null, null);\n this.setName(name);\n } else {\n AV.Object.prototype.constructor.call(this, name, acl);\n }\n if (acl === undefined) {\n if (!noDefaultACL) {\n if(!this.getACL()) {\n console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.');\n var defaultAcl = new AV.ACL();\n defaultAcl.setPublicReadAccess(true); \n this.setACL(defaultAcl);\n }\n }\n } else if (!(acl instanceof AV.ACL)) {\n throw new TypeError('acl must be an instance of AV.ACL');\n } else {\n this.setACL(acl);\n }\n },\n\n /**\n * Gets the name of the role. You can alternatively call role.get(\"name\")\n *\n * @return {String} the name of the role.\n */\n getName: function() {\n return this.get(\"name\");\n },\n\n /**\n * Sets the name for a role. This value must be set before the role has\n * been saved to the server, and cannot be set once the role has been\n * saved.\n *\n *

\n * A role's name can only contain alphanumeric characters, _, -, and\n * spaces.\n *

\n *\n *

This is equivalent to calling role.set(\"name\", name)

\n *\n * @param {String} name The name of the role.\n */\n setName: function(name, options) {\n return this.set(\"name\", name, options);\n },\n\n /**\n * Gets the AV.Relation for the AV.Users that are direct\n * children of this role. These users are granted any privileges that this\n * role has been granted (e.g. read or write access through ACLs). You can\n * add or remove users from the role through this relation.\n *\n *

This is equivalent to calling role.relation(\"users\")

\n *\n * @return {AV.Relation} the relation for the users belonging to this\n * role.\n */\n getUsers: function() {\n return this.relation(\"users\");\n },\n\n /**\n * Gets the AV.Relation for the AV.Roles that are direct\n * children of this role. These roles' users are granted any privileges that\n * this role has been granted (e.g. read or write access through ACLs). You\n * can add or remove child roles from this role through this relation.\n *\n *

This is equivalent to calling role.relation(\"roles\")

\n *\n * @return {AV.Relation} the relation for the roles belonging to this\n * role.\n */\n getRoles: function() {\n return this.relation(\"roles\");\n },\n\n /**\n * @ignore\n */\n validate: function(attrs, options) {\n if (\"name\" in attrs && attrs.name !== this.getName()) {\n var newName = attrs.name;\n if (this.id && this.id !== attrs.objectId) {\n // Check to see if the objectId being set matches this.id.\n // This happens during a fetch -- the id is set before calling fetch.\n // Let the name be set in this case.\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only be set before it has been saved.\");\n }\n if (!_.isString(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name must be a String.\");\n }\n if (!(/^[0-9a-zA-Z\\-_ ]+$/).test(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only contain alphanumeric characters, _,\" +\n \" -, and spaces.\");\n }\n }\n if (AV.Object.prototype.validate) {\n return AV.Object.prototype.validate.call(this, attrs, options);\n }\n return false;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/role.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * A builder to generate sort string for app searching.For example:\n * @class\n * @since 0.5.1\n * @example\n * var builder = new AV.SearchSortBuilder();\n * builder.ascending('key1').descending('key2','max');\n * var query = new AV.SearchQuery('Player');\n * query.sortBy(builder);\n * query.find().then();\n */\n AV.SearchSortBuilder = function() {\n this._sortFields = [];\n };\n\n AV.SearchSortBuilder.prototype = {\n _addField: function(key, order, mode, missing) {\n var field = {};\n field[key] = {\n order: order || 'asc',\n mode: mode ||'avg',\n missing: '_' + (missing || 'last')\n };\n this._sortFields.push(field);\n return this;\n },\n\n\n /**\n * Sorts the results in ascending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n ascending: function(key, mode, missing) {\n return this._addField(key, 'asc', mode, missing);\n },\n\n /**\n * Sorts the results in descending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n descending: function(key, mode, missing) {\n return this._addField(key, 'desc', mode, missing);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Object} options The other options such as mode,order, unit etc.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n whereNear: function(key, point, options) {\n options = options || {};\n var field = {};\n var geo = {\n lat: point.latitude,\n lon: point.longitude\n };\n var m = {\n order: options.order || 'asc',\n mode: options.mode || 'avg',\n unit: options.unit || 'km'\n };\n m[key] = geo;\n field['_geo_distance'] = m;\n\n this._sortFields.push(field);\n return this;\n },\n\n /**\n * Build a sort string by configuration.\n * @return {String} the sort string.\n */\n build: function() {\n return JSON.stringify(AV._encode(this._sortFields));\n }\n };\n\n /**\n * App searching query.Use just like AV.Query:\n *\n * Visit App Searching Guide\n * for more details.\n * @class\n * @since 0.5.1\n * @example\n * var query = new AV.SearchQuery('Player');\n * query.queryString('*');\n * query.find().then(function(results) {\n * console.log('Found %d objects', query.hits());\n * //Process results\n * });\n */\n AV.SearchQuery = AV.Query._extend(/** @lends AV.SearchQuery.prototype */{\n _sid: null,\n _hits: 0,\n _queryString: null,\n _highlights: null,\n _sortBuilder: null,\n _createRequest: function(params, options){\n return AVRequest('search/select', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n /**\n * Sets the sid of app searching query.Default is null.\n * @param {String} sid Scroll id for searching.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n sid: function(sid) {\n this._sid = sid;\n return this;\n },\n\n /**\n * Sets the query string of app searching.\n * @param {String} q The query string.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n queryString: function(q) {\n this._queryString = q;\n return this;\n },\n\n\n /**\n * Sets the highlight fields. Such as\n *
\n     *   query.highlights('title');\n     *   //or pass an array.\n     *   query.highlights(['title', 'content'])\n     * 
\n * @param {String[]} highlights a list of fields.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n highlights: function(highlights) {\n var objects;\n if (highlights && _.isString(highlights)) {\n objects = arguments;\n } else {\n objects = highlights;\n }\n this._highlights = objects;\n return this;\n },\n\n /**\n * Sets the sort builder for this query.\n * @see AV.SearchSortBuilder\n * @param { AV.SearchSortBuilder} builder The sort builder.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n *\n */\n sortBy: function(builder) {\n this._sortBuilder = builder;\n return this;\n },\n\n /**\n * Returns the number of objects that match this query.\n * @return {Number}\n */\n hits: function() {\n if (!this._hits) {\n this._hits = 0;\n }\n return this._hits;\n },\n\n _processResult: function(json){\n delete json['className'];\n delete json['_app_url'];\n delete json['_deeplink'];\n return json;\n },\n\n /**\n * Returns true when there are more documents can be retrieved by this\n * query instance, you can call find function to get more results.\n * @see AV.SearchQuery#find\n * @return {Boolean}\n */\n hasMore: function() {\n return !this._hitEnd;\n },\n\n /**\n * Reset current query instance state(such as sid, hits etc) except params\n * for a new searching. After resetting, hasMore() will return true.\n */\n reset: function() {\n this._hitEnd = false;\n this._sid = null;\n this._hits = 0;\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n * Either options.success or options.error is called when the find\n * completes.\n *\n * @see AV.Query#find\n * @return {AV.Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find: function() {\n var self = this;\n\n var request = this._createRequest();\n\n return request.then(function(response) {\n //update sid for next querying.\n if(response.sid) {\n self._oldSid = self._sid;\n self._sid = response.sid;\n } else {\n self._sid = null;\n self._hitEnd = true;\n }\n self._hits = response.hits || 0;\n\n return _.map(response.results, function(json) {\n if(json.className) {\n response.className = json.className;\n }\n var obj = self._newObject(response);\n obj.appURL = json['_app_url'];\n obj._finishFetch(self._processResult(json), true);\n return obj;\n });\n });\n },\n\n toJSON: function(){\n var params = AV.SearchQuery.__super__.toJSON.call(this);\n delete params.where;\n if(this.className) {\n params.clazz = this.className;\n }\n if(this._sid) {\n params.sid = this._sid;\n }\n if(!this._queryString) {\n throw new Error('Please set query string.');\n } else {\n params.q = this._queryString;\n }\n if(this._highlights) {\n params.highlights = this._highlights.join(',');\n }\n if(this._sortBuilder && params.order) {\n throw new Error('sort and order can not be set at same time.');\n }\n if(this._sortBuilder) {\n params.sort = this._sortBuilder.build();\n }\n\n return params;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/search.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n const getUser = (options = {}) => AV.User.currentAsync()\n .then(currUser => currUser || AV.User._fetchUserBySessionToken(options.sessionToken));\n\n const getUserPointer = options => getUser(options)\n .then(currUser => AV.Object.createWithoutData('_User', currUser.id)._toPointer());\n\n /**\n * Contains functions to deal with Status in LeanCloud.\n * @class\n */\n AV.Status = function(imageUrl, message) {\n this.data = {};\n this.inboxType = 'default';\n this.query = null;\n if(imageUrl && typeof imageUrl === 'object') {\n this.data = imageUrl;\n } else {\n if(imageUrl){\n this.data.image = imageUrl;\n }\n if(message){\n this.data.message = message;\n }\n }\n return this;\n };\n\n AV.Status.prototype = {\n /**\n * Gets the value of an attribute in status data.\n * @param {String} attr The string name of an attribute.\n */\n get: function(attr){\n return this.data[attr];\n },\n /**\n * Sets a hash of model attributes on the status data.\n * @param {String} key The key to set.\n * @param {} value The value to give it.\n */\n set: function(key, value){\n this.data[key] = value;\n return this;\n },\n /**\n * Destroy this status,then it will not be avaiable in other user's inboxes.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options){\n if(!this.id)\n return AV.Promise.reject(new Error('The status id is not exists.'));\n var request = AVRequest('statuses', null, this.id, 'DELETE', options);\n return request;\n },\n /**\n * Cast the AV.Status object to an AV.Object pointer.\n * @return {AV.Object} A AV.Object pointer.\n */\n toObject: function(){\n if(!this.id)\n return null;\n return AV.Object.createWithoutData('_Status', this.id);\n },\n _getDataJSON: function() {\n var json = _.clone(this.data);\n return AV._encode(json);\n },\n /**\n * Send a status by a AV.Query object.\n * @since 0.3.0\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a status to male users\n * var status = new AVStatus('image url', 'a message');\n * status.query = new AV.Query('_User');\n * status.query.equalTo('gender', 'male');\n * status.send().then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n send: function(options = {}){\n if(!options.sessionToken && !AV.User.current()) {\n throw new Error('Please signin an user.');\n }\n if(!this.query){\n return AV.Status.sendStatusToFollowers(this, options);\n }\n\n return getUserPointer(options).then(currUser => {\n var query = this.query.toJSON();\n query.className = this.query.className;\n var data = {};\n data.query = query;\n this.data = this.data || {};\n this.data.source = this.data.source || currUser;\n data.data = this._getDataJSON();\n data.inboxType = this.inboxType || 'default';\n\n return AVRequest('statuses', null, null, 'POST', data, options);\n })\n .then((response) => {\n this.id = response.objectId;\n this.createdAt = AV._parseDate(response.createdAt);\n return this;\n });\n },\n\n _finishFetch: function(serverData){\n this.id = serverData.objectId;\n this.createdAt = AV._parseDate(serverData.createdAt);\n this.updatedAt = AV._parseDate(serverData.updatedAt);\n this.messageId = serverData.messageId;\n delete serverData.messageId;\n delete serverData.objectId;\n delete serverData.createdAt;\n delete serverData.updatedAt;\n this.data = AV._decode(serverData);\n }\n };\n\n /**\n * Send a status to current signined user's followers.\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendStatusToFollowers(status).then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendStatusToFollowers = function(status, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_Follower';\n query.keys = 'follower';\n query.where = {user: currUser};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = status.inboxType || 'default';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n *

Send a status from current signined user to other user's private status inbox.

\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {String} target The target user or user's objectId.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a private status to user '52e84e47e4b0f8de283b079b'\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendPrivateStatus = function(status, target, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n if(!target){\n throw new Error(\"Invalid target user.\");\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error(\"Invalid target user.\");\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_User';\n query.where = {objectId: userObjectId};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = 'private';\n status.inboxType = 'private';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n * Count unread statuses in someone's inbox.\n * @since 0.3.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the count\n * completes.\n * @example\n * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.countUnreadStatuses = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options);\n });\n };\n\n /**\n * reset unread statuses count in someone's inbox.\n * @since 2.1.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the reset\n * completes.\n * @example\n * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.resetUnreadCount = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options);\n });\n };\n\n /**\n * Create a status query to find someone's published statuses.\n * @since 0.3.0\n * @param {Object} source The status source.\n * @return {AV.Query} The query object for status.\n * @example\n * //Find current user's published statuses.\n * var query = AV.Status.statusQuery(AV.User.current());\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.statusQuery = function(source){\n var query = new AV.Query('_Status');\n if(source){\n query.equalTo('source', source);\n }\n return query;\n };\n\n /**\n *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

\n * @class\n */\n AV.InboxQuery = AV.Query._extend(/** @lends AV.InboxQuery.prototype */{\n _objectClass: AV.Status,\n _sinceId: 0,\n _maxId: 0,\n _inboxType: 'default',\n _owner: null,\n _newObject: function(){\n return new AV.Status();\n },\n _createRequest: function(params, options){\n return AVRequest('subscribe/statuses', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n\n /**\n * Sets the messageId of results to skip before returning any results.\n * This is useful for pagination.\n * Default is zero.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n sinceId: function(id){\n this._sinceId = id;\n return this;\n },\n /**\n * Sets the maximal messageId of results。\n * This is useful for pagination.\n * Default is zero that is no limition.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n maxId: function(id){\n this._maxId = id;\n return this;\n },\n /**\n * Sets the owner of the querying inbox.\n * @param {Object} owner The inbox owner.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n owner: function(owner){\n this._owner = owner;\n return this;\n },\n /**\n * Sets the querying inbox type.default is 'default'.\n * @param {Object} owner The inbox type.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n inboxType: function(type){\n this._inboxType = type;\n return this;\n },\n toJSON: function(){\n var params = AV.InboxQuery.__super__.toJSON.call(this);\n params.owner = AV._encode(this._owner);\n params.inboxType = AV._encode(this._inboxType);\n params.sinceId = AV._encode(this._sinceId);\n params.maxId = AV._encode(this._maxId);\n return params;\n }\n });\n\n /**\n * Create a inbox status query to find someone's inbox statuses.\n * @since 0.3.0\n * @param {Object} owner The inbox's owner\n * @param {String} inboxType The inbox type,'default' by default.\n * @return {AV.InboxQuery} The inbox query object.\n * @see AV.InboxQuery\n * @example\n * //Find current user's default inbox statuses.\n * var query = AV.Status.inboxQuery(AV.User.current());\n * //find the statuses after the last message id\n * query.sinceId(lastMessageId);\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.inboxQuery = function(owner, inboxType){\n var query = new AV.InboxQuery(AV.Status);\n if(owner){\n query._owner = owner;\n }\n if(inboxType){\n query._inboxType = inboxType;\n }\n return query;\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/status.js","module.exports = [];\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/comments-browser.js","const version = require('../version');\nconst comments = [process.env.CLIENT_PLATFORM || 'Node.js'].concat(require('./comments'));\n\nmodule.exports = `LeanCloud-JS-SDK/${version} (${comments.join('; ')})`;\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/index.js","const request = require('superagent');\nconst debug = require('debug')('cos');\nconst Promise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n const uploadUrl = uploadInfo.upload_url + \"?sign=\" + encodeURIComponent(uploadInfo.token);\n\n return new Promise((resolve, reject) => {\n const req = request('POST', uploadUrl)\n .field('fileContent', data)\n .field('op', 'upload');\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/cos.js","const request = require('superagent');\nconst Promise = require('../promise');\nconst debug = require('debug')('qiniu');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n // Get the uptoken to upload files to qiniu.\n const uptoken = uploadInfo.token;\n return new Promise((resolve, reject) => {\n const req = request('POST', 'https://up.qbox.me')\n .field('file', data)\n .field('name', file.attributes.name)\n .field('key', file._qiniu_key)\n .field('token', uptoken);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/qiniu-browser.js","const request = require('superagent');\nconst AVPromise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n return new Promise((resolve, reject) => {\n // 海外节点,针对 S3 才会返回 upload_url\n const req = request('PUT', uploadInfo.upload_url)\n .set('Content-Type', file.get('mime_type'))\n .send(data);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/s3.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\n\nconst getWeappLoginCode = () => {\n if (typeof wx === 'undefined' || typeof wx.login !== 'function') {\n throw new Error('Weapp Login is only available in Weapp');\n }\n return new Promise((resolve, reject) => {\n wx.login({\n success: ({ code, errMsg }) => {\n if (code) {\n resolve(code);\n } else {\n reject(new Error(errMsg));\n }\n },\n });\n });\n};\n\nmodule.exports = function(AV) {\n /**\n * @class\n *\n *

An AV.User object is a local representation of a user persisted to the\n * LeanCloud server. This class is a subclass of an AV.Object, and retains the\n * same functionality of an AV.Object, but also extends it with various\n * user specific methods, like authentication, signing up, and validation of\n * uniqueness.

\n */\n AV.User = AV.Object.extend(\"_User\", /** @lends AV.User.prototype */ {\n // Instance Variables\n _isCurrentUser: false,\n\n\n // Instance Methods\n\n /**\n * Internal method to handle special fields in a _User response.\n * @private\n */\n _mergeMagicFields: function(attrs) {\n if (attrs.sessionToken) {\n this._sessionToken = attrs.sessionToken;\n delete attrs.sessionToken;\n }\n AV.User.__super__._mergeMagicFields.call(this, attrs);\n },\n\n /**\n * Removes null values from authData (which exist temporarily for\n * unlinking)\n * @private\n */\n _cleanupAuthData: function() {\n if (!this.isCurrent()) {\n return;\n }\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n AV._objectEach(this.get('authData'), function(value, key) {\n if (!authData[key]) {\n delete authData[key];\n }\n });\n },\n\n /**\n * Synchronizes authData for all providers.\n * @private\n */\n _synchronizeAllAuthData: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._synchronizeAuthData(key);\n });\n },\n\n /**\n * Synchronizes auth data for a provider (e.g. puts the access token in the\n * right place to be used by the Facebook SDK).\n * @private\n */\n _synchronizeAuthData: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[authType];\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData');\n if (!authData || !provider) {\n return;\n }\n var success = provider.restoreAuthentication(authData[authType]);\n if (!success) {\n this._unlinkFrom(provider);\n }\n },\n\n _handleSaveResult: function(makeCurrent) {\n // Clean up and synchronize the authData object, removing any unset values\n if (makeCurrent && !AV._config.disableCurrentUser) {\n this._isCurrentUser = true;\n }\n this._cleanupAuthData();\n this._synchronizeAllAuthData();\n // Don't keep the password around.\n delete this._serverData.password;\n this._rebuildEstimatedDataForKey(\"password\");\n this._refreshCache();\n if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) {\n // Some old version of leanengine-node-sdk will overwrite\n // AV.User._saveCurrentUser which returns no Promise.\n // So we need a Promise wrapper.\n return Promise.resolve(AV.User._saveCurrentUser(this));\n } else {\n return Promise.resolve();\n }\n },\n\n /**\n * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can\n * call linkWith on the user (even if it doesn't exist yet on the server).\n * @private\n */\n _linkWith: function(provider, data) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[provider];\n } else {\n authType = provider.getAuthType();\n }\n if (data) {\n var authData = this.get('authData') || {};\n authData[authType] = data;\n return this.save({ authData })\n .then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n } else {\n return provider.authenticate().then(result => this._linkWith(provider, result));\n }\n },\n\n /**\n * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。\n * 仅在小程序中可用。\n *\n * @return {AV.User}\n */\n linkWithWeapp() {\n return getWeappLoginCode().then(code => this._linkWith('lc_weapp', { code }));\n },\n\n /**\n * Unlinks a user from a service.\n * @private\n */\n _unlinkFrom: function(provider) {\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n return this._linkWith(provider, null).then(model => {\n this._synchronizeAuthData(provider);\n return model;\n });\n },\n\n /**\n * Checks whether a user is linked to a service.\n * @private\n */\n _isLinked: function(provider) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData') || {};\n return !!authData[authType];\n },\n\n logOut: function() {\n this._logOutWithAll();\n this._isCurrentUser = false;\n },\n\n /**\n * Deauthenticates all providers.\n * @private\n */\n _logOutWithAll: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._logOutWith(key);\n });\n },\n\n /**\n * Deauthenticates a single provider (e.g. removing access tokens from the\n * Facebook SDK).\n * @private\n */\n _logOutWith: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n if (provider && provider.deauthenticate) {\n provider.deauthenticate();\n }\n },\n\n /**\n * Signs up a new user. You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUp\n */\n signUp: function(attrs, options) {\n var error;\n\n var username = (attrs && attrs.username) || this.get(\"username\");\n if (!username || (username === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty name.\");\n throw error;\n }\n\n var password = (attrs && attrs.password) || this.get(\"password\");\n if (!password || (password === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty password.\");\n throw error;\n }\n\n return this.save(attrs, options).then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Signs up a new user with mobile phone and sms code.\n * You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(attrs, options = {}) {\n var error;\n\n var mobilePhoneNumber = (attrs && attrs.mobilePhoneNumber) ||\n this.get(\"mobilePhoneNumber\");\n if (!mobilePhoneNumber || (mobilePhoneNumber === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty mobilePhoneNumber.\");\n throw error;\n }\n\n var smsCode = (attrs && attrs.smsCode) || this.get(\"smsCode\");\n if (!smsCode || (smsCode === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty smsCode.\");\n throw error;\n }\n\n options._makeRequest = function(route, className, id, method, json) {\n return AVRequest('usersByMobilePhone', null, null, \"POST\", json);\n };\n return this.save(attrs, options).then(function(model) {\n delete model.attributes.smsCode;\n delete model._serverData.smsCode;\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Logs in a AV.User. On success, this saves the session to localStorage,\n * so you can retrieve the currently logged in user using\n * current.\n *\n *

A username and password must be set before calling logIn.

\n *\n * @see AV.User.logIn\n * @return {Promise} A promise that is fulfilled with the user when\n * the login is complete.\n */\n logIn: function() {\n var model = this;\n var request = AVRequest('login', null, null, 'POST', this.toJSON());\n return request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n model._finishFetch(serverAttrs);\n return model._handleSaveResult(true).then(function() {\n if(!serverAttrs.smsCode)\n delete model.attributes['smsCode'];\n return model;\n });\n });\n },\n /**\n * @see AV.Object#save\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n options = options || {};\n\n return AV.Object.prototype.save\n .call(this, attrs, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Follow a user\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to follow.\n * @param {AuthOptions} options\n */\n follow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'POST', null, options);\n return request;\n },\n\n /**\n * Unfollow a user.\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to unfollow.\n * @param {AuthOptions} options\n */\n unfollow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'DELETE', null, options);\n return request;\n },\n\n /**\n *Create a follower query to query the user's followers.\n * @since 0.3.0\n * @see AV.User#followerQuery\n */\n followerQuery: function() {\n return AV.User.followerQuery(this.id);\n },\n\n /**\n *Create a followee query to query the user's followees.\n * @since 0.3.0\n * @see AV.User#followeeQuery\n */\n followeeQuery: function() {\n return AV.User.followeeQuery(this.id);\n },\n\n /**\n * @see AV.Object#fetch\n */\n fetch: function(fetchOptions, options) {\n return AV.Object.prototype.fetch.call(this, fetchOptions, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Update user's new password safely based on old password.\n * @param {String} oldPassword the old password.\n * @param {String} newPassword the new password.\n * @param {AuthOptions} options\n */\n updatePassword: function(oldPassword, newPassword, options) {\n var route = 'users/' + this.id + '/updatePassword';\n var params = {\n old_password: oldPassword,\n new_password: newPassword\n };\n var request = AVRequest(route, null, null, 'PUT', params, options);\n return request;\n },\n\n /**\n * Returns true if current would return this user.\n * @see AV.User#current\n */\n isCurrent: function() {\n return this._isCurrentUser;\n },\n\n /**\n * Returns get(\"username\").\n * @return {String}\n * @see AV.Object#get\n */\n getUsername: function() {\n return this.get(\"username\");\n },\n\n /**\n * Returns get(\"mobilePhoneNumber\").\n * @return {String}\n * @see AV.Object#get\n */\n getMobilePhoneNumber: function(){\n return this.get(\"mobilePhoneNumber\");\n },\n\n /**\n * Calls set(\"mobilePhoneNumber\", phoneNumber, options) and returns the result.\n * @param {String} mobilePhoneNumber\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setMobilePhoneNumber: function(phone, options) {\n return this.set(\"mobilePhoneNumber\", phone, options);\n },\n\n /**\n * Calls set(\"username\", username, options) and returns the result.\n * @param {String} username\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setUsername: function(username, options) {\n return this.set(\"username\", username, options);\n },\n\n /**\n * Calls set(\"password\", password, options) and returns the result.\n * @param {String} password\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setPassword: function(password, options) {\n return this.set(\"password\", password, options);\n },\n\n /**\n * Returns get(\"email\").\n * @return {String}\n * @see AV.Object#get\n */\n getEmail: function() {\n return this.get(\"email\");\n },\n\n /**\n * Calls set(\"email\", email, options) and returns the result.\n * @param {String} email\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setEmail: function(email, options) {\n return this.set(\"email\", email, options);\n },\n\n /**\n * Checks whether this user is the current user and has been authenticated.\n * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),\n * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id\n * @return (Boolean) whether this user is the current user and is logged in.\n */\n authenticated: function() {\n console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。')\n return !!this._sessionToken &&\n (!AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id);\n },\n\n /**\n * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。\n *\n * @since 2.0.0\n * @return Promise.\n */\n isAuthenticated() {\n return Promise.resolve().then(() =>\n !!this._sessionToken &&\n AV.User._fetchUserBySessionToken(this._sessionToken).then(\n () => true,\n (error) => {\n if (error.code === 211) {\n return false;\n }\n throw error;\n }\n )\n );\n },\n\n /**\n * Get sessionToken of current user.\n * @return {String} sessionToken\n */\n getSessionToken() {\n return this._sessionToken;\n },\n\n /**\n * Refresh sessionToken of current user.\n * @since 2.1.0\n * @param {AuthOptions} [options]\n * @return {Promise.} user with refreshed sessionToken\n */\n refreshSessionToken(options) {\n return AVRequest(`users/${this.id}/refreshSessionToken`, null, null, 'PUT', null, options)\n .then(response => {\n this._finishFetch(response);\n return this._handleSaveResult(true).then(() => this);\n });\n },\n\n /**\n * Get this user's Roles.\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that is fulfilled with the roles when\n * the query is complete.\n */\n getRoles(options) {\n return AV.Relation.reverseQuery(\"_Role\", \"users\", this).find(options);\n },\n\n }, /** @lends AV.User */ {\n // Class Variables\n\n // The currently logged-in user.\n _currentUser: null,\n\n // Whether currentUser is known to match the serialized version on disk.\n // This is useful for saving a localstorage check if you try to load\n // _currentUser frequently while there is none stored.\n _currentUserMatchesDisk: false,\n\n // The localStorage key suffix that the current user is stored under.\n _CURRENT_USER_KEY: \"currentUser\",\n\n // The mapping of auth provider names to actual providers\n _authProviders: {},\n\n // Class Methods\n\n /**\n * Signs up a new user with a username (or email) and password.\n * This will create a new AV.User on the server, and also persist the\n * session in localStorage so that you can access the user using\n * {@link #current}.\n *\n * @param {String} username The username (or email) to sign up with.\n * @param {String} password The password to sign up with.\n * @param {Object} attrs Extra fields to set on the new user.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the signup completes.\n * @see AV.User#signUp\n */\n signUp: function(username, password, attrs, options) {\n attrs = attrs || {};\n attrs.username = username;\n attrs.password = password;\n var user = AV.Object._create(\"_User\");\n return user.signUp(attrs, options);\n },\n\n /**\n * Logs in a user with a username (or email) and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} username The username (or email) to log in with.\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logIn: function(username, password, options) {\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ username: username, password: password });\n return user.logIn(options);\n },\n\n /**\n * Logs in a user with a session token. On success, this saves the session\n * to disk, so you can retrieve the currently logged in user using\n * current.\n *\n * @param {String} sessionToken The sessionToken to log in with.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n */\n become: function(sessionToken) {\n return this._fetchUserBySessionToken(sessionToken).then(user =>\n user._handleSaveResult(true).then(() => user)\n );\n },\n\n _fetchUserBySessionToken: function(sessionToken) {\n var user = AV.Object._create(\"_User\");\n return AVRequest(\n \"users\",\n \"me\",\n null,\n \"GET\", {\n session_token: sessionToken\n }\n ).then(function(resp) {\n var serverAttrs = user.parse(resp);\n user._finishFetch(serverAttrs);\n return user;\n });\n },\n\n /**\n * Logs in a user with a mobile phone number and sms code sent by\n * AV.User.requestLoginSmsCode.On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhoneSmsCode: function(mobilePhone, smsCode, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a mobilePhoneNumber and smsCode.\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {String} mobilePhoneNumber The user's mobilePhoneNumber.\n * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode\n * @param {Object} attributes The user's other attributes such as username etc.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(mobilePhoneNumber, smsCode, attrs, options) {\n attrs = attrs || {};\n attrs.mobilePhoneNumber = mobilePhoneNumber;\n attrs.smsCode = smsCode;\n var user = AV.Object._create(\"_User\");\n return user.signUpOrlogInWithMobilePhone(attrs, options);\n },\n\n\n /**\n * Logs in a user with a mobile phone number and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhone: function(mobilePhone, password, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a third party auth data(AccessToken).\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @param {string} platform Available platform for sign up.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户}\n */\n signUpOrlogInWithAuthData(authData, platform) {\n return AV.User._logInWith(platform, authData);\n },\n\n /**\n * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。\n * 仅在小程序中可用。\n *\n * @since 2.0.0\n * @return {AV.User}\n */\n loginWithWeapp() {\n return getWeappLoginCode().then(code => this.signUpOrlogInWithAuthData({ code }, 'lc_weapp'));\n },\n\n /**\n * Associate a user with a third party auth data(AccessToken).\n *\n * @param {AV.User} userObj A user which you want to associate.\n * @param {string} platform Available platform for sign up.\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @return {Promise} A promise that is fulfilled with the user when completed.\n * @example AV.User.associateWithAuthData(loginUser, 'weixin', {\n * openid: 'abc123',\n * access_token: '123abc',\n * expires_in: 1382686496\n * }).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n */\n associateWithAuthData(userObj, platform, authData) {\n return userObj._linkWith(platform, authData);\n },\n /**\n * Logs out the currently logged in user session. This will remove the\n * session from disk, log out of linked services, and future calls to\n * current will return null.\n * @return {Promise}\n */\n logOut: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser !== null) {\n AV.User._currentUser._logOutWithAll();\n AV.User._currentUser._isCurrentUser = false;\n }\n AV.User._currentUserMatchesDisk = true;\n AV.User._currentUser = null;\n return AV.localStorage.removeItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY));\n },\n\n /**\n *Create a follower query for special user to query the user's followers.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followerQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Follower');\n query._friendshipTag ='follower';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n *Create a followee query for special user to query the user's followees.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followeeQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Followee');\n query._friendshipTag ='followee';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n * Requests a password reset email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * reset their password on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * forgot their password.\n * @return {Promise}\n */\n requestPasswordReset: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestPasswordReset\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * verify their email address on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * doesn't verify their email address.\n * @return {Promise}\n */\n requestEmailVerify: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestEmailVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * verify their mobile phone number by calling AV.User.verifyMobilePhone\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestMobilePhoneVerify: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestMobilePhoneVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n\n /**\n * Requests a reset password sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * reset their account's password by calling AV.User.resetPasswordBySmsCode\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestPasswordResetBySmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestPasswordResetBySmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Makes a call to reset user's account password by sms code and new password.\n * The sms code is sent by AV.User.requestPasswordResetBySmsCode.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @param {String} password The new password.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n resetPasswordBySmsCode: function(code, password){\n var json = { password: password};\n var request = AVRequest(\"resetPasswordBySmsCode\", null, code, \"PUT\",\n json);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode\n * If verify successfully,the user mobilePhoneVerified attribute will be true.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifyMobilePhone: function(code){\n var request = AVRequest(\"verifyMobilePhone\", null, code, \"POST\",\n null);\n return request;\n },\n\n /**\n * Requests a logIn sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * login by AV.User.logInWithMobilePhoneSmsCode function.\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that want to login by AV.User.logInWithMobilePhoneSmsCode\n * @return {Promise}\n */\n requestLoginSmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestLoginSmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {Promise.} resolved with the currently logged in AV.User.\n */\n currentAsync: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser) {\n return Promise.resolve(AV.User._currentUser);\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return Promise.resolve(AV.User._currentUser);\n }\n\n\n return AV.localStorage.getItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY)\n ).then(function(userData) {\n if (!userData) {\n return null;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n });\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {AV.User} The currently logged in AV.User.\n */\n current: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return null;\n }\n\n if (AV.User._currentUser) {\n return AV.User._currentUser;\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return AV.User._currentUser;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n var userData = AV.localStorage.getItem(AV._getAVPath(\n AV.User._CURRENT_USER_KEY));\n if (!userData) {\n\n return null;\n }\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n },\n\n /**\n * Persists a user as currentUser to localStorage, and into the singleton.\n * @private\n */\n _saveCurrentUser: function(user) {\n var promise;\n if (AV.User._currentUser !== user) {\n promise = AV.User.logOut();\n }\n else {\n promise = Promise.resolve();\n }\n return promise.then(function() {\n user._isCurrentUser = true;\n AV.User._currentUser = user;\n\n var json = user.toJSON();\n json._id = user.id;\n json._sessionToken = user._sessionToken;\n return AV.localStorage.setItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY),\n JSON.stringify(json)\n ).then(function() {\n AV.User._currentUserMatchesDisk = true;\n });\n });\n },\n\n _registerAuthenticationProvider: function(provider) {\n AV.User._authProviders[provider.getAuthType()] = provider;\n // Synchronize the current user with the auth provider.\n if (!AV._config.disableCurrentUser && AV.User.current()) {\n AV.User.current()._synchronizeAuthData(provider.getAuthType());\n }\n },\n\n _logInWith: function(provider, options) {\n var user = AV.Object._create(\"_User\");\n return user._linkWith(provider, options);\n }\n\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/user.js","var _ = require('underscore');\nvar Promise = require('../promise');\n\n// interface Storage {\n// readonly attribute boolean async;\n// string getItem(string key);\n// void setItem(string key, string value);\n// void removeItem(string key);\n// void clear();\n// Promise getItemAsync(string key);\n// Promise setItemAsync(string key, string value);\n// Promise removeItemAsync(string key);\n// Promise clearAsync();\n// }\nvar Storage = {};\nvar apiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nvar localStorage = global.localStorage;\n\ntry {\n var testKey = '__storejs__';\n localStorage.setItem(testKey, testKey);\n if (localStorage.getItem(testKey) != testKey) {\n throw new Error();\n }\n localStorage.removeItem(testKey);\n} catch (e) {\n localStorage = require('localstorage-memory');\n}\n\n// in browser, `localStorage.async = false` will excute `localStorage.setItem('async', false)`\n_(apiNames).each(function(apiName) {\n Storage[apiName] = function() {\n return global.localStorage[apiName].apply(global.localStorage, arguments);\n };\n});\nStorage.async = false;\n\nmodule.exports = Storage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/localstorage-browser.js","var dataURItoBlob = function(dataURI, type) {\n var byteString;\n\n // 传入的 base64,不是 dataURL\n if (dataURI.indexOf('base64') < 0) {\n byteString = atob(dataURI);\n } else if (dataURI.split(',')[0].indexOf('base64') >= 0) {\n type = type || dataURI.split(',')[0].split(':')[1].split(';')[0];\n byteString = atob(dataURI.split(',')[1]);\n } else {\n byteString = unescape(dataURI.split(',')[1]);\n }\n var ia = new Uint8Array(byteString.length);\n for (var i = 0; i < byteString.length; i ++) {\n ia[i] = byteString.charCodeAt(i);\n }\n return new Blob([ia], {type});\n};\n\nmodule.exports = dataURItoBlob;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/parse-base64-browser.js","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/component-emitter/index.js\n// module id = 49\n// module chunks = 0","(function() {\n var base64map\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n crypt = {\n // Bit-wise rotation left\n rotl: function(n, b) {\n return (n << b) | (n >>> (32 - b));\n },\n\n // Bit-wise rotation right\n rotr: function(n, b) {\n return (n << (32 - b)) | (n >>> b);\n },\n\n // Swap big-endian to little-endian and vice versa\n endian: function(n) {\n // If number given, swap endian\n if (n.constructor == Number) {\n return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n }\n\n // Else, assume array and swap all items\n for (var i = 0; i < n.length; i++)\n n[i] = crypt.endian(n[i]);\n return n;\n },\n\n // Generate an array of any length of random bytes\n randomBytes: function(n) {\n for (var bytes = []; n > 0; n--)\n bytes.push(Math.floor(Math.random() * 256));\n return bytes;\n },\n\n // Convert a byte array to big-endian 32-bit words\n bytesToWords: function(bytes) {\n for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n words[b >>> 5] |= bytes[i] << (24 - b % 32);\n return words;\n },\n\n // Convert big-endian 32-bit words to a byte array\n wordsToBytes: function(words) {\n for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a hex string\n bytesToHex: function(bytes) {\n for (var hex = [], i = 0; i < bytes.length; i++) {\n hex.push((bytes[i] >>> 4).toString(16));\n hex.push((bytes[i] & 0xF).toString(16));\n }\n return hex.join('');\n },\n\n // Convert a hex string to a byte array\n hexToBytes: function(hex) {\n for (var bytes = [], c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return bytes;\n },\n\n // Convert a byte array to a base-64 string\n bytesToBase64: function(bytes) {\n for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n for (var j = 0; j < 4; j++)\n if (i * 8 + j * 6 <= bytes.length * 8)\n base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n else\n base64.push('=');\n }\n return base64.join('');\n },\n\n // Convert a base-64 string to a byte array\n base64ToBytes: function(base64) {\n // Remove non-base-64 characters\n base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n imod4 = ++i % 4) {\n if (imod4 == 0) continue;\n bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n }\n return bytes;\n }\n };\n\n module.exports = crypt;\n})();\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/crypt/crypt.js\n// module id = 50\n// module chunks = 0","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (namespaces || '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/debug.js\n// module id = 51\n// module chunks = 0","/*!\n * @overview es6-promise - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE\n * @version 4.1.0\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.ES6Promise = factory());\n}(this, (function () { 'use strict';\n\nfunction objectOrFunction(x) {\n return typeof x === 'function' || typeof x === 'object' && x !== null;\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\nvar _isArray = undefined;\nif (!Array.isArray) {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n} else {\n _isArray = Array.isArray;\n}\n\nvar isArray = _isArray;\n\nvar len = 0;\nvar vertxNext = undefined;\nvar customSchedulerFn = undefined;\n\nvar asap = function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 2, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n if (customSchedulerFn) {\n customSchedulerFn(flush);\n } else {\n scheduleFlush();\n }\n }\n};\n\nfunction setScheduler(scheduleFn) {\n customSchedulerFn = scheduleFn;\n}\n\nfunction setAsap(asapFn) {\n asap = asapFn;\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // see https://github.com/cujojs/when/issues/410 for details\n return function () {\n return process.nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n if (typeof vertxNext !== 'undefined') {\n return function () {\n vertxNext(flush);\n };\n }\n\n return useSetTimeout();\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n // Store setTimeout reference so es6-promise will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var globalSetTimeout = setTimeout;\n return function () {\n return globalSetTimeout(flush, 1);\n };\n}\n\nvar queue = new Array(1000);\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n\n callback(arg);\n\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertx() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush = undefined;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush = attemptVertx();\n} else {\n scheduleFlush = useSetTimeout();\n}\n\nfunction then(onFulfillment, onRejection) {\n var _arguments = arguments;\n\n var parent = this;\n\n var child = new this.constructor(noop);\n\n if (child[PROMISE_ID] === undefined) {\n makePromise(child);\n }\n\n var _state = parent._state;\n\n if (_state) {\n (function () {\n var callback = _arguments[_state - 1];\n asap(function () {\n return invokeCallback(_state, child, callback, parent._result);\n });\n })();\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\n/**\n `Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {Any} value value that the returned promise will be resolved with\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve(object) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop);\n _resolve(promise, object);\n return promise;\n}\n\nvar PROMISE_ID = Math.random().toString(36).substring(16);\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nfunction selfFulfillment() {\n return new TypeError(\"You cannot resolve a promise with itself\");\n}\n\nfunction cannotReturnOwn() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then) {\n asap(function (promise) {\n var sealed = false;\n var error = tryThen(then, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n _resolve(promise, value);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n _reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n _reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n _reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n return _resolve(promise, value);\n }, function (reason) {\n return _reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$) {\n if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$ === GET_THEN_ERROR) {\n _reject(promise, GET_THEN_ERROR.error);\n GET_THEN_ERROR.error = null;\n } else if (then$$ === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$)) {\n handleForeignThenable(promise, maybeThenable, then$$);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction _resolve(promise, value) {\n if (promise === value) {\n _reject(promise, selfFulfillment());\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onerror) {\n promise._onerror(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length !== 0) {\n asap(publish, promise);\n }\n}\n\nfunction _reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n\n asap(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var _subscribers = parent._subscribers;\n var length = _subscribers.length;\n\n parent._onerror = null;\n\n _subscribers[length] = child;\n _subscribers[length + FULFILLED] = onFulfillment;\n _subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n asap(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = undefined,\n callback = undefined,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = undefined,\n error = undefined,\n succeeded = undefined,\n failed = undefined;\n\n if (hasCallback) {\n value = tryCatch(callback, detail);\n\n if (value === TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value.error = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n _reject(promise, cannotReturnOwn());\n return;\n }\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n _resolve(promise, value);\n } else if (failed) {\n _reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n _reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n try {\n resolver(function resolvePromise(value) {\n _resolve(promise, value);\n }, function rejectPromise(reason) {\n _reject(promise, reason);\n });\n } catch (e) {\n _reject(promise, e);\n }\n}\n\nvar id = 0;\nfunction nextId() {\n return id++;\n}\n\nfunction makePromise(promise) {\n promise[PROMISE_ID] = id++;\n promise._state = undefined;\n promise._result = undefined;\n promise._subscribers = [];\n}\n\nfunction Enumerator(Constructor, input) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop);\n\n if (!this.promise[PROMISE_ID]) {\n makePromise(this.promise);\n }\n\n if (isArray(input)) {\n this._input = input;\n this.length = input.length;\n this._remaining = input.length;\n\n this._result = new Array(this.length);\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate();\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n _reject(this.promise, validationError());\n }\n}\n\nfunction validationError() {\n return new Error('Array Methods must be provided an Array');\n};\n\nEnumerator.prototype._enumerate = function () {\n var length = this.length;\n var _input = this._input;\n\n for (var i = 0; this._state === PENDING && i < length; i++) {\n this._eachEntry(_input[i], i);\n }\n};\n\nEnumerator.prototype._eachEntry = function (entry, i) {\n var c = this._instanceConstructor;\n var resolve$$ = c.resolve;\n\n if (resolve$$ === resolve) {\n var _then = getThen(entry);\n\n if (_then === then && entry._state !== PENDING) {\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof _then !== 'function') {\n this._remaining--;\n this._result[i] = entry;\n } else if (c === Promise) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, _then);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve$$) {\n return resolve$$(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve$$(entry), i);\n }\n};\n\nEnumerator.prototype._settledAt = function (state, i, value) {\n var promise = this.promise;\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (state === REJECTED) {\n _reject(promise, value);\n } else {\n this._result[i] = value;\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n};\n\nEnumerator.prototype._willSettleAt = function (promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n};\n\n/**\n `Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = resolve(2);\n let promise3 = resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = reject(new Error(\"2\"));\n let promise3 = reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries) {\n return new Enumerator(this, entries).promise;\n}\n\n/**\n `Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} promises array of promises to observe\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (!isArray(entries)) {\n return new Constructor(function (_, reject) {\n return reject(new TypeError('You must pass an array to race.'));\n });\n } else {\n return new Constructor(function (resolve, reject) {\n var length = entries.length;\n for (var i = 0; i < length; i++) {\n Constructor.resolve(entries[i]).then(resolve, reject);\n }\n });\n }\n}\n\n/**\n `Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {Any} reason value that the returned promise will be rejected with.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject(reason) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop);\n _reject(promise, reason);\n return promise;\n}\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise's eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {function} resolver\n Useful for tooling.\n @constructor\n*/\nfunction Promise(resolver) {\n this[PROMISE_ID] = nextId();\n this._result = this._state = undefined;\n this._subscribers = [];\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n}\n\nPromise.all = all;\nPromise.race = race;\nPromise.resolve = resolve;\nPromise.reject = reject;\nPromise._setScheduler = setScheduler;\nPromise._setAsap = setAsap;\nPromise._asap = asap;\n\nPromise.prototype = {\n constructor: Promise,\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n \n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n \n Chaining\n --------\n \n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n \n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n \n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n \n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n \n Assimilation\n ------------\n \n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n \n If the assimliated promise rejects, then the downstream promise will also reject.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n \n Simple Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let result;\n \n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n \n Advanced Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let author, books;\n \n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n \n function foundBooks(books) {\n \n }\n \n function failure(reason) {\n \n }\n \n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n \n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n then: then,\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function _catch(onRejection) {\n return this.then(null, onRejection);\n }\n};\n\nfunction polyfill() {\n var local = undefined;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P) {\n var promiseToString = null;\n try {\n promiseToString = Object.prototype.toString.call(P.resolve());\n } catch (e) {\n // silently ignored\n }\n\n if (promiseToString === '[object Promise]' && !P.cast) {\n return;\n }\n }\n\n local.Promise = Promise;\n}\n\n// Strange compat..\nPromise.polyfill = polyfill;\nPromise.Promise = Promise;\n\nreturn Promise;\n\n})));\n//# sourceMappingURL=es6-promise.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/es6-promise/dist/es6-promise.js\n// module id = 52\n// module chunks = 0","/**\n * @author Toru Nagashima\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n\n\"use strict\";\n\n//-----------------------------------------------------------------------------\n// Requirements\n//-----------------------------------------------------------------------------\n\nvar Commons = require(\"./commons\");\nvar LISTENERS = Commons.LISTENERS;\nvar ATTRIBUTE = Commons.ATTRIBUTE;\nvar newNode = Commons.newNode;\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/**\n * Gets a specified attribute listener from a given EventTarget object.\n *\n * @param {EventTarget} eventTarget - An EventTarget object to get.\n * @param {string} type - An event type to get.\n * @returns {function|null} The found attribute listener.\n */\nfunction getAttributeListener(eventTarget, type) {\n var node = eventTarget[LISTENERS][type];\n while (node != null) {\n if (node.kind === ATTRIBUTE) {\n return node.listener;\n }\n node = node.next;\n }\n return null;\n}\n\n/**\n * Sets a specified attribute listener to a given EventTarget object.\n *\n * @param {EventTarget} eventTarget - An EventTarget object to set.\n * @param {string} type - An event type to set.\n * @param {function|null} listener - A listener to be set.\n * @returns {void}\n */\nfunction setAttributeListener(eventTarget, type, listener) {\n if (typeof listener !== \"function\" && typeof listener !== \"object\") {\n listener = null; // eslint-disable-line no-param-reassign\n }\n\n var prev = null;\n var node = eventTarget[LISTENERS][type];\n while (node != null) {\n if (node.kind === ATTRIBUTE) {\n // Remove old value.\n if (prev == null) {\n eventTarget[LISTENERS][type] = node.next;\n }\n else {\n prev.next = node.next;\n }\n }\n else {\n prev = node;\n }\n\n node = node.next;\n }\n\n // Add new value.\n if (listener != null) {\n if (prev == null) {\n eventTarget[LISTENERS][type] = newNode(listener, ATTRIBUTE);\n }\n else {\n prev.next = newNode(listener, ATTRIBUTE);\n }\n }\n}\n\n//-----------------------------------------------------------------------------\n// Public Interface\n//-----------------------------------------------------------------------------\n\n/**\n * Defines an `EventTarget` implementation which has `onfoobar` attributes.\n *\n * @param {EventTarget} EventTargetBase - A base implementation of EventTarget.\n * @param {string[]} types - A list of event types which are defined as attribute listeners.\n * @returns {EventTarget} The defined `EventTarget` implementation which has attribute listeners.\n */\nexports.defineCustomEventTarget = function(EventTargetBase, types) {\n function EventTarget() {\n EventTargetBase.call(this);\n }\n\n var descripter = {\n constructor: {\n value: EventTarget,\n configurable: true,\n writable: true\n }\n };\n\n types.forEach(function(type) {\n descripter[\"on\" + type] = {\n get: function() { return getAttributeListener(this, type); },\n set: function(listener) { setAttributeListener(this, type, listener); },\n configurable: true,\n enumerable: true\n };\n });\n\n EventTarget.prototype = Object.create(EventTargetBase.prototype, descripter);\n\n return EventTarget;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/event-target-shim/lib/custom-event-target.js\n// module id = 53\n// module chunks = 0","/**\n * @author Toru Nagashima\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n\n\"use strict\";\n\n//-----------------------------------------------------------------------------\n// Requirements\n//-----------------------------------------------------------------------------\n\nvar createUniqueKey = require(\"./commons\").createUniqueKey;\n\n//-----------------------------------------------------------------------------\n// Constsnts\n//-----------------------------------------------------------------------------\n\n/**\n * The key of the flag which is turned on by `stopImmediatePropagation` method.\n *\n * @type {symbol|string}\n * @private\n */\nvar STOP_IMMEDIATE_PROPAGATION_FLAG =\n createUniqueKey(\"stop_immediate_propagation_flag\");\n\n/**\n * The key of the flag which is turned on by `preventDefault` method.\n *\n * @type {symbol|string}\n * @private\n */\nvar CANCELED_FLAG = createUniqueKey(\"canceled_flag\");\n\n/**\n * The key of the original event object.\n *\n * @type {symbol|string}\n * @private\n */\nvar ORIGINAL_EVENT = createUniqueKey(\"original_event\");\n\n/**\n * Method definitions for the event wrapper.\n *\n * @type {object}\n * @private\n */\nvar wrapperPrototypeDefinition = Object.freeze({\n stopPropagation: Object.freeze({\n value: function stopPropagation() {\n var e = this[ORIGINAL_EVENT];\n if (typeof e.stopPropagation === \"function\") {\n e.stopPropagation();\n }\n },\n writable: true,\n configurable: true\n }),\n\n stopImmediatePropagation: Object.freeze({\n value: function stopImmediatePropagation() {\n this[STOP_IMMEDIATE_PROPAGATION_FLAG] = true;\n\n var e = this[ORIGINAL_EVENT];\n if (typeof e.stopImmediatePropagation === \"function\") {\n e.stopImmediatePropagation();\n }\n },\n writable: true,\n configurable: true\n }),\n\n preventDefault: Object.freeze({\n value: function preventDefault() {\n if (this.cancelable === true) {\n this[CANCELED_FLAG] = true;\n }\n\n var e = this[ORIGINAL_EVENT];\n if (typeof e.preventDefault === \"function\") {\n e.preventDefault();\n }\n },\n writable: true,\n configurable: true\n }),\n\n defaultPrevented: Object.freeze({\n get: function defaultPrevented() { return this[CANCELED_FLAG]; },\n enumerable: true,\n configurable: true\n })\n});\n\n//-----------------------------------------------------------------------------\n// Public Interface\n//-----------------------------------------------------------------------------\n\nexports.STOP_IMMEDIATE_PROPAGATION_FLAG = STOP_IMMEDIATE_PROPAGATION_FLAG;\n\n/**\n * Creates an event wrapper.\n *\n * We cannot modify several properties of `Event` object, so we need to create the wrapper.\n * Plus, this wrapper supports non `Event` objects.\n *\n * @param {Event|{type: string}} event - An original event to create the wrapper.\n * @param {EventTarget} eventTarget - The event target of the event.\n * @returns {Event} The created wrapper. This object is implemented `Event` interface.\n * @private\n */\nexports.createEventWrapper = function createEventWrapper(event, eventTarget) {\n var timeStamp = (\n typeof event.timeStamp === \"number\" ? event.timeStamp : Date.now()\n );\n var propertyDefinition = {\n type: {value: event.type, enumerable: true},\n target: {value: eventTarget, enumerable: true},\n currentTarget: {value: eventTarget, enumerable: true},\n eventPhase: {value: 2, enumerable: true},\n bubbles: {value: Boolean(event.bubbles), enumerable: true},\n cancelable: {value: Boolean(event.cancelable), enumerable: true},\n timeStamp: {value: timeStamp, enumerable: true},\n isTrusted: {value: false, enumerable: true}\n };\n propertyDefinition[STOP_IMMEDIATE_PROPAGATION_FLAG] = {value: false, writable: true};\n propertyDefinition[CANCELED_FLAG] = {value: false, writable: true};\n propertyDefinition[ORIGINAL_EVENT] = {value: event};\n\n // For CustomEvent.\n if (typeof event.detail !== \"undefined\") {\n propertyDefinition.detail = {value: event.detail, enumerable: true};\n }\n\n return Object.create(\n Object.create(event, wrapperPrototypeDefinition),\n propertyDefinition\n );\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/event-target-shim/lib/event-wrapper.js\n// module id = 54\n// module chunks = 0","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/is-buffer/index.js\n// module id = 55\n// module chunks = 0","(function(root) {\n var localStorageMemory = {};\n var cache = {};\n\n /**\n * number of stored items.\n */\n localStorageMemory.length = 0;\n\n /**\n * returns item for passed key, or null\n *\n * @para {String} key\n * name of item to be returned\n * @returns {String|null}\n */\n localStorageMemory.getItem = function(key) {\n return cache[key] || null;\n };\n\n /**\n * sets item for key to passed value, as String\n *\n * @para {String} key\n * name of item to be set\n * @para {String} value\n * value, will always be turned into a String\n * @returns {undefined}\n */\n localStorageMemory.setItem = function(key, value) {\n if (typeof value === 'undefined') {\n localStorageMemory.removeItem(key);\n } else {\n if (!(cache.hasOwnProperty(key))) {\n localStorageMemory.length++;\n }\n\n cache[key] = '' + value;\n }\n };\n\n /**\n * removes item for passed key\n *\n * @para {String} key\n * name of item to be removed\n * @returns {undefined}\n */\n localStorageMemory.removeItem = function(key) {\n if (cache.hasOwnProperty(key)) {\n delete cache[key];\n localStorageMemory.length--;\n }\n };\n\n /**\n * returns name of key at passed index\n *\n * @para {Number} index\n * Position for key to be returned (starts at 0)\n * @returns {String|null}\n */\n localStorageMemory.key = function(index) {\n return Object.keys(cache)[index] || null;\n };\n\n /**\n * removes all stored items and sets length to 0\n *\n * @returns {undefined}\n */\n localStorageMemory.clear = function() {\n cache = {};\n localStorageMemory.length = 0;\n };\n\n if (typeof exports === 'object') {\n module.exports = localStorageMemory;\n } else {\n root.localStorageMemory = localStorageMemory;\n }\n})(this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/localstorage-memory/lib/localstorage-memory.js\n// module id = 56\n// module chunks = 0","(function(){\r\n var crypt = require('crypt'),\r\n utf8 = require('charenc').utf8,\r\n isBuffer = require('is-buffer'),\r\n bin = require('charenc').bin,\r\n\r\n // The core\r\n md5 = function (message, options) {\r\n // Convert to byte array\r\n if (message.constructor == String)\r\n if (options && options.encoding === 'binary')\r\n message = bin.stringToBytes(message);\r\n else\r\n message = utf8.stringToBytes(message);\r\n else if (isBuffer(message))\r\n message = Array.prototype.slice.call(message, 0);\r\n else if (!Array.isArray(message))\r\n message = message.toString();\r\n // else, assume byte array already\r\n\r\n var m = crypt.bytesToWords(message),\r\n l = message.length * 8,\r\n a = 1732584193,\r\n b = -271733879,\r\n c = -1732584194,\r\n d = 271733878;\r\n\r\n // Swap endian\r\n for (var i = 0; i < m.length; i++) {\r\n m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;\r\n }\r\n\r\n // Padding\r\n m[l >>> 5] |= 0x80 << (l % 32);\r\n m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n // Method shortcuts\r\n var FF = md5._ff,\r\n GG = md5._gg,\r\n HH = md5._hh,\r\n II = md5._ii;\r\n\r\n for (var i = 0; i < m.length; i += 16) {\r\n\r\n var aa = a,\r\n bb = b,\r\n cc = c,\r\n dd = d;\r\n\r\n a = FF(a, b, c, d, m[i+ 0], 7, -680876936);\r\n d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n c = FF(c, d, a, b, m[i+ 2], 17, 606105819);\r\n b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n a = FF(a, b, c, d, m[i+ 4], 7, -176418897);\r\n d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);\r\n c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);\r\n d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n a = FF(a, b, c, d, m[i+12], 7, 1804603682);\r\n d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n b = FF(b, c, d, a, m[i+15], 22, 1236535329);\r\n\r\n a = GG(a, b, c, d, m[i+ 1], 5, -165796510);\r\n d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);\r\n c = GG(c, d, a, b, m[i+11], 14, 643717713);\r\n b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n a = GG(a, b, c, d, m[i+ 5], 5, -701558691);\r\n d = GG(d, a, b, c, m[i+10], 9, 38016083);\r\n c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n a = GG(a, b, c, d, m[i+ 9], 5, 568446438);\r\n d = GG(d, a, b, c, m[i+14], 9, -1019803690);\r\n c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);\r\n a = GG(a, b, c, d, m[i+13], 5, -1444681467);\r\n d = GG(d, a, b, c, m[i+ 2], 9, -51403784);\r\n c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);\r\n b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n a = HH(a, b, c, d, m[i+ 5], 4, -378558);\r\n d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n c = HH(c, d, a, b, m[i+11], 16, 1839030562);\r\n b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);\r\n d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);\r\n c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n a = HH(a, b, c, d, m[i+13], 4, 681279174);\r\n d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n b = HH(b, c, d, a, m[i+ 6], 23, 76029189);\r\n a = HH(a, b, c, d, m[i+ 9], 4, -640364487);\r\n d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n c = HH(c, d, a, b, m[i+15], 16, 530742520);\r\n b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n a = II(a, b, c, d, m[i+ 0], 6, -198630844);\r\n d = II(d, a, b, c, m[i+ 7], 10, 1126891415);\r\n c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n a = II(a, b, c, d, m[i+12], 6, 1700485571);\r\n d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n a = II(a, b, c, d, m[i+ 8], 6, 1873313359);\r\n d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n b = II(b, c, d, a, m[i+13], 21, 1309151649);\r\n a = II(a, b, c, d, m[i+ 4], 6, -145523070);\r\n d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n c = II(c, d, a, b, m[i+ 2], 15, 718787259);\r\n b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n a = (a + aa) >>> 0;\r\n b = (b + bb) >>> 0;\r\n c = (c + cc) >>> 0;\r\n d = (d + dd) >>> 0;\r\n }\r\n\r\n return crypt.endian([a, b, c, d]);\r\n };\r\n\r\n // Auxiliary functions\r\n md5._ff = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._gg = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._hh = function (a, b, c, d, x, s, t) {\r\n var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._ii = function (a, b, c, d, x, s, t) {\r\n var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n\r\n // Package private blocksize\r\n md5._blocksize = 16;\r\n md5._digestsize = 16;\r\n\r\n module.exports = function (message, options) {\r\n if (message === undefined || message === null)\r\n throw new Error('Illegal argument ' + message);\r\n\r\n var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n return options && options.asBytes ? digestbytes :\r\n options && options.asString ? bin.bytesToString(digestbytes) :\r\n crypt.bytesToHex(digestbytes);\r\n };\r\n\r\n})();\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/md5/md5.js\n// module id = 57\n// module chunks = 0","/**\n * Helpers.\n */\n\nvar s = 1000\nvar m = s * 60\nvar h = m * 60\nvar d = h * 24\nvar y = d * 365.25\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} options\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {}\n var type = typeof val\n if (type === 'string' && val.length > 0) {\n return parse(val)\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ?\n\t\t\tfmtLong(val) :\n\t\t\tfmtShort(val)\n }\n throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))\n}\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str)\n if (str.length > 10000) {\n return\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)\n if (!match) {\n return\n }\n var n = parseFloat(match[1])\n var type = (match[2] || 'ms').toLowerCase()\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y\n case 'days':\n case 'day':\n case 'd':\n return n * d\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n\n default:\n return undefined\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd'\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h'\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm'\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's'\n }\n return ms + 'ms'\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms'\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name\n }\n return Math.ceil(ms / n) + ' ' + name + 's'\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ms/index.js\n// module id = 58\n// module chunks = 0","/**\n * Check if `fn` is a function.\n *\n * @param {Function} fn\n * @return {Boolean}\n * @api private\n */\nvar isObject = require('./is-object');\n\nfunction isFunction(fn) {\n var tag = isObject(fn) ? Object.prototype.toString.call(fn) : '';\n return tag === '[object Function]';\n}\n\nmodule.exports = isFunction;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-function.js\n// module id = 59\n// module chunks = 0","/**\n * Module of mixed-in functions shared between node and client code\n */\nvar isObject = require('./is-object');\n\n/**\n * Expose `RequestBase`.\n */\n\nmodule.exports = RequestBase;\n\n/**\n * Initialize a new `RequestBase`.\n *\n * @api public\n */\n\nfunction RequestBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in RequestBase.prototype) {\n obj[key] = RequestBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Clear previous timeout.\n *\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.clearTimeout = function _clearTimeout(){\n clearTimeout(this._timer);\n clearTimeout(this._responseTimeoutTimer);\n delete this._timer;\n delete this._responseTimeoutTimer;\n return this;\n};\n\n/**\n * Override default response body parser\n *\n * This function will be called to convert incoming data into request.body\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.parse = function parse(fn){\n this._parser = fn;\n return this;\n};\n\n/**\n * Set format of binary response body.\n * In browser valid formats are 'blob' and 'arraybuffer',\n * which return Blob and ArrayBuffer, respectively.\n *\n * In Node all values result in Buffer.\n *\n * Examples:\n *\n * req.get('/')\n * .responseType('blob')\n * .end(callback);\n *\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.responseType = function(val){\n this._responseType = val;\n return this;\n};\n\n/**\n * Override default request body serializer\n *\n * This function will be called to convert data set via .send or .attach into payload to send\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.serialize = function serialize(fn){\n this._serializer = fn;\n return this;\n};\n\n/**\n * Set timeouts.\n *\n * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.\n * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.\n *\n * Value of 0 or false means no timeout.\n *\n * @param {Number|Object} ms or {response, read, deadline}\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.timeout = function timeout(options){\n if (!options || 'object' !== typeof options) {\n this._timeout = options;\n this._responseTimeout = 0;\n return this;\n }\n\n for(var option in options) {\n switch(option) {\n case 'deadline':\n this._timeout = options.deadline;\n break;\n case 'response':\n this._responseTimeout = options.response;\n break;\n default:\n console.warn(\"Unknown timeout option\", option);\n }\n }\n return this;\n};\n\n/**\n * Set number of retry attempts on error.\n *\n * Failed requests will be retried 'count' times if timeout or err.code >= 500.\n *\n * @param {Number} count\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.retry = function retry(count){\n // Default to 1 if no count passed or true\n if (arguments.length === 0 || count === true) count = 1;\n if (count <= 0) count = 0;\n this._maxRetries = count;\n this._retries = 0;\n return this;\n};\n\n/**\n * Retry request\n *\n * @return {Request} for chaining\n * @api private\n */\n\nRequestBase.prototype._retry = function() {\n this.clearTimeout();\n\n // node\n if (this.req) {\n this.req = null;\n this.req = this.request();\n }\n\n this._aborted = false;\n this.timedout = false;\n\n return this._end();\n};\n\n/**\n * Promise support\n *\n * @param {Function} resolve\n * @param {Function} [reject]\n * @return {Request}\n */\n\nRequestBase.prototype.then = function then(resolve, reject) {\n if (!this._fullfilledPromise) {\n var self = this;\n if (this._endCalled) {\n console.warn(\"Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises\");\n }\n this._fullfilledPromise = new Promise(function(innerResolve, innerReject){\n self.end(function(err, res){\n if (err) innerReject(err); else innerResolve(res);\n });\n });\n }\n return this._fullfilledPromise.then(resolve, reject);\n}\n\nRequestBase.prototype.catch = function(cb) {\n return this.then(undefined, cb);\n};\n\n/**\n * Allow for extension\n */\n\nRequestBase.prototype.use = function use(fn) {\n fn(this);\n return this;\n}\n\nRequestBase.prototype.ok = function(cb) {\n if ('function' !== typeof cb) throw Error(\"Callback required\");\n this._okCallback = cb;\n return this;\n};\n\nRequestBase.prototype._isResponseOK = function(res) {\n if (!res) {\n return false;\n }\n\n if (this._okCallback) {\n return this._okCallback(res);\n }\n\n return res.status >= 200 && res.status < 300;\n};\n\n\n/**\n * Get request header `field`.\n * Case-insensitive.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nRequestBase.prototype.get = function(field){\n return this._header[field.toLowerCase()];\n};\n\n/**\n * Get case-insensitive header `field` value.\n * This is a deprecated internal API. Use `.get(field)` instead.\n *\n * (getHeader is no longer used internally by the superagent code base)\n *\n * @param {String} field\n * @return {String}\n * @api private\n * @deprecated\n */\n\nRequestBase.prototype.getHeader = RequestBase.prototype.get;\n\n/**\n * Set header `field` to `val`, or multiple fields with one object.\n * Case-insensitive.\n *\n * Examples:\n *\n * req.get('/')\n * .set('Accept', 'application/json')\n * .set('X-API-Key', 'foobar')\n * .end(callback);\n *\n * req.get('/')\n * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })\n * .end(callback);\n *\n * @param {String|Object} field\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.set = function(field, val){\n if (isObject(field)) {\n for (var key in field) {\n this.set(key, field[key]);\n }\n return this;\n }\n this._header[field.toLowerCase()] = val;\n this.header[field] = val;\n return this;\n};\n\n/**\n * Remove header `field`.\n * Case-insensitive.\n *\n * Example:\n *\n * req.get('/')\n * .unset('User-Agent')\n * .end(callback);\n *\n * @param {String} field\n */\nRequestBase.prototype.unset = function(field){\n delete this._header[field.toLowerCase()];\n delete this.header[field];\n return this;\n};\n\n/**\n * Write the field `name` and `val`, or multiple fields with one object\n * for \"multipart/form-data\" request bodies.\n *\n * ``` js\n * request.post('/upload')\n * .field('foo', 'bar')\n * .end(callback);\n *\n * request.post('/upload')\n * .field({ foo: 'bar', baz: 'qux' })\n * .end(callback);\n * ```\n *\n * @param {String|Object} name\n * @param {String|Blob|File|Buffer|fs.ReadStream} val\n * @return {Request} for chaining\n * @api public\n */\nRequestBase.prototype.field = function(name, val) {\n\n // name should be either a string or an object.\n if (null === name || undefined === name) {\n throw new Error('.field(name, val) name can not be empty');\n }\n\n if (this._data) {\n console.error(\".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObject(name)) {\n for (var key in name) {\n this.field(key, name[key]);\n }\n return this;\n }\n\n if (Array.isArray(val)) {\n for (var i in val) {\n this.field(name, val[i]);\n }\n return this;\n }\n\n // val should be defined now\n if (null === val || undefined === val) {\n throw new Error('.field(name, val) val can not be empty');\n }\n if ('boolean' === typeof val) {\n val = '' + val;\n }\n this._getFormData().append(name, val);\n return this;\n};\n\n/**\n * Abort the request, and clear potential timeout.\n *\n * @return {Request}\n * @api public\n */\nRequestBase.prototype.abort = function(){\n if (this._aborted) {\n return this;\n }\n this._aborted = true;\n this.xhr && this.xhr.abort(); // browser\n this.req && this.req.abort(); // node\n this.clearTimeout();\n this.emit('abort');\n return this;\n};\n\n/**\n * Enable transmission of cookies with x-domain requests.\n *\n * Note that for this to work the origin must not be\n * using \"Access-Control-Allow-Origin\" with a wildcard,\n * and also must set \"Access-Control-Allow-Credentials\"\n * to \"true\".\n *\n * @api public\n */\n\nRequestBase.prototype.withCredentials = function(on){\n // This is browser-only functionality. Node side is no-op.\n if(on==undefined) on = true;\n this._withCredentials = on;\n return this;\n};\n\n/**\n * Set the max redirects to `n`. Does noting in browser XHR implementation.\n *\n * @param {Number} n\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.redirects = function(n){\n this._maxRedirects = n;\n return this;\n};\n\n/**\n * Convert to a plain javascript object (not JSON string) of scalar properties.\n * Note as this method is designed to return a useful non-this value,\n * it cannot be chained.\n *\n * @return {Object} describing method, url, and data of this request\n * @api public\n */\n\nRequestBase.prototype.toJSON = function(){\n return {\n method: this.method,\n url: this.url,\n data: this._data,\n headers: this._header\n };\n};\n\n\n/**\n * Send `data` as the request body, defaulting the `.type()` to \"json\" when\n * an object is given.\n *\n * Examples:\n *\n * // manual json\n * request.post('/user')\n * .type('json')\n * .send('{\"name\":\"tj\"}')\n * .end(callback)\n *\n * // auto json\n * request.post('/user')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // manual x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send('name=tj')\n * .end(callback)\n *\n * // auto x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // defaults to x-www-form-urlencoded\n * request.post('/user')\n * .send('name=tobi')\n * .send('species=ferret')\n * .end(callback)\n *\n * @param {String|Object} data\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.send = function(data){\n var isObj = isObject(data);\n var type = this._header['content-type'];\n\n if (this._formData) {\n console.error(\".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObj && !this._data) {\n if (Array.isArray(data)) {\n this._data = [];\n } else if (!this._isHost(data)) {\n this._data = {};\n }\n } else if (data && this._data && this._isHost(this._data)) {\n throw Error(\"Can't merge these send calls\");\n }\n\n // merge\n if (isObj && isObject(this._data)) {\n for (var key in data) {\n this._data[key] = data[key];\n }\n } else if ('string' == typeof data) {\n // default to x-www-form-urlencoded\n if (!type) this.type('form');\n type = this._header['content-type'];\n if ('application/x-www-form-urlencoded' == type) {\n this._data = this._data\n ? this._data + '&' + data\n : data;\n } else {\n this._data = (this._data || '') + data;\n }\n } else {\n this._data = data;\n }\n\n if (!isObj || this._isHost(data)) {\n return this;\n }\n\n // default to json\n if (!type) this.type('json');\n return this;\n};\n\n\n/**\n * Sort `querystring` by the sort function\n *\n *\n * Examples:\n *\n * // default order\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery()\n * .end(callback)\n *\n * // customized sort function\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery(function(a, b){\n * return a.length - b.length;\n * })\n * .end(callback)\n *\n *\n * @param {Function} sort\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.sortQuery = function(sort) {\n // _sort default to true but otherwise can be a function or boolean\n this._sort = typeof sort === 'undefined' ? true : sort;\n return this;\n};\n\n/**\n * Invoke callback with timeout error.\n *\n * @api private\n */\n\nRequestBase.prototype._timeoutError = function(reason, timeout, errno){\n if (this._aborted) {\n return;\n }\n var err = new Error(reason + timeout + 'ms exceeded');\n err.timeout = timeout;\n err.code = 'ECONNABORTED';\n err.errno = errno;\n this.timedout = true;\n this.abort();\n this.callback(err);\n};\n\nRequestBase.prototype._setTimeouts = function() {\n var self = this;\n\n // deadline\n if (this._timeout && !this._timer) {\n this._timer = setTimeout(function(){\n self._timeoutError('Timeout of ', self._timeout, 'ETIME');\n }, this._timeout);\n }\n // response timeout\n if (this._responseTimeout && !this._responseTimeoutTimer) {\n this._responseTimeoutTimer = setTimeout(function(){\n self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');\n }, this._responseTimeout);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/request-base.js\n// module id = 60\n// module chunks = 0","\n/**\n * Module dependencies.\n */\n\nvar utils = require('./utils');\n\n/**\n * Expose `ResponseBase`.\n */\n\nmodule.exports = ResponseBase;\n\n/**\n * Initialize a new `ResponseBase`.\n *\n * @api public\n */\n\nfunction ResponseBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in ResponseBase.prototype) {\n obj[key] = ResponseBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Get case-insensitive `field` value.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nResponseBase.prototype.get = function(field){\n return this.header[field.toLowerCase()];\n};\n\n/**\n * Set header related properties:\n *\n * - `.type` the content type without params\n *\n * A response of \"Content-Type: text/plain; charset=utf-8\"\n * will provide you with a `.type` of \"text/plain\".\n *\n * @param {Object} header\n * @api private\n */\n\nResponseBase.prototype._setHeaderProperties = function(header){\n // TODO: moar!\n // TODO: make this a util\n\n // content-type\n var ct = header['content-type'] || '';\n this.type = utils.type(ct);\n\n // params\n var params = utils.params(ct);\n for (var key in params) this[key] = params[key];\n\n this.links = {};\n\n // links\n try {\n if (header.link) {\n this.links = utils.parseLinks(header.link);\n }\n } catch (err) {\n // ignore\n }\n};\n\n/**\n * Set flags such as `.ok` based on `status`.\n *\n * For example a 2xx response will give you a `.ok` of __true__\n * whereas 5xx will be __false__ and `.error` will be __true__. The\n * `.clientError` and `.serverError` are also available to be more\n * specific, and `.statusType` is the class of error ranging from 1..5\n * sometimes useful for mapping respond colors etc.\n *\n * \"sugar\" properties are also defined for common cases. Currently providing:\n *\n * - .noContent\n * - .badRequest\n * - .unauthorized\n * - .notAcceptable\n * - .notFound\n *\n * @param {Number} status\n * @api private\n */\n\nResponseBase.prototype._setStatusProperties = function(status){\n var type = status / 100 | 0;\n\n // status / class\n this.status = this.statusCode = status;\n this.statusType = type;\n\n // basics\n this.info = 1 == type;\n this.ok = 2 == type;\n this.redirect = 3 == type;\n this.clientError = 4 == type;\n this.serverError = 5 == type;\n this.error = (4 == type || 5 == type)\n ? this.toError()\n : false;\n\n // sugar\n this.accepted = 202 == status;\n this.noContent = 204 == status;\n this.badRequest = 400 == status;\n this.unauthorized = 401 == status;\n this.notAcceptable = 406 == status;\n this.forbidden = 403 == status;\n this.notFound = 404 == status;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/response-base.js\n// module id = 61\n// module chunks = 0","var ERROR_CODES = [\n 'ECONNRESET',\n 'ETIMEDOUT',\n 'EADDRINFO',\n 'ESOCKETTIMEDOUT'\n];\n\n/**\n * Determine if a request should be retried.\n * (Borrowed from segmentio/superagent-retry)\n *\n * @param {Error} err\n * @param {Response} [res]\n * @returns {Boolean}\n */\nmodule.exports = function shouldRetry(err, res) {\n if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true;\n if (res && res.status && res.status >= 500) return true;\n // Superagent timeout\n if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true;\n if (err && 'crossDomain' in err) return true;\n return false;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/should-retry.js\n// module id = 62\n// module chunks = 0","\n/**\n * Return the mime type for the given `str`.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nexports.type = function(str){\n return str.split(/ *; */).shift();\n};\n\n/**\n * Return header field parameters.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.params = function(str){\n return str.split(/ *; */).reduce(function(obj, str){\n var parts = str.split(/ *= */);\n var key = parts.shift();\n var val = parts.shift();\n\n if (key && val) obj[key] = val;\n return obj;\n }, {});\n};\n\n/**\n * Parse Link header fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.parseLinks = function(str){\n return str.split(/ *, */).reduce(function(obj, str){\n var parts = str.split(/ *; */);\n var url = parts[0].slice(1, -1);\n var rel = parts[1].split(/ *= */)[1].slice(1, -1);\n obj[rel] = url;\n return obj;\n }, {});\n};\n\n/**\n * Strip content related fields from `header`.\n *\n * @param {Object} header\n * @return {Object} header\n * @api private\n */\n\nexports.cleanHeader = function(header, shouldStripCookie){\n delete header['content-type'];\n delete header['content-length'];\n delete header['transfer-encoding'];\n delete header['host'];\n if (shouldStripCookie) {\n delete header['cookie'];\n }\n return header;\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/utils.js\n// module id = 63\n// module chunks = 0"]} \ No newline at end of file diff --git a/dist/av-weapp.js b/dist/av-weapp.js new file mode 100644 index 000000000..709bbbb54 --- /dev/null +++ b/dist/av-weapp.js @@ -0,0 +1,15312 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["AV"] = factory(); + else + root["AV"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 30); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Underscore.js 1.8.3 +// http://underscorejs.org +// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `exports` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var + push = ArrayProto.push, + slice = ArrayProto.slice, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind, + nativeCreate = Object.create; + + // Naked function reference for surrogate-prototype-swapping. + var Ctor = function(){}; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object. + if (true) { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.8.3'; + + // Internal function that returns an efficient (for current engines) version + // of the passed-in callback, to be repeatedly applied in other Underscore + // functions. + var optimizeCb = function(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 2: return function(value, other) { + return func.call(context, value, other); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; + } + return function() { + return func.apply(context, arguments); + }; + }; + + // A mostly-internal function to generate callbacks that can be applied + // to each element in a collection, returning the desired result — either + // identity, an arbitrary callback, a property matcher, or a property accessor. + var cb = function(value, context, argCount) { + if (value == null) return _.identity; + if (_.isFunction(value)) return optimizeCb(value, context, argCount); + if (_.isObject(value)) return _.matcher(value); + return _.property(value); + }; + _.iteratee = function(value, context) { + return cb(value, context, Infinity); + }; + + // An internal function for creating assigner functions. + var createAssigner = function(keysFunc, undefinedOnly) { + return function(obj) { + var length = arguments.length; + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + } + } + return obj; + }; + }; + + // An internal function for creating a new object that inherits from another. + var baseCreate = function(prototype) { + if (!_.isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + Ctor.prototype = prototype; + var result = new Ctor; + Ctor.prototype = null; + return result; + }; + + var property = function(key) { + return function(obj) { + return obj == null ? void 0 : obj[key]; + }; + }; + + // Helper for collection methods to determine whether a collection + // should be iterated as an array or as an object + // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength + // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; + var getLength = property('length'); + var isArrayLike = function(collection) { + var length = getLength(collection); + return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; + }; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles raw objects in addition to array-likes. Treats all + // sparse array-likes as if they were dense. + _.each = _.forEach = function(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var keys = _.keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + iteratee(obj[keys[i]], keys[i], obj); + } + } + return obj; + }; + + // Return the results of applying the iteratee to each element. + _.map = _.collect = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + results = Array(length); + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Create a reducing function iterating left or right. + function createReduce(dir) { + // Optimized iterator function as using arguments.length + // in the main function will deoptimize the, see #1991. + function iterator(obj, iteratee, memo, keys, index, length) { + for (; index >= 0 && index < length; index += dir) { + var currentKey = keys ? keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + } + + return function(obj, iteratee, memo, context) { + iteratee = optimizeCb(iteratee, context, 4); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + index = dir > 0 ? 0 : length - 1; + // Determine the initial value if none is provided. + if (arguments.length < 3) { + memo = obj[keys ? keys[index] : index]; + index += dir; + } + return iterator(obj, iteratee, memo, keys, index, length); + }; + } + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. + _.reduce = _.foldl = _.inject = createReduce(1); + + // The right-associative version of reduce, also known as `foldr`. + _.reduceRight = _.foldr = createReduce(-1); + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, predicate, context) { + var key; + if (isArrayLike(obj)) { + key = _.findIndex(obj, predicate, context); + } else { + key = _.findKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) return obj[key]; + }; + + // Return all the elements that pass a truth test. + // Aliased as `select`. + _.filter = _.select = function(obj, predicate, context) { + var results = []; + predicate = cb(predicate, context); + _.each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, predicate, context) { + return _.filter(obj, _.negate(cb(predicate)), context); + }; + + // Determine whether all of the elements match a truth test. + // Aliased as `all`. + _.every = _.all = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; + } + return true; + }; + + // Determine if at least one element in the object matches a truth test. + // Aliased as `any`. + _.some = _.any = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; + } + return false; + }; + + // Determine if the array or object contains a given item (using `===`). + // Aliased as `includes` and `include`. + _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + if (typeof fromIndex != 'number' || guard) fromIndex = 0; + return _.indexOf(obj, item, fromIndex) >= 0; + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + var func = isFunc ? method : value[method]; + return func == null ? func : func.apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, _.property(key)); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // containing specific `key:value` pairs. + _.where = function(obj, attrs) { + return _.filter(obj, _.matcher(attrs)); + }; + + // Convenience version of a common use case of `find`: getting the first object + // containing specific `key:value` pairs. + _.findWhere = function(obj, attrs) { + return _.find(obj, _.matcher(attrs)); + }; + + // Return the maximum element (or element-based computation). + _.max = function(obj, iteratee, context) { + var result = -Infinity, lastComputed = -Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value > result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed > lastComputed || computed === -Infinity && result === -Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed < lastComputed || computed === Infinity && result === Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Shuffle a collection, using the modern version of the + // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). + _.shuffle = function(obj) { + var set = isArrayLike(obj) ? obj : _.values(obj); + var length = set.length; + var shuffled = Array(length); + for (var index = 0, rand; index < length; index++) { + rand = _.random(0, index); + if (rand !== index) shuffled[index] = shuffled[rand]; + shuffled[rand] = set[index]; + } + return shuffled; + }; + + // Sample **n** random values from a collection. + // If **n** is not specified, returns a single random element. + // The internal `guard` argument allows it to work with `map`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + return _.shuffle(obj).slice(0, Math.max(0, n)); + }; + + // Sort the object's values by a criterion produced by an iteratee. + _.sortBy = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iteratee(value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iteratee, context) { + var result = {}; + iteratee = cb(iteratee, context); + _.each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + return result; + }; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = group(function(result, value, key) { + if (_.has(result, key)) result[key].push(value); else result[key] = [value]; + }); + + // Indexes the object's values by a criterion, similar to `groupBy`, but for + // when you know that your index values will be unique. + _.indexBy = group(function(result, value, key) { + result[key] = value; + }); + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = group(function(result, value, key) { + if (_.has(result, key)) result[key]++; else result[key] = 1; + }); + + // Safely create a real, live array from anything iterable. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); + if (isArrayLike(obj)) return _.map(obj, _.identity); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return isArrayLike(obj) ? obj.length : _.keys(obj).length; + }; + + // Split a collection into two arrays: one whose elements all satisfy the given + // predicate, and one whose elements all do not satisfy the predicate. + _.partition = function(obj, predicate, context) { + predicate = cb(predicate, context); + var pass = [], fail = []; + _.each(obj, function(value, key, obj) { + (predicate(value, key, obj) ? pass : fail).push(value); + }); + return [pass, fail]; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head` and `take`. The **guard** check + // allows it to work with `_.map`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[0]; + return _.initial(array, array.length - n); + }; + + // Returns everything but the last entry of the array. Especially useful on + // the arguments object. Passing **n** will return all the values in + // the array, excluding the last N. + _.initial = function(array, n, guard) { + return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); + }; + + // Get the last element of an array. Passing **n** will return the last N + // values in the array. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[array.length - 1]; + return _.rest(array, Math.max(0, array.length - n)); + }; + + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. + // Especially useful on the arguments object. Passing an **n** will return + // the rest N values in the array. + _.rest = _.tail = _.drop = function(array, n, guard) { + return slice.call(array, n == null || guard ? 1 : n); + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, _.identity); + }; + + // Internal implementation of a recursive `flatten` function. + var flatten = function(input, shallow, strict, startIndex) { + var output = [], idx = 0; + for (var i = startIndex || 0, length = getLength(input); i < length; i++) { + var value = input[i]; + if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { + //flatten current level of array or arguments object + if (!shallow) value = flatten(value, shallow, strict); + var j = 0, len = value.length; + output.length += len; + while (j < len) { + output[idx++] = value[j++]; + } + } else if (!strict) { + output[idx++] = value; + } + } + return output; + }; + + // Flatten out an array, either recursively (by default), or just one level. + _.flatten = function(array, shallow) { + return flatten(array, shallow, false); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted, iteratee, context) { + if (!_.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + if (iteratee != null) iteratee = cb(iteratee, context); + var result = []; + var seen = []; + for (var i = 0, length = getLength(array); i < length; i++) { + var value = array[i], + computed = iteratee ? iteratee(value, i, array) : value; + if (isSorted) { + if (!i || seen !== computed) result.push(value); + seen = computed; + } else if (iteratee) { + if (!_.contains(seen, computed)) { + seen.push(computed); + result.push(value); + } + } else if (!_.contains(result, value)) { + result.push(value); + } + } + return result; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(flatten(arguments, true, true)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var result = []; + var argsLength = arguments.length; + for (var i = 0, length = getLength(array); i < length; i++) { + var item = array[i]; + if (_.contains(result, item)) continue; + for (var j = 1; j < argsLength; j++) { + if (!_.contains(arguments[j], item)) break; + } + if (j === argsLength) result.push(item); + } + return result; + }; + + // Take the difference between one array and a number of other arrays. + // Only the elements present in just the first array will remain. + _.difference = function(array) { + var rest = flatten(arguments, true, true, 1); + return _.filter(array, function(value){ + return !_.contains(rest, value); + }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + return _.unzip(arguments); + }; + + // Complement of _.zip. Unzip accepts an array of arrays and groups + // each array's elements on shared indices + _.unzip = function(array) { + var length = array && _.max(array, getLength).length || 0; + var result = Array(length); + + for (var index = 0; index < length; index++) { + result[index] = _.pluck(array, index); + } + return result; + }; + + // Converts lists into objects. Pass either a single array of `[key, value]` + // pairs, or two parallel arrays of the same length -- one of keys, and one of + // the corresponding values. + _.object = function(list, values) { + var result = {}; + for (var i = 0, length = getLength(list); i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // Generator function to create the findIndex and findLastIndex functions + function createPredicateIndexFinder(dir) { + return function(array, predicate, context) { + predicate = cb(predicate, context); + var length = getLength(array); + var index = dir > 0 ? 0 : length - 1; + for (; index >= 0 && index < length; index += dir) { + if (predicate(array[index], index, array)) return index; + } + return -1; + }; + } + + // Returns the first index on an array-like that passes a predicate test + _.findIndex = createPredicateIndexFinder(1); + _.findLastIndex = createPredicateIndexFinder(-1); + + // Use a comparator function to figure out the smallest index at which + // an object should be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iteratee, context) { + iteratee = cb(iteratee, context, 1); + var value = iteratee(obj); + var low = 0, high = getLength(array); + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; + } + return low; + }; + + // Generator function to create the indexOf and lastIndexOf functions + function createIndexFinder(dir, predicateFind, sortedIndex) { + return function(array, item, idx) { + var i = 0, length = getLength(array); + if (typeof idx == 'number') { + if (dir > 0) { + i = idx >= 0 ? idx : Math.max(idx + length, i); + } else { + length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; + } + } else if (sortedIndex && idx && length) { + idx = sortedIndex(array, item); + return array[idx] === item ? idx : -1; + } + if (item !== item) { + idx = predicateFind(slice.call(array, i, length), _.isNaN); + return idx >= 0 ? idx + i : -1; + } + for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { + if (array[idx] === item) return idx; + } + return -1; + }; + } + + // Return the position of the first occurrence of an item in an array, + // or -1 if the item is not included in the array. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); + _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (stop == null) { + stop = start || 0; + start = 0; + } + step = step || 1; + + var length = Math.max(Math.ceil((stop - start) / step), 0); + var range = Array(length); + + for (var idx = 0; idx < length; idx++, start += step) { + range[idx] = start; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Determines whether to execute a function as a constructor + // or a normal function with the provided arguments + var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { + if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); + var self = baseCreate(sourceFunc.prototype); + var result = sourceFunc.apply(self, args); + if (_.isObject(result)) return result; + return self; + }; + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if + // available. + _.bind = function(func, context) { + if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); + var args = slice.call(arguments, 2); + var bound = function() { + return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); + }; + return bound; + }; + + // Partially apply a function by creating a version that has had some of its + // arguments pre-filled, without changing its dynamic `this` context. _ acts + // as a placeholder, allowing any combination of arguments to be pre-filled. + _.partial = function(func) { + var boundArgs = slice.call(arguments, 1); + var bound = function() { + var position = 0, length = boundArgs.length; + var args = Array(length); + for (var i = 0; i < length; i++) { + args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; + } + while (position < arguments.length) args.push(arguments[position++]); + return executeBound(func, bound, this, this, args); + }; + return bound; + }; + + // Bind a number of an object's methods to that object. Remaining arguments + // are the method names to be bound. Useful for ensuring that all callbacks + // defined on an object belong to it. + _.bindAll = function(obj) { + var i, length = arguments.length, key; + if (length <= 1) throw new Error('bindAll must be passed function names'); + for (i = 1; i < length; i++) { + key = arguments[i]; + obj[key] = _.bind(obj[key], obj); + } + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memoize = function(key) { + var cache = memoize.cache; + var address = '' + (hasher ? hasher.apply(this, arguments) : key); + if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); + return cache[address]; + }; + memoize.cache = {}; + return memoize; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ + return func.apply(null, args); + }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = _.partial(_.delay, _, 1); + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. Normally, the throttled function will run + // as much as it can, without ever going more than once per `wait` duration; + // but if you'd like to disable the execution on the leading edge, pass + // `{leading: false}`. To disable execution on the trailing edge, ditto. + _.throttle = function(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + if (!options) options = {}; + var later = function() { + previous = options.leading === false ? 0 : _.now(); + timeout = null; + result = func.apply(context, args); + if (!timeout) context = args = null; + }; + return function() { + var now = _.now(); + if (!previous && options.leading === false) previous = now; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0 || remaining > wait) { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + previous = now; + result = func.apply(context, args); + if (!timeout) context = args = null; + } else if (!timeout && options.trailing !== false) { + timeout = setTimeout(later, remaining); + } + return result; + }; + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. If `immediate` is passed, trigger the function on the + // leading edge, instead of the trailing. + _.debounce = function(func, wait, immediate) { + var timeout, args, context, timestamp, result; + + var later = function() { + var last = _.now() - timestamp; + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function() { + context = this; + args = arguments; + timestamp = _.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return _.partial(wrapper, func); + }; + + // Returns a negated version of the passed-in predicate. + _.negate = function(predicate) { + return function() { + return !predicate.apply(this, arguments); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var args = arguments; + var start = args.length - 1; + return function() { + var i = start; + var result = args[start].apply(this, arguments); + while (i--) result = args[i].call(this, result); + return result; + }; + }; + + // Returns a function that will only be executed on and after the Nth call. + _.after = function(times, func) { + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Returns a function that will only be executed up to (but not including) the Nth call. + _.before = function(times, func) { + var memo; + return function() { + if (--times > 0) { + memo = func.apply(this, arguments); + } + if (times <= 1) func = null; + return memo; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = _.partial(_.before, 2); + + // Object Functions + // ---------------- + + // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. + var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); + var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', + 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; + + function collectNonEnumProps(obj, keys) { + var nonEnumIdx = nonEnumerableProps.length; + var constructor = obj.constructor; + var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; + + // Constructor is a special case. + var prop = 'constructor'; + if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); + + while (nonEnumIdx--) { + prop = nonEnumerableProps[nonEnumIdx]; + if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { + keys.push(prop); + } + } + } + + // Retrieve the names of an object's own properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = function(obj) { + if (!_.isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve all the property names of an object. + _.allKeys = function(obj) { + if (!_.isObject(obj)) return []; + var keys = []; + for (var key in obj) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var values = Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[keys[i]]; + } + return values; + }; + + // Returns the results of applying the iteratee to each element of the object + // In contrast to _.map it returns an object + _.mapObject = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = _.keys(obj), + length = keys.length, + results = {}, + currentKey; + for (var index = 0; index < length; index++) { + currentKey = keys[index]; + results[currentKey] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var pairs = Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [keys[i], obj[keys[i]]]; + } + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.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; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = createAssigner(_.allKeys); + + // Assigns a given object with all the own properties in the passed-in object(s) + // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + _.extendOwn = _.assign = createAssigner(_.keys); + + // Returns the first key on an object that passes a predicate test + _.findKey = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = _.keys(obj), key; + for (var i = 0, length = keys.length; i < length; i++) { + key = keys[i]; + if (predicate(obj[key], key, obj)) return key; + } + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(object, oiteratee, context) { + var result = {}, obj = object, iteratee, keys; + if (obj == null) return result; + if (_.isFunction(oiteratee)) { + keys = _.allKeys(obj); + iteratee = optimizeCb(oiteratee, context); + } else { + keys = flatten(arguments, false, false, 1); + iteratee = function(value, key, obj) { return key in obj; }; + obj = Object(obj); + } + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; + var value = obj[key]; + if (iteratee(value, key, obj)) result[key] = value; + } + return result; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj, iteratee, context) { + if (_.isFunction(iteratee)) { + iteratee = _.negate(iteratee); + } else { + var keys = _.map(flatten(arguments, false, false, 1), String); + iteratee = function(value, key) { + return !_.contains(keys, key); + }; + } + return _.pick(obj, iteratee, context); + }; + + // Fill in a given object with default properties. + _.defaults = createAssigner(_.allKeys, true); + + // Creates an object that inherits from the given prototype object. + // If additional properties are provided then they will be added to the + // created object. + _.create = function(prototype, props) { + var result = baseCreate(prototype); + if (props) _.extendOwn(result, props); + return result; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + if (!_.isObject(obj)) return obj; + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Returns whether an object has a given set of `key:value` pairs. + _.isMatch = function(object, attrs) { + var keys = _.keys(attrs), length = keys.length; + if (object == null) return !length; + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (attrs[key] !== obj[key] || !(key in obj)) return false; + } + return true; + }; + + + // Internal recursive comparison function for `isEqual`. + var eq = function(a, b, aStack, bStack) { + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) return a !== 0 || 1 / a === 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className !== toString.call(b)) return false; + switch (className) { + // Strings, numbers, regular expressions, dates, and booleans are compared by value. + case '[object RegExp]': + // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return '' + a === '' + b; + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. + // Object(NaN) is equivalent to NaN + if (+a !== +a) return +b !== +b; + // An `egal` comparison is performed for other numeric values. + return +a === 0 ? 1 / +a === 1 / b : +a === +b; + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a === +b; + } + + var areArrays = className === '[object Array]'; + if (!areArrays) { + if (typeof a != 'object' || typeof b != 'object') return false; + + // Objects with different constructors are not equivalent, but `Object`s or `Array`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && + _.isFunction(bCtor) && bCtor instanceof bCtor) + && ('constructor' in a && 'constructor' in b)) { + return false; + } + } + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + + // Initializing stack of traversed objects. + // It's done here since we only need them for objects and arrays comparison. + aStack = aStack || []; + bStack = bStack || []; + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] === a) return bStack[length] === b; + } + + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + + // Recursively compare objects and arrays. + if (areArrays) { + // Compare array lengths to determine if a deep comparison is necessary. + length = a.length; + if (length !== b.length) return false; + // Deep compare the contents, ignoring non-numeric properties. + while (length--) { + if (!eq(a[length], b[length], aStack, bStack)) return false; + } + } else { + // Deep compare objects. + var keys = _.keys(a), key; + length = keys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (_.keys(b).length !== length) return false; + while (length--) { + // Deep compare each member + key = keys[length]; + if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return true; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + return eq(a, b); + }; + + // Is a given array, string, or object empty? + // An "empty" object has no enumerable own-properties. + _.isEmpty = function(obj) { + if (obj == null) return true; + if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; + return _.keys(obj).length === 0; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) === '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. + _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) === '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE < 9), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return _.has(obj, 'callee'); + }; + } + + // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, + // IE 11 (#1621), and in Safari 8 (#1929). + if (typeof /./ != 'function' && typeof Int8Array != 'object') { + _.isFunction = function(obj) { + return typeof obj == 'function' || false; + }; + } + + // Is a given object a finite number? + _.isFinite = function(obj) { + return isFinite(obj) && !isNaN(parseFloat(obj)); + }; + + // Is the given value `NaN`? (NaN is the only number which does not equal itself). + _.isNaN = function(obj) { + return _.isNumber(obj) && obj !== +obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Shortcut function for checking if an object has a given property directly + // on itself (in other words, not on a prototype). + _.has = function(obj, key) { + return obj != null && hasOwnProperty.call(obj, key); + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iteratees. + _.identity = function(value) { + return value; + }; + + // Predicate-generating functions. Often useful outside of Underscore. + _.constant = function(value) { + return function() { + return value; + }; + }; + + _.noop = function(){}; + + _.property = property; + + // Generates a function for a given object that returns a given property. + _.propertyOf = function(obj) { + return obj == null ? function(){} : function(key) { + return obj[key]; + }; + }; + + // Returns a predicate for checking whether an object has a given set of + // `key:value` pairs. + _.matcher = _.matches = function(attrs) { + attrs = _.extendOwn({}, attrs); + return function(obj) { + return _.isMatch(obj, attrs); + }; + }; + + // Run a function **n** times. + _.times = function(n, iteratee, context) { + var accum = Array(Math.max(0, n)); + iteratee = optimizeCb(iteratee, context, 1); + for (var i = 0; i < n; i++) accum[i] = iteratee(i); + return accum; + }; + + // Return a random integer between min and max (inclusive). + _.random = function(min, max) { + if (max == null) { + max = min; + min = 0; + } + return min + Math.floor(Math.random() * (max - min + 1)); + }; + + // A (possibly faster) way to get the current timestamp as an integer. + _.now = Date.now || function() { + return new Date().getTime(); + }; + + // List of HTML entities for escaping. + var escapeMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + var unescapeMap = _.invert(escapeMap); + + // Functions for escaping and unescaping strings to/from HTML interpolation. + var createEscaper = function(map) { + var escaper = function(match) { + return map[match]; + }; + // Regexes for identifying a key that needs to be escaped + var source = '(?:' + _.keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function(string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + }; + _.escape = createEscaper(escapeMap); + _.unescape = createEscaper(unescapeMap); + + // If the value of the named `property` is a function then invoke it with the + // `object` as context; otherwise, return it. + _.result = function(object, property, fallback) { + var value = object == null ? void 0 : object[property]; + if (value === void 0) { + value = fallback; + } + return _.isFunction(value) ? value.call(object) : value; + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = ++idCounter + ''; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\u2028|\u2029/g; + + var escapeChar = function(match) { + return '\\' + escapes[match]; + }; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + // NB: `oldSettings` only exists for backwards compatibility. + _.template = function(text, settings, oldSettings) { + if (!settings && oldSettings) settings = oldSettings; + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset).replace(escaper, escapeChar); + index = offset + match.length; + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } else if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } else if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + + // Adobe VMs need the match returned to produce the correct offest. + return match; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + 'return __p;\n'; + + try { + var render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled source as a convenience for precompilation. + var argument = settings.variable || 'obj'; + template.source = 'function(' + argument + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function. Start chaining a wrapped Underscore object. + _.chain = function(obj) { + var instance = _(obj); + instance._chain = true; + return instance; + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(instance, obj) { + return instance._chain ? _(obj).chain() : obj; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + _.each(_.functions(obj), function(name) { + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result(this, func.apply(_, args)); + }; + }); + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; + return result(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + _.each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result(this, method.apply(this._wrapped, arguments)); + }; + }); + + // Extracts the result from a wrapped and chained object. + _.prototype.value = function() { + return this._wrapped; + }; + + // Provide unwrapping proxy for some methods used in engine operations + // such as arithmetic and JSON stringification. + _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; + + _.prototype.toString = function() { + return '' + this._wrapped; + }; + + // AMD registration happens at the end for compatibility with AMD loaders + // that may not enforce next-turn semantics on modules. Even though general + // practice for AMD registration is to be anonymous, underscore registers + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { + return _; + }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } +}.call(this)); + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(52).Promise; + +Promise._continueWhile = function (predicate, asyncFunction) { + if (predicate()) { + return asyncFunction().then(function () { + return Promise._continueWhile(predicate, asyncFunction); + }); + } + return Promise.resolve(); +}; + +module.exports = Promise; + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var request = __webpack_require__(7); +var debug = __webpack_require__(5)('leancloud:request'); +var md5 = __webpack_require__(57); +var Promise = __webpack_require__(1); +var Cache = __webpack_require__(16); +var AVError = __webpack_require__(3); +var AV = __webpack_require__(6); +var _ = __webpack_require__(0); + +var _require = __webpack_require__(4), + getSessionToken = _require.getSessionToken; + +var getServerURLPromise = void 0; + +// 服务器请求的节点 host +var API_HOST = { + cn: 'https://api.leancloud.cn', + us: 'https://us-api.leancloud.cn' +}; + +// 计算 X-LC-Sign 的签名方法 +var sign = function sign(key, isMasterKey) { + var now = new Date().getTime(); + var signature = md5(now + key); + if (isMasterKey) { + return signature + ',' + now + ',master'; + } + return signature + ',' + now; +}; + +var requestsCount = 0; + +var ajax = function ajax(method, resourceUrl, data) { + var headers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var onprogress = arguments[4]; + + var count = requestsCount++; + + debug('request(' + count + ')', method, resourceUrl, data, headers); + + return new Promise(function (resolve, reject) { + var req = request(method, resourceUrl).set(headers).send(data); + if (onprogress) { + req.on('progress', onprogress); + } + req.end(function (err, res) { + if (res) { + debug('response(' + count + ')', res.status, res.body || res.text, res.header); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + return resolve(res.body); + }); + }); +}; + +var setAppKey = function setAppKey(headers, signKey) { + if (signKey) { + headers['X-LC-Sign'] = sign(AV.applicationKey); + } else { + headers['X-LC-Key'] = AV.applicationKey; + } +}; + +var setHeaders = function setHeaders() { + var authOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var signKey = arguments[1]; + + var headers = { + 'X-LC-Id': AV.applicationId, + 'Content-Type': 'application/json;charset=UTF-8' + }; + var useMasterKey = false; + if (typeof authOptions.useMasterKey === 'boolean') { + useMasterKey = authOptions.useMasterKey; + } else if (typeof AV._useMasterKey === 'boolean') { + useMasterKey = AV._useMasterKey; + } + if (useMasterKey) { + if (AV.masterKey) { + if (signKey) { + headers['X-LC-Sign'] = sign(AV.masterKey, true); + } else { + headers['X-LC-Key'] = AV.masterKey + ',master'; + } + } else { + console.warn('masterKey is not set, fall back to use appKey'); + setAppKey(headers, signKey); + } + } else { + setAppKey(headers, signKey); + } + if (AV.hookKey) { + headers['X-LC-Hook-Key'] = AV.hookKey; + } + if (AV._config.applicationProduction !== null) { + headers['X-LC-Prod'] = String(AV._config.applicationProduction); + } + headers[ false ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent; + + return Promise.resolve().then(function () { + // Pass the session token + var sessionToken = getSessionToken(authOptions); + if (sessionToken) { + headers['X-LC-Session'] = sessionToken; + } else if (!AV._config.disableCurrentUser) { + return AV.User.currentAsync().then(function (currentUser) { + if (currentUser && currentUser._sessionToken) { + headers['X-LC-Session'] = currentUser._sessionToken; + } + return headers; + }); + } + return headers; + }); +}; + +var createApiUrl = function createApiUrl(route, className, objectId, method, dataObject) { + // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉 + if (AV.serverURL) { + AV._config.APIServerURL = AV.serverURL; + console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.'); + } + + var apiURL = AV._config.APIServerURL || API_HOST.cn; + + if (apiURL.charAt(apiURL.length - 1) !== '/') { + apiURL += '/'; + } + apiURL += '1.1/' + route; + if (className) { + apiURL += '/' + className; + } + if (objectId) { + apiURL += '/' + objectId; + } + if ((route === 'users' || route === 'classes') && dataObject) { + apiURL += '?'; + if (dataObject._fetchWhenSave) { + delete dataObject._fetchWhenSave; + apiURL += '&new=true'; + } + if (dataObject._where) { + apiURL += '&where=' + encodeURIComponent(JSON.stringify(dataObject._where)); + delete dataObject._where; + } + } + + if (method.toLowerCase() === 'get') { + if (apiURL.indexOf('?') === -1) { + apiURL += '?'; + } + for (var k in dataObject) { + if (_typeof(dataObject[k]) === 'object') { + dataObject[k] = JSON.stringify(dataObject[k]); + } + apiURL += '&' + k + '=' + encodeURIComponent(dataObject[k]); + } + } + + return apiURL; +}; + +var cacheServerURL = function cacheServerURL(serverURL, ttl) { + if (typeof ttl !== 'number') { + ttl = 3600; + } + return Cache.setAsync('APIServerURL', serverURL, ttl * 1000); +}; + +// handle AV._request Error +var handleError = function handleError(error) { + return new Promise(function (resolve, reject) { + /** + When API request need to redirect to the right location, + can't use browser redirect by http status 307, as the reason of CORS, + so API server response http status 410 and the param "location" for this case. + */ + if (error.statusCode === 410) { + cacheServerURL(error.response.api_server, error.response.ttl).then(function () { + resolve(error.response.location); + }).catch(reject); + } else { + var errorJSON = { + code: error.code || -1, + error: error.message || error.responseText + }; + if (error.response && error.response.code) { + errorJSON = error.response; + } else if (error.responseText) { + try { + errorJSON = JSON.parse(error.responseText); + } catch (e) { + // If we fail to parse the error text, that's okay. + } + } + + // Transform the error into an instance of AVError by trying to parse + // the error string as JSON. + reject(new AVError(errorJSON.code, errorJSON.error)); + } + }); +}; + +var setServerUrl = function setServerUrl(serverURL) { + AV._config.APIServerURL = 'https://' + serverURL; + + // 根据新 URL 重新设置区域 + var newRegion = _.findKey(API_HOST, function (item) { + return item === AV._config.APIServerURL; + }); + if (newRegion) { + AV._config.region = newRegion; + } +}; + +var refreshServerUrlByRouter = function refreshServerUrlByRouter() { + var url = 'https://app-router.leancloud.cn/1/route?appId=' + AV.applicationId; + return ajax('get', url).then(function (servers) { + if (servers.api_server) { + setServerUrl(servers.api_server); + return cacheServerURL(servers.api_server, servers.ttl); + } + }, function (error) { + // bypass all non-4XX errors + if (error.statusCode >= 400 && error.statusCode < 500) { + throw error; + } + }); +}; + +var setServerUrlByRegion = function setServerUrlByRegion() { + var region = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'cn'; + + getServerURLPromise = new Promise(function (resolve, reject) { + // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router + if (AV._config.APIServerURL) { + resolve(); + return; + } + // if not china server region, do not use router + if (region === 'cn') { + return Cache.getAsync('APIServerURL').then(function (serverURL) { + if (serverURL) { + setServerUrl(serverURL); + } else { + return refreshServerUrlByRouter(); + } + }).then(function () { + resolve(); + }).catch(function (error) { + reject(error); + }); + } else { + AV._config.region = region; + AV._config.APIServerURL = API_HOST[region]; + resolve(); + } + }); +}; + +/** + * route is classes, users, login, etc. + * objectId is null if there is no associated objectId. + * method is the http method for the REST API. + * dataObject is the payload as an object, or null if there is none. + * @ignore + */ +var AVRequest = function AVRequest(route, className, objectId, method) { + var dataObject = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + var authOptions = arguments[5]; + + if (!AV.applicationId) { + throw new Error('You must specify your applicationId using AV.init()'); + } + + if (!AV.applicationKey && !AV.masterKey) { + throw new Error('You must specify a AppKey using AV.init()'); + } + + if (!getServerURLPromise) { + return Promise.reject(new Error('Not initialized')); + } + return getServerURLPromise.then(function () { + var apiURL = createApiUrl(route, className, objectId, method, dataObject); + return setHeaders(authOptions, route !== 'bigquery').then(function (headers) { + return ajax(method, apiURL, dataObject, headers).then(null, function (res) { + return handleError(res).then(function (location) { + return ajax(method, location, dataObject, headers); + }); + }); + }); + }); +}; + +module.exports = { + ajax: ajax, + request: AVRequest, + setServerUrlByRegion: setServerUrlByRegion +}; + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +/** + * @class AV.Error + */ + +function AVError(code, message) { + var error = new Error(message); + error.code = code; + return error; +} + +_.extend(AVError, /** @lends AV.Error */{ + /** + * Error code indicating some error other than those enumerated here. + * @constant + */ + OTHER_CAUSE: -1, + + /** + * Error code indicating that something has gone wrong with the server. + * If you get this error code, it is AV's fault. Contact us at + * https://avoscloud.com/help + * @constant + */ + INTERNAL_SERVER_ERROR: 1, + + /** + * Error code indicating the connection to the AV servers failed. + * @constant + */ + CONNECTION_FAILED: 100, + + /** + * Error code indicating the specified object doesn't exist. + * @constant + */ + OBJECT_NOT_FOUND: 101, + + /** + * Error code indicating you tried to query with a datatype that doesn't + * support it, like exact matching an array or object. + * @constant + */ + INVALID_QUERY: 102, + + /** + * Error code indicating a missing or invalid classname. Classnames are + * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the + * only valid characters. + * @constant + */ + INVALID_CLASS_NAME: 103, + + /** + * Error code indicating an unspecified object id. + * @constant + */ + MISSING_OBJECT_ID: 104, + + /** + * Error code indicating an invalid key name. Keys are case-sensitive. They + * must start with a letter, and a-zA-Z0-9_ are the only valid characters. + * @constant + */ + INVALID_KEY_NAME: 105, + + /** + * Error code indicating a malformed pointer. You should not see this unless + * you have been mucking about changing internal AV code. + * @constant + */ + INVALID_POINTER: 106, + + /** + * Error code indicating that badly formed JSON was received upstream. This + * either indicates you have done something unusual with modifying how + * things encode to JSON, or the network is failing badly. + * @constant + */ + INVALID_JSON: 107, + + /** + * Error code indicating that the feature you tried to access is only + * available internally for testing purposes. + * @constant + */ + COMMAND_UNAVAILABLE: 108, + + /** + * You must call AV.initialize before using the AV library. + * @constant + */ + NOT_INITIALIZED: 109, + + /** + * Error code indicating that a field was set to an inconsistent type. + * @constant + */ + INCORRECT_TYPE: 111, + + /** + * Error code indicating an invalid channel name. A channel name is either + * an empty string (the broadcast channel) or contains only a-zA-Z0-9_ + * characters. + * @constant + */ + INVALID_CHANNEL_NAME: 112, + + /** + * Error code indicating that push is misconfigured. + * @constant + */ + PUSH_MISCONFIGURED: 115, + + /** + * Error code indicating that the object is too large. + * @constant + */ + OBJECT_TOO_LARGE: 116, + + /** + * Error code indicating that the operation isn't allowed for clients. + * @constant + */ + OPERATION_FORBIDDEN: 119, + + /** + * Error code indicating the result was not found in the cache. + * @constant + */ + CACHE_MISS: 120, + + /** + * Error code indicating that an invalid key was used in a nested + * JSONObject. + * @constant + */ + INVALID_NESTED_KEY: 121, + + /** + * Error code indicating that an invalid filename was used for AVFile. + * A valid file name contains only a-zA-Z0-9_. characters and is between 1 + * and 128 characters. + * @constant + */ + INVALID_FILE_NAME: 122, + + /** + * Error code indicating an invalid ACL was provided. + * @constant + */ + INVALID_ACL: 123, + + /** + * Error code indicating that the request timed out on the server. Typically + * this indicates that the request is too expensive to run. + * @constant + */ + TIMEOUT: 124, + + /** + * Error code indicating that the email address was invalid. + * @constant + */ + INVALID_EMAIL_ADDRESS: 125, + + /** + * Error code indicating a missing content type. + * @constant + */ + MISSING_CONTENT_TYPE: 126, + + /** + * Error code indicating a missing content length. + * @constant + */ + MISSING_CONTENT_LENGTH: 127, + + /** + * Error code indicating an invalid content length. + * @constant + */ + INVALID_CONTENT_LENGTH: 128, + + /** + * Error code indicating a file that was too large. + * @constant + */ + FILE_TOO_LARGE: 129, + + /** + * Error code indicating an error saving a file. + * @constant + */ + FILE_SAVE_ERROR: 130, + + /** + * Error code indicating an error deleting a file. + * @constant + */ + FILE_DELETE_ERROR: 153, + + /** + * Error code indicating that a unique field was given a value that is + * already taken. + * @constant + */ + DUPLICATE_VALUE: 137, + + /** + * Error code indicating that a role's name is invalid. + * @constant + */ + INVALID_ROLE_NAME: 139, + + /** + * Error code indicating that an application quota was exceeded. Upgrade to + * resolve. + * @constant + */ + EXCEEDED_QUOTA: 140, + + /** + * Error code indicating that a Cloud Code script failed. + * @constant + */ + SCRIPT_FAILED: 141, + + /** + * Error code indicating that a Cloud Code validation failed. + * @constant + */ + VALIDATION_ERROR: 142, + + /** + * Error code indicating that invalid image data was provided. + * @constant + */ + INVALID_IMAGE_DATA: 150, + + /** + * Error code indicating an unsaved file. + * @constant + */ + UNSAVED_FILE_ERROR: 151, + + /** + * Error code indicating an invalid push time. + */ + INVALID_PUSH_TIME_ERROR: 152, + + /** + * Error code indicating that the username is missing or empty. + * @constant + */ + USERNAME_MISSING: 200, + + /** + * Error code indicating that the password is missing or empty. + * @constant + */ + PASSWORD_MISSING: 201, + + /** + * Error code indicating that the username has already been taken. + * @constant + */ + USERNAME_TAKEN: 202, + + /** + * Error code indicating that the email has already been taken. + * @constant + */ + EMAIL_TAKEN: 203, + + /** + * Error code indicating that the email is missing, but must be specified. + * @constant + */ + EMAIL_MISSING: 204, + + /** + * Error code indicating that a user with the specified email was not found. + * @constant + */ + EMAIL_NOT_FOUND: 205, + + /** + * Error code indicating that a user object without a valid session could + * not be altered. + * @constant + */ + SESSION_MISSING: 206, + + /** + * Error code indicating that a user can only be created through signup. + * @constant + */ + MUST_CREATE_USER_THROUGH_SIGNUP: 207, + + /** + * Error code indicating that an an account being linked is already linked + * to another user. + * @constant + */ + ACCOUNT_ALREADY_LINKED: 208, + + /** + * Error code indicating that a user cannot be linked to an account because + * that account's id could not be found. + * @constant + */ + LINKED_ID_MISSING: 250, + + /** + * Error code indicating that a user with a linked (e.g. Facebook) account + * has an invalid session. + * @constant + */ + INVALID_LINKED_SESSION: 251, + + /** + * Error code indicating that a service being linked (e.g. Facebook or + * Twitter) is unsupported. + * @constant + */ + UNSUPPORTED_SERVICE: 252, + /** + * Error code indicating a real error code is unavailable because + * we had to use an XDomainRequest object to allow CORS requests in + * Internet Explorer, which strips the body from HTTP responses that have + * a non-2XX status code. + * @constant + */ + X_DOMAIN_REQUEST: 602 +}); + +module.exports = AVError; + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +// Helper function to check null or undefined. +var isNullOrUndefined = function isNullOrUndefined(x) { + return _.isNull(x) || _.isUndefined(x); +}; + +var ensureArray = function ensureArray(target) { + if (_.isArray(target)) { + return target; + } + if (target === undefined || target === null) { + return []; + } + return [target]; +}; + +var getSessionToken = function getSessionToken(authOptions) { + if (authOptions.sessionToken) { + return authOptions.sessionToken; + } + if (authOptions.user && typeof authOptions.user.getSessionToken === 'function') { + return authOptions.user.getSessionToken(); + } +}; + +var tap = function tap(interceptor) { + return function (value) { + return interceptor(value), value; + }; +}; + +module.exports = { + isNullOrUndefined: isNullOrUndefined, + ensureArray: ensureArray, + getSessionToken: getSessionToken, + tap: tap +}; + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = __webpack_require__(51); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var _ = __webpack_require__(0); +var userAgent = __webpack_require__(42); + +var _require = __webpack_require__(4), + isNullOrUndefined = _require.isNullOrUndefined; + +var AV = global.AV || {}; + +// All internal configuration items +AV._config = AV._config || {}; +var AVConfig = AV._config; + +_.extend(AVConfig, { + + // 服务器节点地区,默认中国大陆 + region: 'cn', + + // 服务器的 URL,默认初始化时被设置为大陆节点地址 + APIServerURL: AVConfig.APIServerURL || '', + + // 禁用 currentUser,通常用于多用户环境 + disableCurrentUser: false, + + // Internal config can modifie the UserAgent + userAgent: userAgent, + + // set production environment or test environment + // 1: production environment, 0: test environment, null: default environment + applicationProduction: null +}); + +/** + * Contains all AV API classes and functions. + * @namespace AV + */ + +// Helpers +// ------- + +// Shared empty constructor function to aid in prototype-chain creation. +var EmptyConstructor = function EmptyConstructor() {}; + +// Helper function to correctly set up the prototype chain, for subclasses. +// Similar to `goog.inherits`, but uses a hash of prototype properties and +// class properties to be extended. +var inherits = function inherits(parent, protoProps, staticProps) { + var child; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent's constructor. + if (protoProps && protoProps.hasOwnProperty('constructor')) { + child = protoProps.constructor; + } else { + /** @ignore */ + child = function child() { + parent.apply(this, arguments); + }; + } + + // Inherit class (static) properties from parent. + _.extend(child, parent); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + EmptyConstructor.prototype = parent.prototype; + child.prototype = new EmptyConstructor(); + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) { + _.extend(child.prototype, protoProps); + } + + // Add static properties to the constructor function, if supplied. + if (staticProps) { + _.extend(child, staticProps); + } + + // Correctly set child's `prototype.constructor`. + child.prototype.constructor = child; + + // Set a convenience property in case the parent's prototype is + // needed later. + child.__super__ = parent.prototype; + + return child; +}; + +/** + * Call this method to set production environment variable. + * @function AV.setProduction + * @param {Boolean} production True is production environment,and + * it's true by default. + */ +AV.setProduction = function (production) { + if (!isNullOrUndefined(production)) { + AVConfig.applicationProduction = production ? 1 : 0; + } else { + // change to default value + AVConfig.applicationProduction = null; + } +}; + +/** + * Returns prefix for localStorage keys used by this instance of AV. + * @param {String} path The relative suffix to append to it. + * null or undefined is treated as the empty string. + * @return {String} The full key name. + * @private + */ +AV._getAVPath = function (path) { + if (!AV.applicationId) { + throw new Error("You need to call AV.initialize before using AV."); + } + if (!path) { + path = ""; + } + if (!_.isString(path)) { + throw new Error("Tried to get a localStorage path that wasn't a String."); + } + if (path[0] === "/") { + path = path.substring(1); + } + return "AV/" + AV.applicationId + "/" + path; +}; + +/** + * Returns the unique string for this app on this machine. + * Gets reset when localStorage is cleared. + * @private + */ +AV._installationId = null; +AV._getInstallationId = function () { + // See if it's cached in RAM. + if (AV._installationId) { + return AV.Promise.resolve(AV._installationId); + } + + // Try to get it from localStorage. + var path = AV._getAVPath("installationId"); + return AV.localStorage.getItemAsync(path).then(function (_installationId) { + AV._installationId = _installationId; + if (!AV._installationId) { + // It wasn't in localStorage, so create a new one. + var hexOctet = function hexOctet() { + return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + }; + AV._installationId = hexOctet() + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + hexOctet() + hexOctet(); + return AV.localStorage.setItemAsync(path, AV._installationId); + } else { + return _installationId; + } + }); +}; + +AV._parseDate = function (iso8601) { + var regexp = new RegExp("^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})" + "T" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})" + "(.([0-9]+))?" + "Z$"); + var match = regexp.exec(iso8601); + if (!match) { + return null; + } + + var year = match[1] || 0; + var month = (match[2] || 1) - 1; + var day = match[3] || 0; + var hour = match[4] || 0; + var minute = match[5] || 0; + var second = match[6] || 0; + var milli = match[8] || 0; + + return new Date(Date.UTC(year, month, day, hour, minute, second, milli)); +}; + +// A self-propagating extend function. +AV._extend = function (protoProps, classProps) { + var child = inherits(this, protoProps, classProps); + child.extend = this.extend; + return child; +}; + +// Helper function to get a value from a Backbone object as a property +// or as a function. +AV._getValue = function (object, prop) { + if (!(object && object[prop])) { + return null; + } + return _.isFunction(object[prop]) ? object[prop]() : object[prop]; +}; + +/** + * Converts a value in a AV Object into the appropriate representation. + * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object) + * if seenObjects is falsey. Otherwise any AV.Objects not in + * seenObjects will be fully embedded rather than encoded + * as a pointer. This array will be used to prevent going into an infinite + * loop because we have circular references. If + * is set, then none of the AV Objects that are serialized can be dirty. + * @private + */ +AV._encode = function (value, seenObjects, disallowObjects) { + if (value instanceof AV.Object) { + if (disallowObjects) { + throw new Error("AV.Objects not allowed here"); + } + if (!seenObjects || _.include(seenObjects, value) || !value._hasData) { + return value._toPointer(); + } + if (!value.dirty()) { + seenObjects = seenObjects.concat(value); + return AV._encode(value._toFullJSON(seenObjects), seenObjects, disallowObjects); + } + throw new Error("Tried to save an object with a pointer to a new, unsaved object."); + } + if (value instanceof AV.ACL) { + return value.toJSON(); + } + if (_.isDate(value)) { + return { "__type": "Date", "iso": value.toJSON() }; + } + if (value instanceof AV.GeoPoint) { + return value.toJSON(); + } + if (_.isArray(value)) { + return _.map(value, function (x) { + return AV._encode(x, seenObjects, disallowObjects); + }); + } + if (_.isRegExp(value)) { + return value.source; + } + if (value instanceof AV.Relation) { + return value.toJSON(); + } + if (value instanceof AV.Op) { + return value.toJSON(); + } + if (value instanceof AV.File) { + if (!value.url() && !value.id) { + throw new Error("Tried to save an object containing an unsaved file."); + } + return value._toFullJSON(); + } + if (_.isObject(value)) { + return _.mapObject(value, function (v, k) { + return AV._encode(v, seenObjects, disallowObjects); + }); + } + return value; +}; + +/** + * The inverse function of AV._encode. + * @private + */ +AV._decode = function (value, key) { + if (!_.isObject(value) || _.isDate(value)) { + return value; + } + if (_.isArray(value)) { + return _.map(value, function (v) { + return AV._decode(v); + }); + } + if (value instanceof AV.Object) { + return value; + } + if (value instanceof AV.File) { + return value; + } + if (value instanceof AV.Op) { + return value; + } + if (value instanceof AV.GeoPoint) { + return value; + } + if (value instanceof AV.ACL) { + return value; + } + if (key === 'ACL') { + return new AV.ACL(value); + } + if (value.__op) { + return AV.Op._decode(value); + } + var className; + if (value.__type === "Pointer") { + className = value.className; + var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + if (Object.keys(value).length > 3) { + var v = _.clone(value); + delete v.__type; + delete v.className; + pointer._finishFetch(v, true); + } else { + pointer._finishFetch({ objectId: value.objectId }, false); + } + return pointer; + } + if (value.__type === "Object") { + // It's an Object included in a query result. + className = value.className; + var _v = _.clone(value); + delete _v.__type; + delete _v.className; + var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + object._finishFetch(_v, true); + return object; + } + if (value.__type === "Date") { + return AV._parseDate(value.iso); + } + if (value.__type === "GeoPoint") { + return new AV.GeoPoint({ + latitude: value.latitude, + longitude: value.longitude + }); + } + if (value.__type === "Relation") { + if (!key) throw new Error('key missing decoding a Relation'); + var relation = new AV.Relation(null, key); + relation.targetClassName = value.className; + return relation; + } + if (value.__type === 'File') { + var file = new AV.File(value.name); + var _v2 = _.clone(value); + delete _v2.__type; + file._finishFetch(_v2); + return file; + } + return _.mapObject(value, AV._decode); +}; + +AV._encodeObjectOrArray = function (value) { + var encodeAVObject = function encodeAVObject(object) { + if (object && object._toFullJSON) { + object = object._toFullJSON([]); + } + + return _.mapObject(object, function (value) { + return AV._encode(value, []); + }); + }; + + if (_.isArray(value)) { + return value.map(function (object) { + return encodeAVObject(object); + }); + } else { + return encodeAVObject(value); + } +}; + +AV._arrayEach = _.each; + +/** + * Does a deep traversal of every item in object, calling func on every one. + * @param {Object} object The object or array to traverse deeply. + * @param {Function} func The function to call for every item. It will + * be passed the item as an argument. If it returns a truthy value, that + * value will replace the item in its parent container. + * @returns {} the result of calling func on the top-level object itself. + * @private + */ +AV._traverse = function (object, func, seen) { + if (object instanceof AV.Object) { + seen = seen || []; + if (_.indexOf(seen, object) >= 0) { + // We've already visited this object in this call. + return; + } + seen.push(object); + AV._traverse(object.attributes, func, seen); + return func(object); + } + if (object instanceof AV.Relation || object instanceof AV.File) { + // Nothing needs to be done, but we don't want to recurse into the + // object's parent infinitely, so we catch this case. + return func(object); + } + if (_.isArray(object)) { + _.each(object, function (child, index) { + var newChild = AV._traverse(child, func, seen); + if (newChild) { + object[index] = newChild; + } + }); + return func(object); + } + if (_.isObject(object)) { + AV._each(object, function (child, key) { + var newChild = AV._traverse(child, func, seen); + if (newChild) { + object[key] = newChild; + } + }); + return func(object); + } + return func(object); +}; + +/** + * This is like _.each, except: + * * it doesn't work for so-called array-like objects, + * * it does work for dictionaries with a "length" attribute. + * @private + */ +AV._objectEach = AV._each = function (obj, callback) { + if (_.isObject(obj)) { + _.each(_.keys(obj), function (key) { + callback(obj[key], key); + }); + } else { + _.each(obj, callback); + } +}; + +module.exports = AV; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Root reference for iframes. + */ + +var root; +if (typeof window !== 'undefined') { // Browser window + root = window; +} else if (typeof self !== 'undefined') { // Web Worker + root = self; +} else { // Other environments + console.warn("Using browser-only version of superagent in non-browser environment"); + root = this; +} + +var Emitter = __webpack_require__(49); +var RequestBase = __webpack_require__(60); +var isObject = __webpack_require__(11); +var isFunction = __webpack_require__(59); +var ResponseBase = __webpack_require__(61); +var shouldRetry = __webpack_require__(62); + +/** + * Noop. + */ + +function noop(){}; + +/** + * Expose `request`. + */ + +var request = exports = module.exports = function(method, url) { + // callback + if ('function' == typeof url) { + return new exports.Request('GET', method).end(url); + } + + // url first + if (1 == arguments.length) { + return new exports.Request('GET', method); + } + + return new exports.Request(method, url); +} + +exports.Request = Request; + +/** + * Determine XHR. + */ + +request.getXHR = function () { + if (root.XMLHttpRequest + && (!root.location || 'file:' != root.location.protocol + || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} + } + throw Error("Browser-only verison of superagent could not find XHR"); +}; + +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + +var trim = ''.trim + ? function(s) { return s.trim(); } + : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; + +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + for (var key in obj) { + pushEncodedKeyValuePair(pairs, key, obj[key]); + } + return pairs.join('&'); +} + +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + +function pushEncodedKeyValuePair(pairs, key, val) { + if (val != null) { + if (Array.isArray(val)) { + val.forEach(function(v) { + pushEncodedKeyValuePair(pairs, key, v); + }); + } else if (isObject(val)) { + for(var subkey in val) { + pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); + } + } else { + pairs.push(encodeURIComponent(key) + + '=' + encodeURIComponent(val)); + } + } else if (val === null) { + pairs.push(encodeURIComponent(key)); + } +} + +/** + * Expose serialization method. + */ + + request.serializeObject = serialize; + + /** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var pair; + var pos; + + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos == -1) { + obj[decodeURIComponent(pair)] = ''; + } else { + obj[decodeURIComponent(pair.slice(0, pos))] = + decodeURIComponent(pair.slice(pos + 1)); + } + } + + return obj; +} + +/** + * Expose parser. + */ + +request.parseString = parseString; + +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'application/xml', + urlencoded: 'application/x-www-form-urlencoded', + 'form': 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + + request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': JSON.stringify + }; + + /** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; + +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + + lines.pop(); // trailing CRLF + + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + + return fields; +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + return /[\/+]json\b/.test(mime); +} + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + +function Response(req) { + this.req = req; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') + ? this.xhr.responseText + : null; + this.statusText = this.req.xhr.statusText; + var status = this.xhr.status; + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + this._setStatusProperties(status); + this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + + if (null === this.text && req._responseType) { + this.body = this.xhr.response; + } else { + this.body = this.req.method != 'HEAD' + ? this._parseBody(this.text ? this.text : this.xhr.response) + : null; + } +} + +ResponseBase(Response.prototype); + +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function(str){ + var parse = request.parse[this.type]; + if(this.req._parser) { + return this.req._parser(this, str); + } + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && str && (str.length || str instanceof Object) + ? parse(str) + : null; +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function(){ + var req = this.req; + var method = req.method; + var url = req.url; + + var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + + return err; +}; + +/** + * Expose `Response`. + */ + +request.Response = Response; + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + var self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', function(){ + var err = null; + var res = null; + + try { + res = new Response(self); + } catch(e) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = e; + // issue #675: return the raw response if the response parsing fails + if (self.xhr) { + // ie9 doesn't have 'response' property + err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + err.status = self.xhr.status ? self.xhr.status : null; + err.statusCode = err.status; // backwards-compat only + } else { + err.rawResponse = null; + err.status = null; + } + + return self.callback(err); + } + + self.emit('response', res); + + var new_err; + try { + if (!self._isResponseOK(res)) { + new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + } + } catch(e) { + new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android + } + + // #1000 don't catch errors from the callback to avoid double calling it + if (new_err) { + self.callback(new_err, res); + } else { + self.callback(null, res); + } + }); +} + +/** + * Mixin `Emitter` and `RequestBase`. + */ + +Emitter(Request.prototype); +RequestBase(Request.prototype); + +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function(type){ + this.set('Content-Type', request.types[type] || type); + return this; +}; + +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function(type){ + this.set('Accept', request.types[type] || type); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} [pass] optional in case of using 'bearer' as type + * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function(user, pass, options){ + if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options + options = pass; + } + if (!options) { + options = { + type: 'function' === typeof btoa ? 'basic' : 'auto', + } + } + + switch (options.type) { + case 'basic': + this.set('Authorization', 'Basic ' + btoa(user + ':' + pass)); + break; + + case 'auto': + this.username = user; + this.password = pass; + break; + + case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' }) + this.set('Authorization', 'Bearer ' + user); + break; + } + return this; +}; + +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.query = function(val){ + if ('string' != typeof val) val = serialize(val); + if (val) this._query.push(val); + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function(field, file, options){ + if (file) { + if (this._data) { + throw Error("superagent can't mix .send() and .attach()"); + } + + this._getFormData().append(field, file, options || file.name); + } + return this; +}; + +Request.prototype._getFormData = function(){ + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function(err, res){ + // console.log(this._retries, this._maxRetries) + if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) { + return this._retry(); + } + + var fn = this._callback; + this.clearTimeout(); + + if (err) { + if (this._maxRetries) err.retries = this._retries - 1; + this.emit('error', err); + } + + fn(err, res); +}; + +/** + * Invoke callback with x-domain error. + * + * @api private + */ + +Request.prototype.crossDomainError = function(){ + var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + err.crossDomain = true; + + err.status = this.status; + err.method = this.method; + err.url = this.url; + + this.callback(err); +}; + +// This only warns, because the request is still likely to work +Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){ + console.warn("This is not supported in browser version of superagent"); + return this; +}; + +// This throws, because it can't send/receive data as expected +Request.prototype.pipe = Request.prototype.write = function(){ + throw Error("Streaming is not supported in browser version of superagent"); +}; + +/** + * Compose querystring to append to req.url + * + * @api private + */ + +Request.prototype._appendQueryString = function(){ + var query = this._query.join('&'); + if (query) { + this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query; + } + + if (this._sort) { + var index = this.url.indexOf('?'); + if (index >= 0) { + var queryArr = this.url.substring(index + 1).split('&'); + if (isFunction(this._sort)) { + queryArr.sort(this._sort); + } else { + queryArr.sort(); + } + this.url = this.url.substring(0, index) + '?' + queryArr.join('&'); + } + } +}; + +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +Request.prototype._isHost = function _isHost(obj) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; +} + +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype.end = function(fn){ + if (this._endCalled) { + console.warn("Warning: .end() was called twice. This is not supported in superagent"); + } + this._endCalled = true; + + // store callback + this._callback = fn || noop; + + // querystring + this._appendQueryString(); + + return this._end(); +}; + +Request.prototype._end = function() { + var self = this; + var xhr = this.xhr = request.getXHR(); + var data = this._formData || this._data; + + this._setTimeouts(); + + // state change + xhr.onreadystatechange = function(){ + var readyState = xhr.readyState; + if (readyState >= 2 && self._responseTimeoutTimer) { + clearTimeout(self._responseTimeoutTimer); + } + if (4 != readyState) { + return; + } + + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + var status; + try { status = xhr.status } catch(e) { status = 0; } + + if (!status) { + if (self.timedout || self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }; + + // progress + var handleProgress = function(direction, e) { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + } + e.direction = direction; + self.emit('progress', e); + } + if (this.hasListeners('progress')) { + try { + xhr.onprogress = handleProgress.bind(null, 'download'); + if (xhr.upload) { + xhr.upload.onprogress = handleProgress.bind(null, 'upload'); + } + } catch(e) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + + // initiate request + try { + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + } catch (err) { + // see #1149 + return this.callback(err); + } + + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { + // serialize stuff + var contentType = this._header['content-type']; + var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) { + serialize = request.serialize['application/json']; + } + if (serialize) data = serialize(data); + } + + // set header fields + for (var field in this.header) { + if (null == this.header[field]) continue; + + if (this.header.hasOwnProperty(field)) + xhr.setRequestHeader(field, this.header[field]); + } + + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data !== 'undefined' ? data : null); + return this; +}; + +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; + +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.options = function(url, data, fn){ + var req = request('OPTIONS', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * DELETE `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +function del(url, data, fn){ + var req = request('DELETE', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +request['del'] = del; +request['delete'] = del; + +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var FormData = function () { + function FormData() { + _classCallCheck(this, FormData); + + this._entries = []; + } + + _createClass(FormData, [{ + key: 'append', + value: function append(name, value) { + if (typeof name !== 'string') { + throw new TypeError('FormData name must be a string'); + } + if (typeof value !== 'string') { + if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object' || typeof value.uri !== 'string') { + throw new TypeError('FormData value must be a string or { uri: tempFilePath }'); + } + } + this._entries.push([name, value]); + } + }, { + key: 'set', + value: function set(name, value) { + var entry = this.get(name); + if (entry) { + entry[1] = value; + } else { + this.append(name, value); + } + } + }, { + key: 'delete', + value: function _delete(name) { + this._entries = this._entries.filter(function (entry) { + return entry[0] !== name; + }); + } + }, { + key: 'entries', + value: function entries() { + return this._entries; + } + }, { + key: 'get', + value: function get(name) { + return this._entries.find(function (entry) { + return entry[0] === name; + }); + } + }, { + key: 'getAll', + value: function getAll(name) { + return this._entries.filter(function (entry) { + return entry[0] === name; + }); + } + }, { + key: 'has', + value: function has(name) { + return this._entries.some(function (entry) { + return entry[0] === name; + }); + } + }, { + key: 'keys', + value: function keys() { + return this._entries.map(function (entry) { + return entry[0]; + }); + } + }, { + key: 'values', + value: function values() { + return this._entries.map(function (entry) { + return entry[1]; + }); + } + }]); + + return FormData; +}(); + +module.exports = FormData; + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ + + + +/** + * Creates a unique key. + * + * @param {string} name - A name to create. + * @returns {symbol|string} + * @private + */ +var createUniqueKey = exports.createUniqueKey = (typeof Symbol !== "undefined" ? + Symbol : + function createUniqueKey(name) { + return "[[" + name + "_" + Math.random().toFixed(8).slice(2) + "]]"; + }); + +/** + * The key of listeners. + * + * @type {symbol|string} + * @private + */ +exports.LISTENERS = createUniqueKey("listeners"); + +/** + * A value of kind for listeners which are registered in the capturing phase. + * + * @type {number} + * @private + */ +exports.CAPTURE = 1; + +/** + * A value of kind for listeners which are registered in the bubbling phase. + * + * @type {number} + * @private + */ +exports.BUBBLE = 2; + +/** + * A value of kind for listeners which are registered as an attribute. + * + * @type {number} + * @private + */ +exports.ATTRIBUTE = 3; + +/** + * @typedef object ListenerNode + * @property {function} listener - A listener function. + * @property {number} kind - The kind of the listener. + * @property {ListenerNode|null} next - The next node. + * If this node is the last, this is `null`. + */ + +/** + * Creates a node of singly linked list for a list of listeners. + * + * @param {function} listener - A listener function. + * @param {number} kind - The kind of the listener. + * @returns {ListenerNode} The created listener node. + */ +exports.newNode = function newNode(listener, kind) { + return {listener: listener, kind: kind, next: null}; +}; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports) { + +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isObject(obj) { + return null !== obj && 'object' === typeof obj; +} + +module.exports = isObject; + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Storage = function () { + function Storage() { + _classCallCheck(this, Storage); + } + + _createClass(Storage, [{ + key: 'getItem', + value: function getItem(key) { + return wx.getStorageSync(key); + } + }, { + key: 'setItem', + value: function setItem(key, value) { + return wx.setStorageSync(key, value); + } + }, { + key: 'removeItem', + value: function removeItem(key) { + return this.setItem(key, ''); + } + }, { + key: 'clear', + value: function clear() { + return wx.clearStorageSync(); + } + }]); + + return Storage; +}(); + +module.exports = new Storage(); + +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = {}; + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var assign = __webpack_require__(21); +var EventTarget = __webpack_require__(20); + +var CONNECTING = 0; +var OPEN = 1; +var CLOSING = 2; +var CLOSED = 3; + +var EVENTS = ['open', 'error', 'message', 'close']; + +var instance = void 0; + +function errorHandler(event) { + // 安卓小程序会诡异地触发 onSocketError 回调 + // 通过比较 message 过滤掉 + if (event.message === "") return; + if (instance) { + instance._readyState = CLOSED; + instance.dispatchEvent({ + type: 'error', + message: event.errMsg + }); + } +} + +var WebSocket = function (_EventTarget) { + _inherits(WebSocket, _EventTarget); + + function WebSocket(url, protocal) { + _classCallCheck(this, WebSocket); + + if (!url) { + throw new TypeError('Failed to construct \'WebSocket\': url required'); + } + if (protocal) { + throw new Error('subprotocal not supported in weapp'); + } + + var _this = _possibleConstructorReturn(this, (WebSocket.__proto__ || Object.getPrototypeOf(WebSocket)).call(this)); + + _this._url = url; + _this._protocal = ''; // default value according to specs + _this._readyState = CONNECTING; + if (instance) { + instance.dispatchEvent({ + type: 'close' + }); + } + instance = _this; + + wx.onSocketOpen(function (event) { + if (instance) { + instance._readyState = OPEN; + instance.dispatchEvent({ + type: 'open' + }); + } + }); + wx.onSocketError(errorHandler); + wx.onSocketMessage(function (event) { + if (instance) { + var data = event.data, + origin = event.origin, + ports = event.ports, + source = event.source; + + instance.dispatchEvent({ + data: data, + origin: origin, + ports: ports, + source: source, + type: 'message' + }); + } + }); + wx.onSocketClose(function (event) { + if (instance) { + instance._readyState = CLOSED; + var code = event.code, + reason = event.reason, + wasClean = event.wasClean; + + instance.dispatchEvent({ + code: code, + reason: reason, + wasClean: wasClean, + type: 'close' + }); + instance = null; + } + }); + + wx.connectSocket({ + url: url, + fail: function fail(error) { + return setTimeout(function () { + return errorHandler(error); + }, 0); + } + }); + return _this; + } + + _createClass(WebSocket, [{ + key: 'close', + value: function close() { + if (this.readyState === CONNECTING) { + console.warn('close WebSocket which is connecting might not work'); + } + wx.closeSocket(); + } + }, { + key: 'send', + value: function send(data) { + if (this.readyState !== OPEN) { + throw new Error('INVALID_STATE_ERR'); + } + + if (typeof data !== 'string') { + throw new TypeError('only string typed data are supported'); + } + + wx.sendSocketMessage({ + data: data + }); + } + }, { + key: 'url', + get: function get() { + return this._url; + } + }, { + key: 'protocal', + get: function get() { + return this._protocal; + } + }, { + key: 'readyState', + get: function get() { + return this._readyState; + } + }]); + + return WebSocket; +}(EventTarget(EVENTS)); + +assign(WebSocket, { + CONNECTING: CONNECTING, + OPEN: OPEN, + CLOSING: CLOSING, + CLOSED: CLOSED +}); + +module.exports = WebSocket; + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var assign = __webpack_require__(21); +var EventTarget = __webpack_require__(20); +var FormData = __webpack_require__(9); + +var UNSENT = 0; +var OPENED = 1; +var HEADERS_RECEIVED = 2; +var LOADING = 3; +var DONE = 4; + +var REQUEST_EVENTS = ['abort', 'error', 'load', 'loadstart', 'progress', 'timeout', 'loadend', 'readystatechange']; + +function successCallback(response) { + this.status = response.statusCode; + this.statusText = response.statusCode; + var text = response.data; + if (typeof text !== 'string') { + text = JSON.stringify(text); + } + this.responseText = this.response = text; + this.readyState = DONE; + this.dispatchEvent({ type: 'readystatechange' }); +} + +var XMLHttpRequest = function (_EventTarget) { + _inherits(XMLHttpRequest, _EventTarget); + + function XMLHttpRequest() { + _classCallCheck(this, XMLHttpRequest); + + var _this = _possibleConstructorReturn(this, (XMLHttpRequest.__proto__ || Object.getPrototypeOf(XMLHttpRequest)).call(this)); + + _this.readyState = UNSENT; + _this._headers = {}; + return _this; + } + + _createClass(XMLHttpRequest, [{ + key: 'abort', + value: function abort() { + throw new Error('not supported in weapp'); + } + }, { + key: 'getAllResponseHeaders', + value: function getAllResponseHeaders() { + console.warn('getAllResponseHeaders always returns \'\''); + return ''; + } + }, { + key: 'getResponseHeader', + value: function getResponseHeader(key) { + if (key === 'content-type') { + console.warn('get content-type always returns \'application/json\''); + return 'application/json'; + } + console.warn('getResponseHeader always returns \'\''); + return ''; + } + }, { + key: 'overrideMimeType', + value: function overrideMimeType() { + throw new Error('not supported in weapp'); + } + }, { + key: 'open', + value: function open(method, url) { + var async = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + + if (this.readyState !== UNSENT) { + throw new Error('request is already opened'); + } + if (!async) { + throw new Error('sync request is not supported'); + } + this._method = method; + this._url = url; + this.readyState = OPENED; + this.dispatchEvent({ type: 'readystatechange' }); + } + }, { + key: 'setRequestHeader', + value: function setRequestHeader(header, value) { + if (this.readyState !== OPENED) { + throw new Error('request is not opened'); + } + this._headers[header.toLowerCase()] = value; + } + }, { + key: 'send', + value: function send(data) { + var _this2 = this; + + if (this.readyState !== OPENED) { + throw new Error('request is not opened'); + } + if (data instanceof FormData) { + var entries = data.entries(); + var blobs = entries.filter(function (entry) { + return typeof entry[1] !== 'string'; + }); + if (blobs.length === 0) { + throw new Error('Must specify a Blob field in FormData'); + } + if (blobs.length > 1) { + console.warn('Only the first Blob will be send in Weapp'); + } + var restData = entries.filter(function (entry) { + return typeof entry[1] === 'string'; + }).reduce(function (result, entry) { + return assign(result, _defineProperty({}, entry[0], entry[1])); + }, {}); + wx.uploadFile({ + url: this._url, + name: blobs[0][0], + filePath: blobs[0][1].uri, + formData: restData, + header: this._headers, + success: successCallback.bind(this), + fail: function fail(error) { + _this2.status = 0; + _this2.readyState = DONE; + _this2.dispatchEvent({ type: 'readystatechange' }); + _this2.dispatchEvent({ type: 'error' }); + } + }); + } else { + wx.request({ + url: this._url, + data: data || '', + // method 的 value 居然必须为大写 + method: this._method.toUpperCase(), + header: this._headers, + success: successCallback.bind(this), + fail: function fail(error) { + _this2.status = 0; + _this2.readyState = DONE; + _this2.dispatchEvent({ type: 'readystatechange' }); + _this2.dispatchEvent({ type: 'error' }); + } + }); + } + } + }]); + + return XMLHttpRequest; +}(EventTarget(REQUEST_EVENTS)); + +assign(XMLHttpRequest, { + UNSENT: UNSENT, + OPENED: OPENED, + HEADERS_RECEIVED: HEADERS_RECEIVED, + LOADING: LOADING, + DONE: DONE +}); + +module.exports = XMLHttpRequest; + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var storage = __webpack_require__(17); +var AV = __webpack_require__(6); + +var removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage); + +var getCacheData = function getCacheData(cacheData, key) { + try { + cacheData = JSON.parse(cacheData); + } catch (e) { + return null; + } + if (cacheData) { + var expired = cacheData.expiredAt && cacheData.expiredAt < Date.now(); + if (!expired) { + return cacheData.value; + } + return removeAsync(key).then(function () { + return null; + }); + } + return null; +}; + +exports.getAsync = function (key) { + key = AV.applicationId + '/' + key; + return storage.getItemAsync(key).then(function (cache) { + return getCacheData(cache, key); + }); +}; + +exports.setAsync = function (key, value, ttl) { + var cache = { value: value }; + if (typeof ttl === 'number') { + cache.expiredAt = Date.now() + ttl; + } + return storage.setItemAsync(AV.applicationId + '/' + key, JSON.stringify(cache)); +}; + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(1); +var localStorage = __webpack_require__(47); + +var syncApiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +if (!localStorage.async) { + // wrap sync apis with async ones. + _(syncApiNames).each(function (apiName) { + if (typeof localStorage[apiName] === 'function') { + localStorage[apiName + 'Async'] = function () { + return Promise.resolve(localStorage[apiName].apply(localStorage, arguments)); + }; + } + }); +} else { + _(syncApiNames).each(function (apiName) { + if (typeof localStorage[apiName] !== 'function') { + localStorage[apiName] = function () { + var error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.'); + error.code = 'SYNC_API_NOT_AVAILABLE'; + throw error; + }; + } + }); +} + +module.exports = localStorage; + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = '2.1.4'; + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + +var charenc = { + // UTF-8 encoding + utf8: { + // Convert a string to a byte array + stringToBytes: function(str) { + return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))); + }, + + // Convert a byte array to a string + bytesToString: function(bytes) { + return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))); + } + }, + + // Binary encoding + bin: { + // Convert a string to a byte array + stringToBytes: function(str) { + for (var bytes = [], i = 0; i < str.length; i++) + bytes.push(str.charCodeAt(i) & 0xFF); + return bytes; + }, + + // Convert a byte array to a string + bytesToString: function(bytes) { + for (var str = [], i = 0; i < bytes.length; i++) + str.push(String.fromCharCode(bytes[i])); + return str.join(''); + } + } +}; + +module.exports = charenc; + + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ + + + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +var Commons = __webpack_require__(10); +var CustomEventTarget = __webpack_require__(53); +var EventWrapper = __webpack_require__(54); +var LISTENERS = Commons.LISTENERS; +var CAPTURE = Commons.CAPTURE; +var BUBBLE = Commons.BUBBLE; +var ATTRIBUTE = Commons.ATTRIBUTE; +var newNode = Commons.newNode; +var defineCustomEventTarget = CustomEventTarget.defineCustomEventTarget; +var createEventWrapper = EventWrapper.createEventWrapper; +var STOP_IMMEDIATE_PROPAGATION_FLAG = + EventWrapper.STOP_IMMEDIATE_PROPAGATION_FLAG; + +//----------------------------------------------------------------------------- +// Constants +//----------------------------------------------------------------------------- + +/** + * A flag which shows there is the native `EventTarget` interface object. + * + * @type {boolean} + * @private + */ +var HAS_EVENTTARGET_INTERFACE = ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +); + +//----------------------------------------------------------------------------- +// Public Interface +//----------------------------------------------------------------------------- + +/** + * An implementation for `EventTarget` interface. + * + * @constructor + * @public + */ +var EventTarget = module.exports = function EventTarget() { + if (this instanceof EventTarget) { + // this[LISTENERS] is a Map. + // Its key is event type. + // Its value is ListenerNode object or null. + // + // interface ListenerNode { + // var listener: Function + // var kind: CAPTURE|BUBBLE|ATTRIBUTE + // var next: ListenerNode|null + // } + Object.defineProperty(this, LISTENERS, {value: Object.create(null)}); + } + else if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(EventTarget, arguments[0]); + } + else if (arguments.length > 0) { + var types = Array(arguments.length); + for (var i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + + // To use to extend with attribute listener properties. + // e.g. + // class MyCustomObject extends EventTarget("message", "error") { + // //... + // } + return defineCustomEventTarget(EventTarget, types); + } + else { + throw new TypeError("Cannot call a class as a function"); + } +}; + +EventTarget.prototype = Object.create( + (HAS_EVENTTARGET_INTERFACE ? window.EventTarget : Object).prototype, + { + constructor: { + value: EventTarget, + writable: true, + configurable: true + }, + + addEventListener: { + value: function addEventListener(type, listener, capture) { + if (listener == null) { + return false; + } + if (typeof listener !== "function" && typeof listener !== "object") { + throw new TypeError("\"listener\" is not an object."); + } + + var kind = (capture ? CAPTURE : BUBBLE); + var node = this[LISTENERS][type]; + if (node == null) { + this[LISTENERS][type] = newNode(listener, kind); + return true; + } + + var prev = null; + while (node != null) { + if (node.listener === listener && node.kind === kind) { + // Should ignore a duplicated listener. + return false; + } + prev = node; + node = node.next; + } + + prev.next = newNode(listener, kind); + return true; + }, + configurable: true, + writable: true + }, + + removeEventListener: { + value: function removeEventListener(type, listener, capture) { + if (listener == null) { + return false; + } + + var kind = (capture ? CAPTURE : BUBBLE); + var prev = null; + var node = this[LISTENERS][type]; + while (node != null) { + if (node.listener === listener && node.kind === kind) { + if (prev == null) { + this[LISTENERS][type] = node.next; + } + else { + prev.next = node.next; + } + return true; + } + + prev = node; + node = node.next; + } + + return false; + }, + configurable: true, + writable: true + }, + + dispatchEvent: { + value: function dispatchEvent(event) { + // If listeners aren't registered, terminate. + var node = this[LISTENERS][event.type]; + if (node == null) { + return true; + } + + // Since we cannot rewrite several properties, so wrap object. + var wrapped = createEventWrapper(event, this); + + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + while (node != null) { + if (typeof node.listener === "function") { + node.listener.call(this, wrapped); + } + else if (node.kind !== ATTRIBUTE && typeof node.listener.handleEvent === "function") { + node.listener.handleEvent(wrapped); + } + + if (wrapped[STOP_IMMEDIATE_PROPAGATION_FLAG]) { + break; + } + node = node.next; + } + + return !wrapped.defaultPrevented; + }, + configurable: true, + writable: true + } + } +); + + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + + +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var polyfill = __webpack_require__(24).polyfill; +window = window || {}; +polyfill(); +polyfill(window); +try { + localStorage = localStorage || __webpack_require__(12); +} catch (e) {} +try { + XMLHttpRequest = XMLHttpRequest || __webpack_require__(15); +} catch (e) {} +try { + FormData = FormData || __webpack_require__(9); +} catch (e) {} +try { + WebSocket = WebSocket || __webpack_require__(14); +} catch (e) {} +try { + navigator = navigator || __webpack_require__(13); +} catch (e) {} + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/*! + * LeanCloud JavaScript SDK + * https://leancloud.cn + * + * Copyright 2016 LeanCloud.cn, Inc. + * The LeanCloud JavaScript SDK is freely distributable under the MIT license. + */ + +var AV = __webpack_require__(6); + +AV._ = __webpack_require__(0); +AV.version = __webpack_require__(18); +AV.Promise = __webpack_require__(1); +AV.localStorage = __webpack_require__(17); +AV.Cache = __webpack_require__(16); +AV.Error = __webpack_require__(3); + +__webpack_require__(31); +__webpack_require__(27)(AV); +__webpack_require__(29)(AV); +__webpack_require__(25)(AV); +__webpack_require__(34)(AV); +__webpack_require__(37)(AV); +__webpack_require__(28)(AV); +__webpack_require__(33)(AV); +__webpack_require__(38)(AV); +__webpack_require__(46)(AV); +__webpack_require__(36)(AV); +__webpack_require__(26)(AV); +__webpack_require__(35)(AV); +__webpack_require__(40)(AV); +__webpack_require__(39)(AV); +__webpack_require__(32)(AV); + +module.exports = AV; + +/** + * Options to controll the authentication for an operation + * @typedef {Object} AuthOptions + * @property {String} [sessionToken] Specify a user to excute the operation as. + * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided. + * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set. + */ + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var localStorage = __webpack_require__(12); +var XMLHttpRequest = __webpack_require__(15); +var FormData = __webpack_require__(9); +var WebSocket = __webpack_require__(14); +var navigator = __webpack_require__(13); + +module.exports = { + polyfill: function polyfill() { + var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : global || window; + + if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) !== 'object') { + throw new Error('polyfill target is not an Object'); + } + var polyfills = { + localStorage: localStorage, + XMLHttpRequest: XMLHttpRequest, + FormData: FormData, + WebSocket: WebSocket, + Object: Object, + navigator: navigator + }; + for (var k in polyfills) { + if (!target[k]) target[k] = polyfills[k]; + } + }, + + localStorage: localStorage, + XMLHttpRequest: XMLHttpRequest, + FormData: FormData, + WebSocket: WebSocket +}; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + var PUBLIC_KEY = "*"; + + /** + * Creates a new ACL. + * If no argument is given, the ACL has no permissions for anyone. + * If the argument is a AV.User, the ACL will have read and write + * permission for only that user. + * If the argument is any other JSON object, that object will be interpretted + * as a serialized ACL created with toJSON(). + * @see AV.Object#setACL + * @class + * + *

An ACL, or Access Control List can be added to any + * AV.Object to restrict access to only a subset of users + * of your application.

+ */ + AV.ACL = function (arg1) { + var self = this; + self.permissionsById = {}; + if (_.isObject(arg1)) { + if (arg1 instanceof AV.User) { + self.setReadAccess(arg1, true); + self.setWriteAccess(arg1, true); + } else { + if (_.isFunction(arg1)) { + throw new Error('AV.ACL() called with a function. Did you forget ()?'); + } + AV._objectEach(arg1, function (accessList, userId) { + if (!_.isString(userId)) { + throw new Error('Tried to create an ACL with an invalid userId.'); + } + self.permissionsById[userId] = {}; + AV._objectEach(accessList, function (allowed, permission) { + if (permission !== "read" && permission !== "write") { + throw new Error('Tried to create an ACL with an invalid permission type.'); + } + if (!_.isBoolean(allowed)) { + throw new Error('Tried to create an ACL with an invalid permission value.'); + } + self.permissionsById[userId][permission] = allowed; + }); + }); + } + } + }; + + /** + * Returns a JSON-encoded version of the ACL. + * @return {Object} + */ + AV.ACL.prototype.toJSON = function () { + return _.clone(this.permissionsById); + }; + + AV.ACL.prototype._setAccess = function (accessType, userId, allowed) { + if (userId instanceof AV.User) { + userId = userId.id; + } else if (userId instanceof AV.Role) { + userId = "role:" + userId.getName(); + } + if (!_.isString(userId)) { + throw new Error('userId must be a string.'); + } + if (!_.isBoolean(allowed)) { + throw new Error('allowed must be either true or false.'); + } + var permissions = this.permissionsById[userId]; + if (!permissions) { + if (!allowed) { + // The user already doesn't have this permission, so no action needed. + return; + } else { + permissions = {}; + this.permissionsById[userId] = permissions; + } + } + + if (allowed) { + this.permissionsById[userId][accessType] = true; + } else { + delete permissions[accessType]; + if (_.isEmpty(permissions)) { + delete this.permissionsById[userId]; + } + } + }; + + AV.ACL.prototype._getAccess = function (accessType, userId) { + if (userId instanceof AV.User) { + userId = userId.id; + } else if (userId instanceof AV.Role) { + userId = "role:" + userId.getName(); + } + var permissions = this.permissionsById[userId]; + if (!permissions) { + return false; + } + return permissions[accessType] ? true : false; + }; + + /** + * Set whether the given user is allowed to read this object. + * @param userId An instance of AV.User or its objectId. + * @param {Boolean} allowed Whether that user should have read access. + */ + AV.ACL.prototype.setReadAccess = function (userId, allowed) { + this._setAccess("read", userId, allowed); + }; + + /** + * Get whether the given user id is *explicitly* allowed to read this object. + * Even if this returns false, the user may still be able to access it if + * getPublicReadAccess returns true or a role that the user belongs to has + * write access. + * @param userId An instance of AV.User or its objectId, or a AV.Role. + * @return {Boolean} + */ + AV.ACL.prototype.getReadAccess = function (userId) { + return this._getAccess("read", userId); + }; + + /** + * Set whether the given user id is allowed to write this object. + * @param userId An instance of AV.User or its objectId, or a AV.Role.. + * @param {Boolean} allowed Whether that user should have write access. + */ + AV.ACL.prototype.setWriteAccess = function (userId, allowed) { + this._setAccess("write", userId, allowed); + }; + + /** + * Get whether the given user id is *explicitly* allowed to write this object. + * Even if this returns false, the user may still be able to write it if + * getPublicWriteAccess returns true or a role that the user belongs to has + * write access. + * @param userId An instance of AV.User or its objectId, or a AV.Role. + * @return {Boolean} + */ + AV.ACL.prototype.getWriteAccess = function (userId) { + return this._getAccess("write", userId); + }; + + /** + * Set whether the public is allowed to read this object. + * @param {Boolean} allowed + */ + AV.ACL.prototype.setPublicReadAccess = function (allowed) { + this.setReadAccess(PUBLIC_KEY, allowed); + }; + + /** + * Get whether the public is allowed to read this object. + * @return {Boolean} + */ + AV.ACL.prototype.getPublicReadAccess = function () { + return this.getReadAccess(PUBLIC_KEY); + }; + + /** + * Set whether the public is allowed to write this object. + * @param {Boolean} allowed + */ + AV.ACL.prototype.setPublicWriteAccess = function (allowed) { + this.setWriteAccess(PUBLIC_KEY, allowed); + }; + + /** + * Get whether the public is allowed to write this object. + * @return {Boolean} + */ + AV.ACL.prototype.getPublicWriteAccess = function () { + return this.getWriteAccess(PUBLIC_KEY); + }; + + /** + * Get whether users belonging to the given role are allowed + * to read this object. Even if this returns false, the role may + * still be able to write it if a parent role has read access. + * + * @param role The name of the role, or a AV.Role object. + * @return {Boolean} true if the role has read access. false otherwise. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.getRoleReadAccess = function (role) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + return this.getReadAccess("role:" + role); + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Get whether users belonging to the given role are allowed + * to write this object. Even if this returns false, the role may + * still be able to write it if a parent role has write access. + * + * @param role The name of the role, or a AV.Role object. + * @return {Boolean} true if the role has write access. false otherwise. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.getRoleWriteAccess = function (role) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + return this.getWriteAccess("role:" + role); + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Set whether users belonging to the given role are allowed + * to read this object. + * + * @param role The name of the role, or a AV.Role object. + * @param {Boolean} allowed Whether the given role can read this object. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.setRoleReadAccess = function (role, allowed) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + this.setReadAccess("role:" + role, allowed); + return; + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Set whether users belonging to the given role are allowed + * to write this object. + * + * @param role The name of the role, or a AV.Role object. + * @param {Boolean} allowed Whether the given role can write this object. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.setRoleWriteAccess = function (role, allowed) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + this.setWriteAccess("role:" + role, allowed); + return; + } + throw new Error('role must be a AV.Role or a String'); + }; +}; + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * Contains functions for calling and declaring + *

+ * Some functions are only available from Cloud Code. + *

+ * + * @namespace + */ + AV.Cloud = AV.Cloud || {}; + + _.extend(AV.Cloud, /** @lends AV.Cloud */{ + /** + * Makes a call to a cloud function. + * @param {String} name The function name. + * @param {Object} data The parameters to send to the cloud function. + * @param {AuthOptions} options + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + run: function run(name, data, options) { + var request = AVRequest('functions', name, null, 'POST', AV._encode(data, null, true), options); + + return request.then(function (resp) { + return AV._decode(resp).result; + }); + }, + + /** + * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response + * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object} + * @param {String} name The function name. + * @param {Object} data The parameters to send to the cloud function. + * @param {AuthOptions} options + * @return {Promise} A promise that will be resolved with the result of the function. + */ + rpc: function rpc(name, data, options) { + if (_.isArray(data)) { + return Promise.reject(new Error('Can\'t pass Array as the param of rpc function in JavaScript SDK.')); + } + + return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function (resp) { + return AV._decode(resp).result; + }); + }, + + /** + * Make a call to request server date time. + * @return {Promise.} A promise that will be resolved with the result + * of the function. + * @since 0.5.9 + */ + getServerDate: function getServerDate() { + var request = AVRequest("date", null, null, 'GET'); + + return request.then(function (resp) { + return AV._decode(resp); + }); + }, + + /** + * Makes a call to request a sms code for operation verification. + * @param {Object} data The mobile phone number string or a JSON + * object that contains mobilePhoneNumber,template,op,ttl,name etc. + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + requestSmsCode: function requestSmsCode(data) { + if (_.isString(data)) { + data = { mobilePhoneNumber: data }; + } + if (!data.mobilePhoneNumber) { + throw new Error('Missing mobilePhoneNumber.'); + } + var request = AVRequest("requestSmsCode", null, null, 'POST', data); + return request; + }, + + /** + * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode + * @param {String} code The sms code sent by AV.Cloud.requestSmsCode + * @param {phone} phone The mobile phoner number(optional). + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + verifySmsCode: function verifySmsCode(code, phone) { + if (!code) throw new Error('Missing sms code.'); + var params = {}; + if (_.isString(phone)) { + params['mobilePhoneNumber'] = phone; + } + + var request = AVRequest("verifySmsCode", code, null, 'POST', params); + return request; + } + }); +}; + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + var eventSplitter = /\s+/; + var slice = Array.prototype.slice; + + /** + * @class + * + *

AV.Events is a fork of Backbone's Events module, provided for your + * convenience.

+ * + *

A module that can be mixed in to any object in order to provide + * it with custom events. You may bind callback functions to an event + * with `on`, or remove these functions with `off`. + * Triggering an event fires all callbacks in the order that `on` was + * called. + * + * @private + * @example + * var object = {}; + * _.extend(object, AV.Events); + * object.on('expand', function(){ alert('expanded'); }); + * object.trigger('expand');

+ * + */ + AV.Events = { + /** + * Bind one or more space separated events, `events`, to a `callback` + * function. Passing `"all"` will bind the callback to all events fired. + */ + on: function on(events, callback, context) { + + var calls, event, node, tail, list; + if (!callback) { + return this; + } + events = events.split(eventSplitter); + calls = this._callbacks || (this._callbacks = {}); + + // Create an immutable callback list, allowing traversal during + // modification. The tail is an empty object that will always be used + // as the next node. + event = events.shift(); + while (event) { + list = calls[event]; + node = list ? list.tail : {}; + node.next = tail = {}; + node.context = context; + node.callback = callback; + calls[event] = { tail: tail, next: list ? list.next : node }; + event = events.shift(); + } + + return this; + }, + + /** + * Remove one or many callbacks. If `context` is null, removes all callbacks + * with that function. If `callback` is null, removes all callbacks for the + * event. If `events` is null, removes all bound callbacks for all events. + */ + off: function off(events, callback, context) { + var event, calls, node, tail, cb, ctx; + + // No events, or removing *all* events. + if (!(calls = this._callbacks)) { + return; + } + if (!(events || callback || context)) { + delete this._callbacks; + return this; + } + + // Loop through the listed events and contexts, splicing them out of the + // linked list of callbacks if appropriate. + events = events ? events.split(eventSplitter) : _.keys(calls); + event = events.shift(); + while (event) { + node = calls[event]; + delete calls[event]; + if (!node || !(callback || context)) { + continue; + } + // Create a new list, omitting the indicated callbacks. + tail = node.tail; + node = node.next; + while (node !== tail) { + cb = node.callback; + ctx = node.context; + if (callback && cb !== callback || context && ctx !== context) { + this.on(event, cb, ctx); + } + node = node.next; + } + event = events.shift(); + } + + return this; + }, + + /** + * Trigger one or many events, firing all bound callbacks. Callbacks are + * passed the same arguments as `trigger` is, apart from the event name + * (unless you're listening on `"all"`, which will cause your callback to + * receive the true name of the event as the first argument). + */ + trigger: function trigger(events) { + var event, node, calls, tail, args, all, rest; + if (!(calls = this._callbacks)) { + return this; + } + all = calls.all; + events = events.split(eventSplitter); + rest = slice.call(arguments, 1); + + // For each event, walk through the linked list of callbacks twice, + // first to trigger the event, then to trigger any `"all"` callbacks. + event = events.shift(); + while (event) { + node = calls[event]; + if (node) { + tail = node.tail; + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, rest); + } + } + node = all; + if (node) { + tail = node.tail; + args = [event].concat(rest); + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, args); + } + } + event = events.shift(); + } + + return this; + } + }; + + /** + * @function + */ + AV.Events.bind = AV.Events.on; + + /** + * @function + */ + AV.Events.unbind = AV.Events.off; +}; + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var cos = __webpack_require__(43); +var qiniu = __webpack_require__(44); +var s3 = __webpack_require__(45); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var Promise = __webpack_require__(1); + +var _require = __webpack_require__(4), + tap = _require.tap; + +var debug = __webpack_require__(5)('leancloud:file'); +var parseBase64 = __webpack_require__(48); + +module.exports = function (AV) { + + // 挂载一些配置 + var avConfig = AV._config; + + var hexOctet = function hexOctet() { + return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + }; + + // port from browserify path module + // since react-native packager won't shim node modules. + var extname = function extname(path) { + return path.match(/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/)[4]; + }; + + var b64Digit = function b64Digit(number) { + if (number < 26) { + return String.fromCharCode(65 + number); + } + if (number < 52) { + return String.fromCharCode(97 + (number - 26)); + } + if (number < 62) { + return String.fromCharCode(48 + (number - 52)); + } + if (number === 62) { + return '+'; + } + if (number === 63) { + return '/'; + } + throw new Error('Tried to encode large digit ' + number + ' in base64.'); + }; + + var encodeBase64 = function encodeBase64(array) { + var chunks = []; + chunks.length = Math.ceil(array.length / 3); + _.times(chunks.length, function (i) { + var b1 = array[i * 3]; + var b2 = array[i * 3 + 1] || 0; + var b3 = array[i * 3 + 2] || 0; + + var has2 = i * 3 + 1 < array.length; + var has3 = i * 3 + 2 < array.length; + + chunks[i] = [b64Digit(b1 >> 2 & 0x3F), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0F), has2 ? b64Digit(b2 << 2 & 0x3C | b3 >> 6 & 0x03) : "=", has3 ? b64Digit(b3 & 0x3F) : "="].join(""); + }); + return chunks.join(""); + }; + + /** + * An AV.File is a local representation of a file that is saved to the AV + * cloud. + * @param name {String} The file's name. This will change to a unique value + * once the file has finished saving. + * @param data {Array} The data for the file, as either: + * 1. an Array of byte value Numbers, or + * 2. an Object like { base64: "..." } with a base64-encoded String. + * 3. a File object selected with a file upload control. (3) only works + * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+. + * 4.a Buffer object in Node.js runtime. + * + * For example:
+   * var fileUploadControl = $("#profilePhotoFileUpload")[0];
+   * if (fileUploadControl.files.length > 0) {
+   *   var file = fileUploadControl.files[0];
+   *   var name = "photo.jpg";
+   *   var file = new AV.File(name, file);
+   *   file.save().then(function() {
+   *     // The file has been saved to AV.
+   *   }, function(error) {
+   *     // The file either could not be read, or could not be saved to AV.
+   *   });
+   * }
+ * + * @class + * @param [mimeType] {String} Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + */ + AV.File = function (name, data, mimeType) { + + this.attributes = { + name: name, + url: '', + metaData: {}, + // 用来存储转换后要上传的 base64 String + base64: '' + }; + + if (_.isString(data)) { + throw new TypeError("Creating an AV.File from a String is not yet supported."); + } + if (_.isArray(data)) { + this.attributes.metaData.size = data.length; + data = { base64: encodeBase64(data) }; + } + + this._extName = ''; + this._data = data; + + var owner = void 0; + if (data && data.owner) { + owner = data.owner; + } else if (!AV._config.disableCurrentUser) { + try { + owner = AV.User.current(); + } catch (error) { + if ('SYNC_API_NOT_AVAILABLE' === error.code) { + console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().'); + } else { + throw error; + } + } + } + + this.attributes.metaData.owner = owner ? owner.id : 'unknown'; + + this.set('mime_type', mimeType); + }; + + /** + * Creates a fresh AV.File object with exists url for saving to AVOS Cloud. + * @param {String} name the file name + * @param {String} url the file url. + * @param {Object} [metaData] the file metadata object. + * @param {String} [type] Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + * @return {AV.File} the file object + */ + AV.File.withURL = function (name, url, metaData, type) { + if (!name || !url) { + throw new Error("Please provide file name and url"); + } + var file = new AV.File(name, null, type); + //copy metaData properties to file. + if (metaData) { + for (var prop in metaData) { + if (!file.attributes.metaData[prop]) file.attributes.metaData[prop] = metaData[prop]; + } + } + file.attributes.url = url; + //Mark the file is from external source. + file.attributes.metaData.__source = 'external'; + return file; + }; + + /** + * Creates a file object with exists objectId. + * @param {String} objectId The objectId string + * @return {AV.File} the file object + */ + AV.File.createWithoutData = function (objectId) { + var file = new AV.File(); + file.id = objectId; + return file; + }; + + AV.File.prototype = { + className: '_File', + + _toFullJSON: function _toFullJSON(seenObjects) { + var _this = this; + + var json = _.clone(this.attributes); + AV._objectEach(json, function (val, key) { + json[key] = AV._encode(val, seenObjects); + }); + AV._objectEach(this._operations, function (val, key) { + json[key] = val; + }); + + if (_.has(this, "id")) { + json.objectId = this.id; + } + _(['createdAt', 'updatedAt']).each(function (key) { + if (_.has(_this, key)) { + var val = _this[key]; + json[key] = _.isDate(val) ? val.toJSON() : val; + } + }); + json.__type = "File"; + return json; + }, + toJSON: function toJSON() { + var json = this._toFullJSON(); + // add id and keep __type for backward compatible + if (_.has(this, 'id')) { + json.id = this.id; + } + return json; + }, + + + /** + * Returns the ACL for this file. + * @returns {AV.ACL} An instance of AV.ACL. + */ + getACL: function getACL() { + return this._acl; + }, + + /** + * Sets the ACL to be used for this file. + * @param {AV.ACL} acl An instance of AV.ACL. + */ + setACL: function setACL(acl) { + if (!(acl instanceof AV.ACL)) { + return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.'); + } + this._acl = acl; + }, + + /** + * Gets the name of the file. Before save is called, this is the filename + * given by the user. After save is called, that name gets prefixed with a + * unique identifier. + */ + name: function name() { + return this.get('name'); + }, + + /** + * Gets the url of the file. It is only available after you save the file or + * after you get the file from a AV.Object. + * @return {String} + */ + url: function url() { + return this.get('url'); + }, + + /** + * Gets the attributs of the file object. + * @param {String} The attribute name which want to get. + * @returns {Any} + */ + get: function get(attrName) { + switch (attrName) { + case 'objectId': + return this.id; + case 'url': + case 'name': + case 'mime_type': + case 'metaData': + case 'createdAt': + case 'updatedAt': + return this.attributes[attrName]; + default: + return this.attributes.metaData[attrName]; + } + }, + + /** + * Set the metaData of the file object. + * @param {Object} Object is an key value Object for setting metaData. + * @param {String} attr is an optional metadata key. + * @param {Object} value is an optional metadata value. + * @returns {String|Number|Array|Object} + */ + set: function set() { + var _this2 = this; + + var set = function set(attrName, value) { + switch (attrName) { + case 'name': + case 'url': + case 'mime_type': + case 'base64': + case 'metaData': + _this2.attributes[attrName] = value; + break; + default: + // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面 + _this2.attributes.metaData[attrName] = value; + break; + } + }; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + switch (args.length) { + case 1: + // 传入一个 Object + for (var k in args[0]) { + set(k, args[0][k]); + } + break; + case 2: + set(args[0], args[1]); + break; + } + }, + + /** + *

Returns the file's metadata JSON object if no arguments is given.Returns the + * metadata value if a key is given.Set metadata value if key and value are both given.

+ *

+    *  var metadata = file.metaData(); //Get metadata JSON object.
+    *  var size = file.metaData('size');  // Get the size metadata value.
+    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.
+    *

+ * @return {Object} The file's metadata JSON object. + * @param {String} attr an optional metadata key. + * @param {Object} value an optional metadata value. + **/ + metaData: function metaData(attr, value) { + if (attr && value) { + this.attributes.metaData[attr] = value; + return this; + } else if (attr && !value) { + return this.attributes.metaData[attr]; + } else { + return this.attributes.metaData; + } + }, + + /** + * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。 + * @return {String} 缩略图URL + * @param {Number} width 宽度,单位:像素 + * @param {Number} heigth 高度,单位:像素 + * @param {Number} quality 质量,1-100的数字,默认100 + * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。 + * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。 + */ + + thumbnailURL: function thumbnailURL(width, height, quality, scaleToFit, fmt) { + var url = this.attributes.url; + if (!url) { + throw new Error('Invalid url.'); + } + if (!width || !height || width <= 0 || height <= 0) { + throw new Error('Invalid width or height value.'); + } + quality = quality || 100; + scaleToFit = !scaleToFit ? true : scaleToFit; + if (quality <= 0 || quality > 100) { + throw new Error('Invalid quality value.'); + } + fmt = fmt || 'png'; + var mode = scaleToFit ? 2 : 1; + return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt; + }, + + /** + * Returns the file's size. + * @return {Number} The file's size in bytes. + **/ + size: function size() { + return this.metaData().size; + }, + + /** + * Returns the file's owner. + * @return {String} The file's owner id. + */ + ownerId: function ownerId() { + return this.metaData().owner; + }, + + /** + * Destroy the file. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + if (!this.id) { + return Promise.reject(new Error('The file id is not eixsts.')); + } + var request = AVRequest("files", null, this.id, 'DELETE', null, options); + return request; + }, + + /** + * Request Qiniu upload token + * @param {string} type + * @return {Promise} Resolved with the response + * @private + */ + _fileToken: function _fileToken(type) { + var route = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'fileTokens'; + + var name = this.attributes.name; + + var extName = extname(name); + if (!extName && this._extName) { + name += this._extName; + extName = this._extName; + } + // Create 16-bits uuid as qiniu key. + var key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName; + var data = { + key: key, + name: name, + ACL: this._acl, + mime_type: type, + metaData: this.attributes.metaData + }; + this._qiniu_key = key; + return AVRequest(route, null, null, 'POST', data); + }, + + + /** + * @callback UploadProgressCallback + * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes + */ + /** + * Saves the file to the AV cloud. + * @param {Object} [options] + * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。 + * @return {Promise} Promise that is resolved when the save finishes. + */ + save: function save(options) { + var _this3 = this; + + if (this.id) { + throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.'); + } + if (!this._previousSave) { + if (this._data) { + var mimeType = this.get('mime_type'); + this._previousSave = this._fileToken(mimeType).then(function (uploadInfo) { + if (uploadInfo.mime_type) { + mimeType = uploadInfo.mime_type; + _this3.set('mime_type', mimeType); + } + _this3._token = uploadInfo.token; + return Promise.resolve().then(function () { + var data = _this3._data; + if (data && data.base64) { + return parseBase64(data.base64, mimeType); + } + if (data && data.blob) { + if (!data.blob.type && mimeType) { + data.blob.type = mimeType; + } + if (!data.blob.name) { + data.blob.name = _this3.get('name'); + } + if (true) { + _this3._extName = extname(data.blob.uri); + } + return data.blob; + } + if (typeof File !== "undefined" && data instanceof File) { + if (data.size) { + _this3.attributes.metaData.size = data.size; + } + if (data.name) { + _this3._extName = extname(data.name); + } + return data; + } + if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) { + _this3.attributes.metaData.size = data.length; + return data; + } + throw new TypeError('malformed file data'); + }).then(function (data) { + var uploadPromise = void 0; + switch (uploadInfo.provider) { + case 's3': + uploadPromise = s3(uploadInfo, data, _this3, options); + break; + case 'qcloud': + uploadPromise = cos(uploadInfo, data, _this3, options); + break; + case 'qiniu': + default: + uploadPromise = qiniu(uploadInfo, data, _this3, options); + break; + } + return uploadPromise.then(tap(function () { + return _this3._callback(true); + }), function (error) { + _this3._callback(false); + throw error; + }); + }); + }); + } else if (this.attributes.url && this.attributes.metaData.__source === 'external') { + // external link file. + var data = { + name: this.attributes.name, + ACL: this._acl, + metaData: this.attributes.metaData, + mime_type: this.mimeType, + url: this.attributes.url + }; + this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then(function (response) { + _this3.attributes.name = response.name; + _this3.attributes.url = response.url; + _this3.id = response.objectId; + if (response.size) { + _this3.attributes.metaData.size = response.size; + } + return _this3; + }); + } + } + return this._previousSave; + }, + _callback: function _callback(success) { + AVRequest('fileCallback', null, null, 'post', { + token: this._token, + result: success + }).catch(debug); + delete this._token; + delete this._data; + }, + + + /** + * fetch the file from server. If the server's representation of the + * model differs from its current attributes, they will be overriden, + * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option. + * @return {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch: function fetch(options) { + var options = null; + + var request = AVRequest('files', null, this.id, 'GET', options); + return request.then(this._finishFetch.bind(this)); + }, + _finishFetch: function _finishFetch(response) { + var value = AV.Object.prototype.parse(response); + value.attributes = { + name: value.name, + url: value.url, + mime_type: value.mime_type, + bucket: value.bucket + }; + value.attributes.metaData = value.metaData || {}; + value.id = value.objectId; + // clean + delete value.objectId; + delete value.metaData; + delete value.url; + delete value.name; + delete value.mime_type; + delete value.bucket; + _.extend(this, value); + return this; + } + }; +}; + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +/*global navigator: false */ +module.exports = function (AV) { + /** + * Creates a new GeoPoint with any of the following forms:
+ * @example + * new GeoPoint(otherGeoPoint) + * new GeoPoint(30, 30) + * new GeoPoint([30, 30]) + * new GeoPoint({latitude: 30, longitude: 30}) + * new GeoPoint() // defaults to (0, 0) + * @class + * + *

Represents a latitude / longitude point that may be associated + * with a key in a AVObject or used as a reference point for geo queries. + * This allows proximity-based queries on the key.

+ * + *

Only one key in a class may contain a GeoPoint.

+ * + *

Example:

+   *   var point = new AV.GeoPoint(30.0, -20.0);
+   *   var object = new AV.Object("PlaceObject");
+   *   object.set("location", point);
+   *   object.save();

+ */ + AV.GeoPoint = function (arg1, arg2) { + if (_.isArray(arg1)) { + AV.GeoPoint._validate(arg1[0], arg1[1]); + this.latitude = arg1[0]; + this.longitude = arg1[1]; + } else if (_.isObject(arg1)) { + AV.GeoPoint._validate(arg1.latitude, arg1.longitude); + this.latitude = arg1.latitude; + this.longitude = arg1.longitude; + } else if (_.isNumber(arg1) && _.isNumber(arg2)) { + AV.GeoPoint._validate(arg1, arg2); + this.latitude = arg1; + this.longitude = arg2; + } else { + this.latitude = 0; + this.longitude = 0; + } + + // Add properties so that anyone using Webkit or Mozilla will get an error + // if they try to set values that are out of bounds. + var self = this; + if (this.__defineGetter__ && this.__defineSetter__) { + // Use _latitude and _longitude to actually store the values, and add + // getters and setters for latitude and longitude. + this._latitude = this.latitude; + this._longitude = this.longitude; + this.__defineGetter__("latitude", function () { + return self._latitude; + }); + this.__defineGetter__("longitude", function () { + return self._longitude; + }); + this.__defineSetter__("latitude", function (val) { + AV.GeoPoint._validate(val, self.longitude); + self._latitude = val; + }); + this.__defineSetter__("longitude", function (val) { + AV.GeoPoint._validate(self.latitude, val); + self._longitude = val; + }); + } + }; + + /** + * @lends AV.GeoPoint.prototype + * @property {float} latitude North-south portion of the coordinate, in range + * [-90, 90]. Throws an exception if set out of range in a modern browser. + * @property {float} longitude East-west portion of the coordinate, in range + * [-180, 180]. Throws if set out of range in a modern browser. + */ + + /** + * Throws an exception if the given lat-long is out of bounds. + * @private + */ + AV.GeoPoint._validate = function (latitude, longitude) { + if (latitude < -90.0) { + throw new Error("AV.GeoPoint latitude " + latitude + " < -90.0."); + } + if (latitude > 90.0) { + throw new Error("AV.GeoPoint latitude " + latitude + " > 90.0."); + } + if (longitude < -180.0) { + throw new Error("AV.GeoPoint longitude " + longitude + " < -180.0."); + } + if (longitude > 180.0) { + throw new Error("AV.GeoPoint longitude " + longitude + " > 180.0."); + } + }; + + /** + * Creates a GeoPoint with the user's current location, if available. + * @return {Promise.} + */ + AV.GeoPoint.current = function () { + return new AV.Promise(function (resolve, reject) { + navigator.geolocation.getCurrentPosition(function (location) { + resolve(new AV.GeoPoint({ + latitude: location.coords.latitude, + longitude: location.coords.longitude + })); + }, reject); + }); + }; + + AV.GeoPoint.prototype = { + /** + * Returns a JSON representation of the GeoPoint, suitable for AV. + * @return {Object} + */ + toJSON: function toJSON() { + AV.GeoPoint._validate(this.latitude, this.longitude); + return { + "__type": "GeoPoint", + latitude: this.latitude, + longitude: this.longitude + }; + }, + + /** + * Returns the distance from this GeoPoint to another in radians. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + radiansTo: function radiansTo(point) { + var d2r = Math.PI / 180.0; + var lat1rad = this.latitude * d2r; + var long1rad = this.longitude * d2r; + var lat2rad = point.latitude * d2r; + var long2rad = point.longitude * d2r; + var deltaLat = lat1rad - lat2rad; + var deltaLong = long1rad - long2rad; + var sinDeltaLatDiv2 = Math.sin(deltaLat / 2); + var sinDeltaLongDiv2 = Math.sin(deltaLong / 2); + // Square of half the straight line chord distance between both points. + var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2; + a = Math.min(1.0, a); + return 2 * Math.asin(Math.sqrt(a)); + }, + + /** + * Returns the distance from this GeoPoint to another in kilometers. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + kilometersTo: function kilometersTo(point) { + return this.radiansTo(point) * 6371.0; + }, + + /** + * Returns the distance from this GeoPoint to another in miles. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + milesTo: function milesTo(point) { + return this.radiansTo(point) * 3958.8; + } + }; +}; + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +__webpack_require__(22); + +module.exports = __webpack_require__(23); + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var AV = __webpack_require__(6); +var request = __webpack_require__(2); + +var initialize = function initialize(appId, appKey, masterKey, hookKey) { + if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) { + console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.'); + } + AV.applicationId = appId; + AV.applicationKey = appKey; + AV.masterKey = masterKey; + if (false) { + AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY; + } + AV._useMasterKey = false; +}; + +var masterKeyWarn = function masterKeyWarn() { + console.warn('MasterKey is not supposed to be used in browser.'); +}; + +/** + * Call this method first to set up your authentication tokens for AV. + * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn . + * @function AV.init + * @param {Object} options + * @param {String} options.appId application id + * @param {String} options.appKey application key + * @param {String} options.masterKey application master key +*/ + +AV.init = function () { + if (arguments.length === 1) { + var options = arguments.length <= 0 ? undefined : arguments[0]; + if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { + if ("Weapp" && options.masterKey) { + masterKeyWarn(); + } + initialize(options.appId, options.appKey, options.masterKey, options.hookKey); + request.setServerUrlByRegion(options.region); + } else { + throw new Error('AV.init(): Parameter is not correct.'); + } + } else { + // 兼容旧版本的初始化方法 + if ("Weapp" && (arguments.length <= 3 ? undefined : arguments[3])) { + masterKeyWarn(); + } + initialize.apply(undefined, arguments); + request.setServerUrlByRegion('cn'); + } +}; + +// If we're running in node.js, allow using the master key. +if (false) { + AV.Cloud = AV.Cloud || {}; + /** + * Switches the LeanCloud SDK to using the Master key. The Master key grants + * priveleged access to the data in LeanCloud and can be used to bypass ACLs and + * other restrictions that are applied to the client SDKs. + *

Available in Cloud Code and Node.js only. + *

+ */ + AV.Cloud.useMasterKey = function () { + AV._useMasterKey = true; + }; +} + +// 兼容老版本的初始化方法 +AV.initialize = AV.init; + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * 包含了使用了 LeanCloud + * 离线数据分析功能的函数。 + *

+ * 仅在云引擎运行环境下有效。 + *

+ * @namespace + */ + AV.Insight = AV.Insight || {}; + + _.extend(AV.Insight, /** @lends AV.Insight */{ + + /** + * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用 + * AV.Insight.JobQuery 查询任务状态和结果。 + * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
+     *                   { "sql" : "select count(*) as c,gender from _User group by gender",
+     *                     "saveAs": {
+     *                         "className" : "UserGender",
+     *                         "limit": 1
+     *                      }
+     *                   }
+     *                  
+ * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。 + * @param {AuthOptions} [options] + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + startJob: function startJob(jobConfig, options) { + if (!jobConfig || !jobConfig.sql) { + throw new Error('Please provide the sql to run the job.'); + } + var data = { + jobConfig: jobConfig, + appId: AV.applicationId + }; + var request = AVRequest("bigquery", 'jobs', null, 'POST', AV._encode(data, null, true), options); + + return request.then(function (resp) { + return AV._decode(resp).id; + }); + }, + + /** + * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。 + *

+ * 仅在云引擎运行环境下有效。 + *

+ * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成 + * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息, + * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。 + * + */ + on: function on(event, cb) {} + }); + + /** + * 创建一个对象,用于查询 Insight 任务状态和结果。 + * @class + * @param {String} id 任务 id + * @since 0.5.5 + */ + AV.Insight.JobQuery = function (id, className) { + if (!id) { + throw new Error('Please provide the job id.'); + } + this.id = id; + this.className = className; + this._skip = 0; + this._limit = 100; + }; + + AV.Insight.JobQuery.prototype = { + + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * @param {Number} n the number of results to skip. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + skip: function skip(n) { + this._skip = n; + return this; + }, + + /** + * Sets the limit of the number of results to return. The default limit is + * 100, with a maximum of 1000 results being returned at a time. + * @param {Number} n the number of results to limit to. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + limit: function limit(n) { + this._limit = n; + return this; + }, + + /** + * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数, + * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间 + * startTime、endTime 等信息。 + * + * @param {AuthOptions} [options] + * @return {Promise} A promise that will be resolved with the result + * of the function. + * + */ + find: function find(options) { + var params = { + skip: this._skip, + limit: this._limit + }; + + var request = AVRequest("bigquery", 'jobs', this.id, "GET", params, options); + var self = this; + return request.then(function (response) { + if (response.error) { + return AV.Promise.reject(new AVError(response.code, response.error)); + } + return AV.Promise.resolve(response); + }); + } + + }; +}; + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var utils = __webpack_require__(4); + +var RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt']; +var checkReservedKey = function checkReservedKey(key) { + if (RESERVED_KEYS.indexOf(key) !== -1) { + throw new Error('key[' + key + '] is reserved'); + } +}; + +// AV.Object is analogous to the Java AVObject. +// It also implements the same interface as a Backbone model. + +module.exports = function (AV) { + /** + * Creates a new model with defined attributes. A client id (cid) is + * automatically generated and assigned for you. + * + *

You won't normally call this method directly. It is recommended that + * you use a subclass of AV.Object instead, created by calling + * extend.

+ * + *

However, if you don't want to use a subclass, or aren't sure which + * subclass is appropriate, you can use this form:

+   *     var object = new AV.Object("ClassName");
+   * 
+ * That is basically equivalent to:
+   *     var MyClass = AV.Object.extend("ClassName");
+   *     var object = new MyClass();
+   * 

+ * + * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @see AV.Object.extend + * + * @class + * + *

The fundamental unit of AV data, which implements the Backbone Model + * interface.

+ */ + AV.Object = function (attributes, options) { + // Allow new AV.Object("ClassName") as a shortcut to _create. + if (_.isString(attributes)) { + return AV.Object._create.apply(this, arguments); + } + + attributes = attributes || {}; + if (options && options.parse) { + attributes = this.parse(attributes); + attributes = this._mergeMagicFields(attributes); + } + var defaults = AV._getValue(this, 'defaults'); + if (defaults) { + attributes = _.extend({}, defaults, attributes); + } + if (options && options.collection) { + this.collection = options.collection; + } + + this._serverData = {}; // The last known data for this object from cloud. + this._opSetQueue = [{}]; // List of sets of changes to the data. + this._flags = {}; + this.attributes = {}; // The best estimate of this's current data. + + this._hashedJSON = {}; // Hash of values of containers at last save. + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this.set(attributes, { silent: true }); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this._hasData = true; + this._previousAttributes = _.clone(this.attributes); + this.initialize.apply(this, arguments); + }; + + /** + * @lends AV.Object.prototype + * @property {String} id The objectId of the AV Object. + */ + + /** + * Saves the given list of AV.Object. + * If any error is encountered, stops and calls the error handler. + * + *
+   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {
+   *     // All the objects were saved.
+   *   }, function(error) {
+   *     // An error occurred while saving one of the objects.
+   *   });
+   *
+   * @param {Array} list A list of AV.Object.
+   */
+  AV.Object.saveAll = function (list, options) {
+    return AV.Object._deepSaveAsync(list, null, options);
+  };
+
+  /**
+   * Fetch the given list of AV.Object.
+   *
+   * @param {AV.Object[]} objects A list of AV.Object
+   * @param {AuthOptions} options
+   * @return {Promise.} The given list of AV.Object, updated
+   */
+
+  AV.Object.fetchAll = function (objects, options) {
+    return AV.Promise.resolve().then(function () {
+      return AVRequest('batch', null, null, 'POST', {
+        requests: _.map(objects, function (object) {
+          if (!object.className) throw new Error('object must have className to fetch');
+          if (!object.id) throw new Error('object must have id to fetch');
+          if (object.dirty()) throw new Error('object is modified but not saved');
+          return {
+            method: 'GET',
+            path: '/1.1/classes/' + object.className + '/' + object.id
+          };
+        })
+      }, options);
+    }).then(function (response) {
+      _.forEach(objects, function (object, i) {
+        if (response[i].success) {
+          object._finishFetch(object.parse(response[i].success));
+        } else {
+          var error = new Error(response[i].error.error);
+          error.code = response[i].error.code;
+          throw error;
+        }
+      });
+      return objects;
+    });
+  };
+
+  // Attach all inheritable methods to the AV.Object prototype.
+  _.extend(AV.Object.prototype, AV.Events,
+  /** @lends AV.Object.prototype */{
+    _fetchWhenSave: false,
+
+    /**
+     * Initialize is an empty function by default. Override it with your own
+     * initialization logic.
+     */
+    initialize: function initialize() {},
+
+    /**
+      * Set whether to enable fetchWhenSave option when updating object.
+      * When set true, SDK would fetch the latest object after saving.
+      * Default is false.
+      *
+      * @deprecated use AV.Object#save with options.fetchWhenSave instead
+      * @param {boolean} enable  true to enable fetchWhenSave option.
+      */
+    fetchWhenSave: function fetchWhenSave(enable) {
+      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');
+      if (!_.isBoolean(enable)) {
+        throw new Error('Expect boolean value for fetchWhenSave');
+      }
+      this._fetchWhenSave = enable;
+    },
+
+    /**
+     * Returns the object's objectId.
+     * @return {String} the objectId.
+     */
+    getObjectId: function getObjectId() {
+      return this.id;
+    },
+
+    /**
+     * Returns the object's createdAt attribute.
+     * @return {Date}
+     */
+    getCreatedAt: function getCreatedAt() {
+      return this.createdAt || this.get('createdAt');
+    },
+
+    /**
+     * Returns the object's updatedAt attribute.
+     * @return {Date}
+     */
+    getUpdatedAt: function getUpdatedAt() {
+      return this.updatedAt || this.get('updatedAt');
+    },
+
+    /**
+     * Returns a JSON version of the object suitable for saving to AV.
+     * @return {Object}
+     */
+    toJSON: function toJSON() {
+      var json = this._toFullJSON();
+      AV._arrayEach(["__type", "className"], function (key) {
+        delete json[key];
+      });
+      return json;
+    },
+
+    _toFullJSON: function _toFullJSON(seenObjects) {
+      var _this = this;
+
+      var json = _.clone(this.attributes);
+      AV._objectEach(json, function (val, key) {
+        json[key] = AV._encode(val, seenObjects);
+      });
+      AV._objectEach(this._operations, function (val, key) {
+        json[key] = val;
+      });
+
+      if (_.has(this, "id")) {
+        json.objectId = this.id;
+      }
+      _(['createdAt', 'updatedAt']).each(function (key) {
+        if (_.has(_this, key)) {
+          var val = _this[key];
+          json[key] = _.isDate(val) ? val.toJSON() : val;
+        }
+      });
+      json.__type = "Object";
+      json.className = this.className;
+      return json;
+    },
+
+    /**
+     * Updates _hashedJSON to reflect the current state of this object.
+     * Adds any changed hash values to the set of pending changes.
+     * @private
+     */
+    _refreshCache: function _refreshCache() {
+      var self = this;
+      if (self._refreshingCache) {
+        return;
+      }
+      self._refreshingCache = true;
+      AV._objectEach(this.attributes, function (value, key) {
+        if (value instanceof AV.Object) {
+          value._refreshCache();
+        } else if (_.isObject(value)) {
+          if (self._resetCacheForKey(key)) {
+            self.set(key, new AV.Op.Set(value), { silent: true });
+          }
+        }
+      });
+      delete self._refreshingCache;
+    },
+
+    /**
+     * Returns true if this object has been modified since its last
+     * save/refresh.  If an attribute is specified, it returns true only if that
+     * particular attribute has been modified since the last save/refresh.
+     * @param {String} attr An attribute name (optional).
+     * @return {Boolean}
+     */
+    dirty: function dirty(attr) {
+      this._refreshCache();
+
+      var currentChanges = _.last(this._opSetQueue);
+
+      if (attr) {
+        return currentChanges[attr] ? true : false;
+      }
+      if (!this.id) {
+        return true;
+      }
+      if (_.keys(currentChanges).length > 0) {
+        return true;
+      }
+      return false;
+    },
+
+    /**
+     * Gets a Pointer referencing this Object.
+     * @private
+     */
+    _toPointer: function _toPointer() {
+      // if (!this.id) {
+      //   throw new Error("Can't serialize an unsaved AV.Object");
+      // }
+      return { __type: "Pointer",
+        className: this.className,
+        objectId: this.id };
+    },
+
+    /**
+     * Gets the value of an attribute.
+     * @param {String} attr The string name of an attribute.
+     */
+    get: function get(attr) {
+      switch (attr) {
+        case 'objectId':
+          return this.id;
+        case 'createdAt':
+        case 'updatedAt':
+          return this[attr];
+        default:
+          return this.attributes[attr];
+      }
+    },
+
+    /**
+     * Gets a relation on the given class for the attribute.
+     * @param {String} attr The attribute to get the relation for.
+     * @return {AV.Relation}
+     */
+    relation: function relation(attr) {
+      var value = this.get(attr);
+      if (value) {
+        if (!(value instanceof AV.Relation)) {
+          throw new Error("Called relation() on non-relation field " + attr);
+        }
+        value._ensureParentAndKey(this, attr);
+        return value;
+      } else {
+        return new AV.Relation(this, attr);
+      }
+    },
+
+    /**
+     * Gets the HTML-escaped value of an attribute.
+     */
+    escape: function escape(attr) {
+      var html = this._escapedAttributes[attr];
+      if (html) {
+        return html;
+      }
+      var val = this.attributes[attr];
+      var escaped;
+      if (utils.isNullOrUndefined(val)) {
+        escaped = '';
+      } else {
+        escaped = _.escape(val.toString());
+      }
+      this._escapedAttributes[attr] = escaped;
+      return escaped;
+    },
+
+    /**
+     * Returns true if the attribute contains a value that is not
+     * null or undefined.
+     * @param {String} attr The string name of the attribute.
+     * @return {Boolean}
+     */
+    has: function has(attr) {
+      return !utils.isNullOrUndefined(this.attributes[attr]);
+    },
+
+    /**
+     * Pulls "special" fields like objectId, createdAt, etc. out of attrs
+     * and puts them on "this" directly.  Removes them from attrs.
+     * @param attrs - A dictionary with the data for this AV.Object.
+     * @private
+     */
+    _mergeMagicFields: function _mergeMagicFields(attrs) {
+      // Check for changes of magic fields.
+      var model = this;
+      var specialFields = ["objectId", "createdAt", "updatedAt"];
+      AV._arrayEach(specialFields, function (attr) {
+        if (attrs[attr]) {
+          if (attr === "objectId") {
+            model.id = attrs[attr];
+          } else if ((attr === "createdAt" || attr === "updatedAt") && !_.isDate(attrs[attr])) {
+            model[attr] = AV._parseDate(attrs[attr]);
+          } else {
+            model[attr] = attrs[attr];
+          }
+          delete attrs[attr];
+        }
+      });
+      return attrs;
+    },
+
+    /**
+     * Returns the json to be sent to the server.
+     * @private
+     */
+    _startSave: function _startSave() {
+      this._opSetQueue.push({});
+    },
+
+    /**
+     * Called when a save fails because of an error. Any changes that were part
+     * of the save need to be merged with changes made after the save. This
+     * might throw an exception is you do conflicting operations. For example,
+     * if you do:
+     *   object.set("foo", "bar");
+     *   object.set("invalid field name", "baz");
+     *   object.save();
+     *   object.increment("foo");
+     * then this will throw when the save fails and the client tries to merge
+     * "bar" with the +1.
+     * @private
+     */
+    _cancelSave: function _cancelSave() {
+      var self = this;
+      var failedChanges = _.first(this._opSetQueue);
+      this._opSetQueue = _.rest(this._opSetQueue);
+      var nextChanges = _.first(this._opSetQueue);
+      AV._objectEach(failedChanges, function (op, key) {
+        var op1 = failedChanges[key];
+        var op2 = nextChanges[key];
+        if (op1 && op2) {
+          nextChanges[key] = op2._mergeWithPrevious(op1);
+        } else if (op1) {
+          nextChanges[key] = op1;
+        }
+      });
+      this._saving = this._saving - 1;
+    },
+
+    /**
+     * Called when a save completes successfully. This merges the changes that
+     * were saved into the known server data, and overrides it with any data
+     * sent directly from the server.
+     * @private
+     */
+    _finishSave: function _finishSave(serverData) {
+      // Grab a copy of any object referenced by this object. These instances
+      // may have already been fetched, and we don't want to lose their data.
+      // Note that doing it like this means we will unify separate copies of the
+      // same object, but that's a risk we have to take.
+      var fetchedObjects = {};
+      AV._traverse(this.attributes, function (object) {
+        if (object instanceof AV.Object && object.id && object._hasData) {
+          fetchedObjects[object.id] = object;
+        }
+      });
+
+      var savedChanges = _.first(this._opSetQueue);
+      this._opSetQueue = _.rest(this._opSetQueue);
+      this._applyOpSet(savedChanges, this._serverData);
+      this._mergeMagicFields(serverData);
+      var self = this;
+      AV._objectEach(serverData, function (value, key) {
+        self._serverData[key] = AV._decode(value, key);
+
+        // Look for any objects that might have become unfetched and fix them
+        // by replacing their values with the previously observed values.
+        var fetched = AV._traverse(self._serverData[key], function (object) {
+          if (object instanceof AV.Object && fetchedObjects[object.id]) {
+            return fetchedObjects[object.id];
+          }
+        });
+        if (fetched) {
+          self._serverData[key] = fetched;
+        }
+      });
+      this._rebuildAllEstimatedData();
+      this._saving = this._saving - 1;
+    },
+
+    /**
+     * Called when a fetch or login is complete to set the known server data to
+     * the given object.
+     * @private
+     */
+    _finishFetch: function _finishFetch(serverData, hasData) {
+      // Clear out any changes the user might have made previously.
+      this._opSetQueue = [{}];
+
+      // Bring in all the new server data.
+      this._mergeMagicFields(serverData);
+      var self = this;
+      AV._objectEach(serverData, function (value, key) {
+        self._serverData[key] = AV._decode(value, key);
+      });
+
+      // Refresh the attributes.
+      this._rebuildAllEstimatedData();
+
+      // Clear out the cache of mutable containers.
+      this._refreshCache();
+      this._opSetQueue = [{}];
+
+      this._hasData = hasData;
+    },
+
+    /**
+     * Applies the set of AV.Op in opSet to the object target.
+     * @private
+     */
+    _applyOpSet: function _applyOpSet(opSet, target) {
+      var self = this;
+      AV._objectEach(opSet, function (change, key) {
+        target[key] = change._estimate(target[key], self, key);
+        if (target[key] === AV.Op._UNSET) {
+          delete target[key];
+        }
+      });
+    },
+
+    /**
+     * Replaces the cached value for key with the current value.
+     * Returns true if the new value is different than the old value.
+     * @private
+     */
+    _resetCacheForKey: function _resetCacheForKey(key) {
+      var value = this.attributes[key];
+      if (_.isObject(value) && !(value instanceof AV.Object) && !(value instanceof AV.File)) {
+
+        value = value.toJSON ? value.toJSON() : value;
+        var json = JSON.stringify(value);
+        if (this._hashedJSON[key] !== json) {
+          var wasSet = !!this._hashedJSON[key];
+          this._hashedJSON[key] = json;
+          return wasSet;
+        }
+      }
+      return false;
+    },
+
+    /**
+     * Populates attributes[key] by starting with the last known data from the
+     * server, and applying all of the local changes that have been made to that
+     * key since then.
+     * @private
+     */
+    _rebuildEstimatedDataForKey: function _rebuildEstimatedDataForKey(key) {
+      var self = this;
+      delete this.attributes[key];
+      if (this._serverData[key]) {
+        this.attributes[key] = this._serverData[key];
+      }
+      AV._arrayEach(this._opSetQueue, function (opSet) {
+        var op = opSet[key];
+        if (op) {
+          self.attributes[key] = op._estimate(self.attributes[key], self, key);
+          if (self.attributes[key] === AV.Op._UNSET) {
+            delete self.attributes[key];
+          } else {
+            self._resetCacheForKey(key);
+          }
+        }
+      });
+    },
+
+    /**
+     * Populates attributes by starting with the last known data from the
+     * server, and applying all of the local changes that have been made since
+     * then.
+     * @private
+     */
+    _rebuildAllEstimatedData: function _rebuildAllEstimatedData() {
+      var self = this;
+
+      var previousAttributes = _.clone(this.attributes);
+
+      this.attributes = _.clone(this._serverData);
+      AV._arrayEach(this._opSetQueue, function (opSet) {
+        self._applyOpSet(opSet, self.attributes);
+        AV._objectEach(opSet, function (op, key) {
+          self._resetCacheForKey(key);
+        });
+      });
+
+      // Trigger change events for anything that changed because of the fetch.
+      AV._objectEach(previousAttributes, function (oldValue, key) {
+        if (self.attributes[key] !== oldValue) {
+          self.trigger('change:' + key, self, self.attributes[key], {});
+        }
+      });
+      AV._objectEach(this.attributes, function (newValue, key) {
+        if (!_.has(previousAttributes, key)) {
+          self.trigger('change:' + key, self, newValue, {});
+        }
+      });
+    },
+
+    /**
+     * Sets a hash of model attributes on the object, firing
+     * "change" unless you choose to silence it.
+     *
+     * 

You can call it with an object containing keys and values, or with one + * key and value. For example:

+     *   gameTurn.set({
+     *     player: player1,
+     *     diceRoll: 2
+     *   }, {
+     *     error: function(gameTurnAgain, error) {
+     *       // The set failed validation.
+     *     }
+     *   });
+     *
+     *   game.set("currentPlayer", player2, {
+     *     error: function(gameTurnAgain, error) {
+     *       // The set failed validation.
+     *     }
+     *   });
+     *
+     *   game.set("finished", true);

+ * + * @param {String} key The key to set. + * @param {Any} value The value to give it. + * @param {Object} [options] + * @param {Boolean} [options.silent] + * @return {AV.Object} self if succeeded, throws if the value is not valid. + * @see AV.Object#validate + */ + set: function set(key, value, options) { + var attrs; + if (_.isObject(key) || utils.isNullOrUndefined(key)) { + attrs = _.mapObject(key, function (v, k) { + checkReservedKey(k); + return AV._decode(v, k); + }); + options = value; + } else { + attrs = {}; + checkReservedKey(key); + attrs[key] = AV._decode(value, key); + } + + // Extract attributes and options. + options = options || {}; + if (!attrs) { + return this; + } + if (attrs instanceof AV.Object) { + attrs = attrs.attributes; + } + + // If the unset option is used, every attribute should be a Unset. + if (options.unset) { + AV._objectEach(attrs, function (unused_value, key) { + attrs[key] = new AV.Op.Unset(); + }); + } + + // Apply all the attributes to get the estimated values. + var dataToValidate = _.clone(attrs); + var self = this; + AV._objectEach(dataToValidate, function (value, key) { + if (value instanceof AV.Op) { + dataToValidate[key] = value._estimate(self.attributes[key], self, key); + if (dataToValidate[key] === AV.Op._UNSET) { + delete dataToValidate[key]; + } + } + }); + + // Run validation. + this._validate(attrs, options); + + options.changes = {}; + var escaped = this._escapedAttributes; + var prev = this._previousAttributes || {}; + + // Update attributes. + AV._arrayEach(_.keys(attrs), function (attr) { + var val = attrs[attr]; + + // If this is a relation object we need to set the parent correctly, + // since the location where it was parsed does not have access to + // this object. + if (val instanceof AV.Relation) { + val.parent = self; + } + + if (!(val instanceof AV.Op)) { + val = new AV.Op.Set(val); + } + + // See if this change will actually have any effect. + var isRealChange = true; + if (val instanceof AV.Op.Set && _.isEqual(self.attributes[attr], val.value)) { + isRealChange = false; + } + + if (isRealChange) { + delete escaped[attr]; + if (options.silent) { + self._silent[attr] = true; + } else { + options.changes[attr] = true; + } + } + + var currentChanges = _.last(self._opSetQueue); + currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]); + self._rebuildEstimatedDataForKey(attr); + + if (isRealChange) { + self.changed[attr] = self.attributes[attr]; + if (!options.silent) { + self._pending[attr] = true; + } + } else { + delete self.changed[attr]; + delete self._pending[attr]; + } + }); + + if (!options.silent) { + this.change(options); + } + return this; + }, + + /** + * Remove an attribute from the model, firing "change" unless + * you choose to silence it. This is a noop if the attribute doesn't + * exist. + */ + unset: function unset(attr, options) { + options = options || {}; + options.unset = true; + return this.set(attr, null, options); + }, + + /** + * Atomically increments the value of the given attribute the next time the + * object is saved. If no amount is specified, 1 is used by default. + * + * @param attr {String} The key. + * @param amount {Number} The amount to increment by. + */ + increment: function increment(attr, amount) { + if (_.isUndefined(amount) || _.isNull(amount)) { + amount = 1; + } + return this.set(attr, new AV.Op.Increment(amount)); + }, + + /** + * Atomically add an object to the end of the array associated with a given + * key. + * @param attr {String} The key. + * @param item {} The item to add. + */ + add: function add(attr, item) { + return this.set(attr, new AV.Op.Add(utils.ensureArray(item))); + }, + + /** + * Atomically add an object to the array associated with a given key, only + * if it is not already present in the array. The position of the insert is + * not guaranteed. + * + * @param attr {String} The key. + * @param item {} The object to add. + */ + addUnique: function addUnique(attr, item) { + return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item))); + }, + + /** + * Atomically remove all instances of an object from the array associated + * with a given key. + * + * @param attr {String} The key. + * @param item {} The object to remove. + */ + remove: function remove(attr, item) { + return this.set(attr, new AV.Op.Remove(utils.ensureArray(item))); + }, + + /** + * Returns an instance of a subclass of AV.Op describing what kind of + * modification has been performed on this field since the last time it was + * saved. For example, after calling object.increment("x"), calling + * object.op("x") would return an instance of AV.Op.Increment. + * + * @param attr {String} The key. + * @returns {AV.Op} The operation, or undefined if none. + */ + op: function op(attr) { + return _.last(this._opSetQueue)[attr]; + }, + + /** + * Clear all attributes on the model, firing "change" unless + * you choose to silence it. + */ + clear: function clear(options) { + options = options || {}; + options.unset = true; + var keysToClear = _.extend(this.attributes, this._operations); + return this.set(keysToClear, options); + }, + + /** + * Returns a JSON-encoded set of operations to be sent with the next save + * request. + * @private + */ + _getSaveJSON: function _getSaveJSON() { + var json = _.clone(_.first(this._opSetQueue)); + AV._objectEach(json, function (op, key) { + json[key] = op.toJSON(); + }); + return json; + }, + + /** + * Returns true if this object can be serialized for saving. + * @private + */ + _canBeSerialized: function _canBeSerialized() { + return AV.Object._canBeSerializedAsValue(this.attributes); + }, + + /** + * Fetch the model from the server. If the server's representation of the + * model differs from its current attributes, they will be overriden, + * triggering a "change" event. + * @param {Object} fetchOptions Optional options to set 'keys' and + * 'include' option. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch: function fetch() { + var fetchOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var options = arguments[1]; + + if (_.isArray(fetchOptions.keys)) { + fetchOptions.keys = fetchOptions.keys.join(','); + } + if (_.isArray(fetchOptions.include)) { + fetchOptions.include = fetchOptions.include.join(','); + } + + var self = this; + var request = AVRequest('classes', this.className, this.id, 'GET', fetchOptions, options); + return request.then(function (response) { + self._finishFetch(self.parse(response), true); + return self; + }); + }, + + /** + * Set a hash of model attributes, and save the model to the server. + * updatedAt will be updated when the request returns. + * You can either call it as:
+     *   object.save();
+ * or
+     *   object.save(null, options);
+ * or
+     *   object.save(attrs, options);
+ * or
+     *   object.save(key, value, options);
+ * + * For example,
+     *   gameTurn.save({
+     *     player: "Jake Cutter",
+     *     diceRoll: 2
+     *   }).then(function(gameTurnAgain) {
+     *     // The save was successful.
+     *   }, function(error) {
+     *     // The save failed.  Error is an instance of AVError.
+     *   });
+ * @param {AuthOptions} options AuthOptions plus: + * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded + * @param {AV.Query} options.query Save object only when it matches the query + * @return {AV.Promise} A promise that is fulfilled when the save + * completes. + * @see AVError + */ + save: function save(arg1, arg2, arg3) { + var i, attrs, current, options, saved; + if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) { + attrs = arg1; + options = arg2; + } else { + attrs = {}; + attrs[arg1] = arg2; + options = arg3; + } + + options = _.clone(options) || {}; + if (options.wait) { + current = _.clone(this.attributes); + } + + var setOptions = _.clone(options) || {}; + if (setOptions.wait) { + setOptions.silent = true; + } + if (attrs) { + this.set(attrs, setOptions); + } + + var model = this; + + // If there is any unsaved child, save it first. + model._refreshCache(); + + var unsavedChildren = []; + var unsavedFiles = []; + AV.Object._findUnsavedChildren(model.attributes, unsavedChildren, unsavedFiles); + if (unsavedChildren.length + unsavedFiles.length > 0) { + return AV.Object._deepSaveAsync(this.attributes, model, options).then(function () { + return model.save(null, options); + }); + } + + this._startSave(); + this._saving = (this._saving || 0) + 1; + + this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve(); + this._allPreviousSaves = this._allPreviousSaves.catch(function (e) {}).then(function () { + var method = model.id ? 'PUT' : 'POST'; + + var json = model._getSaveJSON(); + + if (model._fetchWhenSave) { + //Sepcial-case fetchWhenSave when updating object. + json._fetchWhenSave = true; + } + + if (options.fetchWhenSave) { + json._fetchWhenSave = true; + } + if (options.query) { + var queryJSON; + if (typeof options.query.toJSON === 'function') { + queryJSON = options.query.toJSON(); + if (queryJSON) { + json._where = queryJSON.where; + } + } + if (!json._where) { + var error = new Error('options.query is not an AV.Query'); + throw error; + } + } + + _.extend(json, model._flags); + + var route = "classes"; + var className = model.className; + if (model.className === "_User" && !model.id) { + // Special-case user sign-up. + route = "users"; + className = null; + } + //hook makeRequest in options. + var makeRequest = options._makeRequest || AVRequest; + var request = makeRequest(route, className, model.id, method, json, options); + + request = request.then(function (resp) { + var serverAttrs = model.parse(resp); + if (options.wait) { + serverAttrs = _.extend(attrs || {}, serverAttrs); + } + model._finishSave(serverAttrs); + if (options.wait) { + model.set(current, setOptions); + } + return model; + }, function (error) { + model._cancelSave(); + throw error; + }); + + return request; + }); + return this._allPreviousSaves; + }, + + /** + * Destroy this model on the server if it was already persisted. + * Optimistically removes the model from its collection, if it has one. + * @param {AuthOptions} options AuthOptions plus: + * @param {Boolean} [options.wait] wait for the server to respond + * before removal. + * + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + options = options || {}; + var model = this; + + var triggerDestroy = function triggerDestroy() { + model.trigger('destroy', model, model.collection, options); + }; + + if (!this.id) { + return triggerDestroy(); + } + + if (!options.wait) { + triggerDestroy(); + } + + var request = AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options); + return request.then(function () { + if (options.wait) { + triggerDestroy(); + } + return model; + }); + }, + + /** + * Converts a response into the hash of attributes to be set on the model. + * @ignore + */ + parse: function parse(resp) { + var output = _.clone(resp); + _(["createdAt", "updatedAt"]).each(function (key) { + if (output[key]) { + output[key] = AV._parseDate(output[key]); + } + }); + if (!output.updatedAt) { + output.updatedAt = output.createdAt; + } + return output; + }, + + /** + * Creates a new model with identical attributes to this one. + * @return {AV.Object} + */ + clone: function clone() { + return new this.constructor(this.attributes); + }, + + /** + * Returns true if this object has never been saved to AV. + * @return {Boolean} + */ + isNew: function isNew() { + return !this.id; + }, + + /** + * Call this method to manually fire a `"change"` event for this model and + * a `"change:attribute"` event for each changed attribute. + * Calling this will cause all objects observing the model to update. + */ + change: function change(options) { + options = options || {}; + var changing = this._changing; + this._changing = true; + + // Silent changes become pending changes. + var self = this; + AV._objectEach(this._silent, function (attr) { + self._pending[attr] = true; + }); + + // Silent changes are triggered. + var changes = _.extend({}, options.changes, this._silent); + this._silent = {}; + AV._objectEach(changes, function (unused_value, attr) { + self.trigger('change:' + attr, self, self.get(attr), options); + }); + if (changing) { + return this; + } + + // This is to get around lint not letting us make a function in a loop. + var deleteChanged = function deleteChanged(value, attr) { + if (!self._pending[attr] && !self._silent[attr]) { + delete self.changed[attr]; + } + }; + + // Continue firing `"change"` events while there are pending changes. + while (!_.isEmpty(this._pending)) { + this._pending = {}; + this.trigger('change', this, options); + // Pending and silent changes still remain. + AV._objectEach(this.changed, deleteChanged); + self._previousAttributes = _.clone(this.attributes); + } + + this._changing = false; + return this; + }, + + /** + * Determine if the model has changed since the last "change" + * event. If you specify an attribute name, determine if that attribute + * has changed. + * @param {String} attr Optional attribute name + * @return {Boolean} + */ + hasChanged: function hasChanged(attr) { + if (!arguments.length) { + return !_.isEmpty(this.changed); + } + return this.changed && _.has(this.changed, attr); + }, + + /** + * Returns an object containing all the attributes that have changed, or + * false if there are no changed attributes. Useful for determining what + * parts of a view need to be updated and/or what attributes need to be + * persisted to the server. Unset attributes will be set to undefined. + * You can also pass an attributes object to diff against the model, + * determining if there *would be* a change. + */ + changedAttributes: function changedAttributes(diff) { + if (!diff) { + return this.hasChanged() ? _.clone(this.changed) : false; + } + var changed = {}; + var old = this._previousAttributes; + AV._objectEach(diff, function (diffVal, attr) { + if (!_.isEqual(old[attr], diffVal)) { + changed[attr] = diffVal; + } + }); + return changed; + }, + + /** + * Gets the previous value of an attribute, recorded at the time the last + * "change" event was fired. + * @param {String} attr Name of the attribute to get. + */ + previous: function previous(attr) { + if (!arguments.length || !this._previousAttributes) { + return null; + } + return this._previousAttributes[attr]; + }, + + /** + * Gets all of the attributes of the model at the time of the previous + * "change" event. + * @return {Object} + */ + previousAttributes: function previousAttributes() { + return _.clone(this._previousAttributes); + }, + + /** + * Checks if the model is currently in a valid state. It's only possible to + * get into an *invalid* state if you're using silent changes. + * @return {Boolean} + */ + isValid: function isValid() { + try { + this.validate(this.attributes); + } catch (error) { + return false; + } + return true; + }, + + /** + * You should not call this function directly unless you subclass + * AV.Object, in which case you can override this method + * to provide additional validation on set and + * save. Your implementation should throw an Error if + * the attrs is invalid + * + * @param {Object} attrs The current data to validate. + * @see AV.Object#set + */ + validate: function validate(attrs) { + if (_.has(attrs, "ACL") && !(attrs.ACL instanceof AV.ACL)) { + throw new AVError(AVError.OTHER_CAUSE, "ACL must be a AV.ACL."); + } + }, + + /** + * Run validation against a set of incoming attributes, returning `true` + * if all is well. If a specific `error` callback has been passed, + * call that instead of firing the general `"error"` event. + * @private + */ + _validate: function _validate(attrs, options) { + if (options.silent || !this.validate) { + return; + } + attrs = _.extend({}, this.attributes, attrs); + this.validate(attrs); + }, + + /** + * Returns the ACL for this object. + * @returns {AV.ACL} An instance of AV.ACL. + * @see AV.Object#get + */ + getACL: function getACL() { + return this.get("ACL"); + }, + + /** + * Sets the ACL to be used for this object. + * @param {AV.ACL} acl An instance of AV.ACL. + * @param {Object} options Optional Backbone-like options object to be + * passed in to set. + * @return {Boolean} Whether the set passed validation. + * @see AV.Object#set + */ + setACL: function setACL(acl, options) { + return this.set("ACL", acl, options); + }, + + disableBeforeHook: function disableBeforeHook() { + this.ignoreHook('beforeSave'); + this.ignoreHook('beforeUpdate'); + this.ignoreHook('beforeDelete'); + }, + + disableAfterHook: function disableAfterHook() { + this.ignoreHook('afterSave'); + this.ignoreHook('afterUpdate'); + this.ignoreHook('afterDelete'); + }, + + ignoreHook: function ignoreHook(hookName) { + if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) { + console.trace('Unsupported hookName: ' + hookName); + } + + if (!AV.hookKey) { + console.trace('ignoreHook required hookKey'); + } + + if (!this._flags.__ignore_hooks) { + this._flags.__ignore_hooks = []; + } + + this._flags.__ignore_hooks.push(hookName); + } + }); + + /** + * Creates an instance of a subclass of AV.Object for the give classname + * and id. + * @param {String} className The name of the AV class backing this model. + * @param {String} id The object id of this model. + * @return {AV.Object} A new subclass instance of AV.Object. + */ + AV.Object.createWithoutData = function (className, id, hasData) { + var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + result.id = id; + result._hasData = hasData; + return result; + }; + /** + * Delete objects in batch. + * @param {AV.Object[]} objects The AV.Object array to be deleted. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the save + * completes. + */ + AV.Object.destroyAll = function (objects) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!objects || objects.length === 0) { + return AV.Promise.resolve(); + } + var objectsByClassNameAndFlags = _.groupBy(objects, function (object) { + return JSON.stringify({ + className: object.className, + flags: object._flags + }); + }); + var body = { + requests: _.map(objectsByClassNameAndFlags, function (objects) { + var ids = _.map(objects, 'id').join(','); + return { + method: 'DELETE', + path: '/1.1/classes/' + objects[0].className + '/' + ids, + body: objects[0]._flags + }; + }) + }; + return AVRequest('batch', null, null, 'POST', body, options); + }; + + /** + * Returns the appropriate subclass for making new instances of the given + * className string. + * @private + */ + AV.Object._getSubclass = function (className) { + if (!_.isString(className)) { + throw new Error('AV.Object._getSubclass requires a string argument.'); + } + var ObjectClass = AV.Object._classMap[className]; + if (!ObjectClass) { + ObjectClass = AV.Object.extend(className); + AV.Object._classMap[className] = ObjectClass; + } + return ObjectClass; + }; + + /** + * Creates an instance of a subclass of AV.Object for the given classname. + * @private + */ + AV.Object._create = function (className, attributes, options, noDefaultACL) { + var ObjectClass = AV.Object._getSubclass(className); + return new ObjectClass(attributes, options, noDefaultACL); + }; + + // Set up a map of className to class so that we can create new instances of + // AV Objects from JSON automatically. + AV.Object._classMap = {}; + + AV.Object._extend = AV._extend; + + /** + * Creates a new model with defined attributes, + * It's the same with + *
+   *   new AV.Object(attributes, options);
+   *  
+ * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @return {AV.Object} + * @since v0.4.4 + * @see AV.Object + * @see AV.Object.extend + */ + AV.Object['new'] = function (attributes, options) { + return new AV.Object(attributes, options); + }; + + /** + * Creates a new subclass of AV.Object for the given AV class name. + * + *

Every extension of a AV class will inherit from the most recent + * previous extension of that class. When a AV.Object is automatically + * created by parsing JSON, it will use the most recent extension of that + * class.

+ * + *

You should call either:

+   *     var MyClass = AV.Object.extend("MyClass", {
+   *         Instance properties
+   *     }, {
+   *         Class properties
+   *     });
+ * or, for Backbone compatibility:
+   *     var MyClass = AV.Object.extend({
+   *         className: "MyClass",
+   *         Other instance properties
+   *     }, {
+   *         Class properties
+   *     });

+ * + * @param {String} className The name of the AV class backing this model. + * @param {Object} protoProps Instance properties to add to instances of the + * class returned from this method. + * @param {Object} classProps Class properties to add the class returned from + * this method. + * @return {Class} A new subclass of AV.Object. + */ + AV.Object.extend = function (className, protoProps, classProps) { + // Handle the case with only two args. + if (!_.isString(className)) { + if (className && _.has(className, "className")) { + return AV.Object.extend(className.className, className, protoProps); + } else { + throw new Error("AV.Object.extend's first argument should be the className."); + } + } + + // If someone tries to subclass "User", coerce it to the right type. + if (className === "User") { + className = "_User"; + } + + var NewClassObject = null; + if (_.has(AV.Object._classMap, className)) { + var OldClassObject = AV.Object._classMap[className]; + // This new subclass has been told to extend both from "this" and from + // OldClassObject. This is multiple inheritance, which isn't supported. + // For now, let's just pick one. + if (protoProps || classProps) { + NewClassObject = OldClassObject._extend(protoProps, classProps); + } else { + return OldClassObject; + } + } else { + protoProps = protoProps || {}; + protoProps._className = className; + NewClassObject = this._extend(protoProps, classProps); + } + // Extending a subclass should reuse the classname automatically. + NewClassObject.extend = function (arg0) { + if (_.isString(arg0) || arg0 && _.has(arg0, "className")) { + return AV.Object.extend.apply(NewClassObject, arguments); + } + var newArguments = [className].concat(_.toArray(arguments)); + return AV.Object.extend.apply(NewClassObject, newArguments); + }; + NewClassObject['new'] = function (attributes, options) { + return new NewClassObject(attributes, options); + }; + AV.Object._classMap[className] = NewClassObject; + return NewClassObject; + }; + + // ES6 class syntax support + Object.defineProperty(AV.Object.prototype, 'className', { + get: function get() { + var className = this._className || this.constructor._LCClassName || this.constructor.name; + // If someone tries to subclass "User", coerce it to the right type. + if (className === "User") { + return "_User"; + } + return className; + } + }); + + /** + * Register a class. + * If a subclass of AV.Object is defined with your own implement + * rather then AV.Object.extend, the subclass must be registered. + * @param {Function} klass A subclass of AV.Object + * @param {String} [name] Specify the name of the class. Useful when the class might be uglified. + * @example + * class Person extend AV.Object {} + * AV.Object.register(Person); + */ + AV.Object.register = function (klass, name) { + if (!(klass.prototype instanceof AV.Object)) { + throw new Error('registered class is not a subclass of AV.Object'); + } + var className = name || klass.name; + if (!className.length) { + throw new Error('registered class must be named'); + } + if (name) { + klass._LCClassName = name; + } + AV.Object._classMap[className] = klass; + }; + + AV.Object._findUnsavedChildren = function (object, children, files) { + AV._traverse(object, function (object) { + if (object instanceof AV.Object) { + object._refreshCache(); + if (object.dirty()) { + children.push(object); + } + return; + } + + if (object instanceof AV.File) { + if (!object.url() && !object.id) { + files.push(object); + } + return; + } + }); + }; + + AV.Object._canBeSerializedAsValue = function (object) { + var canBeSerializedAsValue = true; + + if (object instanceof AV.Object || object instanceof AV.File) { + canBeSerializedAsValue = !!object.id; + } else if (_.isArray(object)) { + AV._arrayEach(object, function (child) { + if (!AV.Object._canBeSerializedAsValue(child)) { + canBeSerializedAsValue = false; + } + }); + } else if (_.isObject(object)) { + AV._objectEach(object, function (child) { + if (!AV.Object._canBeSerializedAsValue(child)) { + canBeSerializedAsValue = false; + } + }); + } + + return canBeSerializedAsValue; + }; + + AV.Object._deepSaveAsync = function (object, model, options) { + var unsavedChildren = []; + var unsavedFiles = []; + AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles); + if (model) { + unsavedChildren = _.filter(unsavedChildren, function (object) { + return object != model; + }); + } + + var promise = AV.Promise.resolve(); + _.each(unsavedFiles, function (file) { + promise = promise.then(function () { + return file.save(); + }); + }); + + var objects = _.uniq(unsavedChildren); + var remaining = _.uniq(objects); + + return promise.then(function () { + return AV.Promise._continueWhile(function () { + return remaining.length > 0; + }, function () { + + // Gather up all the objects that can be saved in this batch. + var batch = []; + var newRemaining = []; + AV._arrayEach(remaining, function (object) { + // Limit batches to 20 objects. + if (batch.length > 20) { + newRemaining.push(object); + return; + } + + if (object._canBeSerialized()) { + batch.push(object); + } else { + newRemaining.push(object); + } + }); + remaining = newRemaining; + + // If we can't save any objects, there must be a circular reference. + if (batch.length === 0) { + return AV.Promise.reject(new AVError(AVError.OTHER_CAUSE, "Tried to save a batch with a cycle.")); + } + + // Reserve a spot in every object's save queue. + var readyToStart = AV.Promise.resolve(_.map(batch, function (object) { + return object._allPreviousSaves || AV.Promise.resolve(); + })); + + // Save a single batch, whether previous saves succeeded or failed. + var bathSavePromise = readyToStart.then(function () { + return AVRequest("batch", null, null, "POST", { + requests: _.map(batch, function (object) { + var json = object._getSaveJSON(); + _.extend(json, object._flags); + var method = "POST"; + + var path = "/1.1/classes/" + object.className; + if (object.id) { + path = path + "/" + object.id; + method = "PUT"; + } + + object._startSave(); + + return { + method: method, + path: path, + body: json + }; + }) + + }, options).then(function (response) { + var error; + AV._arrayEach(batch, function (object, i) { + if (response[i].success) { + object._finishSave(object.parse(response[i].success)); + } else { + error = error || response[i].error; + object._cancelSave(); + } + }); + if (error) { + return AV.Promise.reject(new AVError(error.code, error.error)); + } + }); + }); + AV._arrayEach(batch, function (object) { + object._allPreviousSaves = bathSavePromise; + }); + return bathSavePromise; + }); + }).then(function () { + return object; + }); + }; +}; + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + + /** + * @private + * @class + * A AV.Op is an atomic operation that can be applied to a field in a + * AV.Object. For example, calling object.set("foo", "bar") + * is an example of a AV.Op.Set. Calling object.unset("foo") + * is a AV.Op.Unset. These operations are stored in a AV.Object and + * sent to the server as part of object.save() operations. + * Instances of AV.Op should be immutable. + * + * You should not create subclasses of AV.Op or instantiate AV.Op + * directly. + */ + AV.Op = function () { + this._initialize.apply(this, arguments); + }; + + AV.Op.prototype = { + _initialize: function _initialize() {} + }; + + _.extend(AV.Op, { + /** + * To create a new Op, call AV.Op._extend(); + * @private + */ + _extend: AV._extend, + + // A map of __op string to decoder function. + _opDecoderMap: {}, + + /** + * Registers a function to convert a json object with an __op field into an + * instance of a subclass of AV.Op. + * @private + */ + _registerDecoder: function _registerDecoder(opName, decoder) { + AV.Op._opDecoderMap[opName] = decoder; + }, + + /** + * Converts a json object into an instance of a subclass of AV.Op. + * @private + */ + _decode: function _decode(json) { + var decoder = AV.Op._opDecoderMap[json.__op]; + if (decoder) { + return decoder(json); + } else { + return undefined; + } + } + }); + + /* + * Add a handler for Batch ops. + */ + AV.Op._registerDecoder("Batch", function (json) { + var op = null; + AV._arrayEach(json.ops, function (nextOp) { + nextOp = AV.Op._decode(nextOp); + op = nextOp._mergeWithPrevious(op); + }); + return op; + }); + + /** + * @private + * @class + * A Set operation indicates that either the field was changed using + * AV.Object.set, or it is a mutable container that was detected as being + * changed. + */ + AV.Op.Set = AV.Op._extend( /** @lends AV.Op.Set.prototype */{ + _initialize: function _initialize(value) { + this._value = value; + }, + + /** + * Returns the new value of this field after the set. + */ + value: function value() { + return this._value; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return AV._encode(this.value()); + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + return this; + }, + + _estimate: function _estimate(oldValue) { + return this.value(); + } + }); + + /** + * A sentinel value that is returned by AV.Op.Unset._estimate to + * indicate the field should be deleted. Basically, if you find _UNSET as a + * value in your object, you should remove that key. + */ + AV.Op._UNSET = {}; + + /** + * @private + * @class + * An Unset operation indicates that this field has been deleted from the + * object. + */ + AV.Op.Unset = AV.Op._extend( /** @lends AV.Op.Unset.prototype */{ + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Delete" }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + return this; + }, + + _estimate: function _estimate(oldValue) { + return AV.Op._UNSET; + } + }); + + AV.Op._registerDecoder("Delete", function (json) { + return new AV.Op.Unset(); + }); + + /** + * @private + * @class + * An Increment is an atomic operation where the numeric value for the field + * will be increased by a given amount. + */ + AV.Op.Increment = AV.Op._extend( + /** @lends AV.Op.Increment.prototype */{ + + _initialize: function _initialize(amount) { + this._amount = amount; + }, + + /** + * Returns the amount to increment by. + * @return {Number} the amount to increment by. + */ + amount: function amount() { + return this._amount; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Increment", amount: this._amount }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.amount()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(previous.value() + this.amount()); + } else if (previous instanceof AV.Op.Increment) { + return new AV.Op.Increment(this.amount() + previous.amount()); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return this.amount(); + } + return oldValue + this.amount(); + } + }); + + AV.Op._registerDecoder("Increment", function (json) { + return new AV.Op.Increment(json.amount); + }); + + /** + * @private + * @class + * Add is an atomic operation where the given objects will be appended to the + * array that is stored in this field. + */ + AV.Op.Add = AV.Op._extend( /** @lends AV.Op.Add.prototype */{ + _initialize: function _initialize(objects) { + this._objects = objects; + }, + + /** + * Returns the objects to be added to the array. + * @return {Array} The objects to be added to the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Add", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.objects()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.Add) { + return new AV.Op.Add(previous.objects().concat(this.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return _.clone(this.objects()); + } else { + return oldValue.concat(this.objects()); + } + } + }); + + AV.Op._registerDecoder("Add", function (json) { + return new AV.Op.Add(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * AddUnique is an atomic operation where the given items will be appended to + * the array that is stored in this field only if they were not already + * present in the array. + */ + AV.Op.AddUnique = AV.Op._extend( + /** @lends AV.Op.AddUnique.prototype */{ + + _initialize: function _initialize(objects) { + this._objects = _.uniq(objects); + }, + + /** + * Returns the objects to be added to the array. + * @return {Array} The objects to be added to the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "AddUnique", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.objects()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.AddUnique) { + return new AV.Op.AddUnique(this._estimate(previous.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return _.clone(this.objects()); + } else { + // We can't just take the _.uniq(_.union(...)) of oldValue and + // this.objects, because the uniqueness may not apply to oldValue + // (especially if the oldValue was set via .set()) + var newValue = _.clone(oldValue); + AV._arrayEach(this.objects(), function (obj) { + if (obj instanceof AV.Object && obj.id) { + var matchingObj = _.find(newValue, function (anObj) { + return anObj instanceof AV.Object && anObj.id === obj.id; + }); + if (!matchingObj) { + newValue.push(obj); + } else { + var index = _.indexOf(newValue, matchingObj); + newValue[index] = obj; + } + } else if (!_.contains(newValue, obj)) { + newValue.push(obj); + } + }); + return newValue; + } + } + }); + + AV.Op._registerDecoder("AddUnique", function (json) { + return new AV.Op.AddUnique(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * Remove is an atomic operation where the given objects will be removed from + * the array that is stored in this field. + */ + AV.Op.Remove = AV.Op._extend( /** @lends AV.Op.Remove.prototype */{ + _initialize: function _initialize(objects) { + this._objects = _.uniq(objects); + }, + + /** + * Returns the objects to be removed from the array. + * @return {Array} The objects to be removed from the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Remove", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return previous; + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.Remove) { + return new AV.Op.Remove(_.union(previous.objects(), this.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return []; + } else { + var newValue = _.difference(oldValue, this.objects()); + // If there are saved AV Objects being removed, also remove them. + AV._arrayEach(this.objects(), function (obj) { + if (obj instanceof AV.Object && obj.id) { + newValue = _.reject(newValue, function (other) { + return other instanceof AV.Object && other.id === obj.id; + }); + } + }); + return newValue; + } + } + }); + + AV.Op._registerDecoder("Remove", function (json) { + return new AV.Op.Remove(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * A Relation operation indicates that the field is an instance of + * AV.Relation, and objects are being added to, or removed from, that + * relation. + */ + AV.Op.Relation = AV.Op._extend( + /** @lends AV.Op.Relation.prototype */{ + + _initialize: function _initialize(adds, removes) { + this._targetClassName = null; + + var self = this; + + var pointerToId = function pointerToId(object) { + if (object instanceof AV.Object) { + if (!object.id) { + throw new Error('You can\'t add an unsaved AV.Object to a relation.'); + } + if (!self._targetClassName) { + self._targetClassName = object.className; + } + if (self._targetClassName !== object.className) { + throw new Error("Tried to create a AV.Relation with 2 different types: " + self._targetClassName + " and " + object.className + "."); + } + return object.id; + } + return object; + }; + + this.relationsToAdd = _.uniq(_.map(adds, pointerToId)); + this.relationsToRemove = _.uniq(_.map(removes, pointerToId)); + }, + + /** + * Returns an array of unfetched AV.Object that are being added to the + * relation. + * @return {Array} + */ + added: function added() { + var self = this; + return _.map(this.relationsToAdd, function (objectId) { + var object = AV.Object._create(self._targetClassName); + object.id = objectId; + return object; + }); + }, + + /** + * Returns an array of unfetched AV.Object that are being removed from + * the relation. + * @return {Array} + */ + removed: function removed() { + var self = this; + return _.map(this.relationsToRemove, function (objectId) { + var object = AV.Object._create(self._targetClassName); + object.id = objectId; + return object; + }); + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + var adds = null; + var removes = null; + var self = this; + var idToPointer = function idToPointer(id) { + return { __type: 'Pointer', + className: self._targetClassName, + objectId: id }; + }; + var pointers = null; + if (this.relationsToAdd.length > 0) { + pointers = _.map(this.relationsToAdd, idToPointer); + adds = { "__op": "AddRelation", "objects": pointers }; + } + + if (this.relationsToRemove.length > 0) { + pointers = _.map(this.relationsToRemove, idToPointer); + removes = { "__op": "RemoveRelation", "objects": pointers }; + } + + if (adds && removes) { + return { "__op": "Batch", "ops": [adds, removes] }; + } + + return adds || removes || {}; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + throw new Error('You can\'t modify a relation after deleting it.'); + } else if (previous instanceof AV.Op.Relation) { + if (previous._targetClassName && previous._targetClassName !== this._targetClassName) { + throw new Error("Related object must be of class " + previous._targetClassName + ", but " + this._targetClassName + " was passed in."); + } + var newAdd = _.union(_.difference(previous.relationsToAdd, this.relationsToRemove), this.relationsToAdd); + var newRemove = _.union(_.difference(previous.relationsToRemove, this.relationsToAdd), this.relationsToRemove); + + var newRelation = new AV.Op.Relation(newAdd, newRemove); + newRelation._targetClassName = this._targetClassName; + return newRelation; + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue, object, key) { + if (!oldValue) { + var relation = new AV.Relation(object, key); + relation.targetClassName = this._targetClassName; + } else if (oldValue instanceof AV.Relation) { + if (this._targetClassName) { + if (oldValue.targetClassName) { + if (oldValue.targetClassName !== this._targetClassName) { + throw new Error("Related object must be a " + oldValue.targetClassName + ", but a " + this._targetClassName + " was passed in."); + } + } else { + oldValue.targetClassName = this._targetClassName; + } + } + return oldValue; + } else { + throw new Error('Op is invalid after previous op.'); + } + } + }); + + AV.Op._registerDecoder("AddRelation", function (json) { + return new AV.Op.Relation(AV._decode(json.objects), []); + }); + AV.Op._registerDecoder("RemoveRelation", function (json) { + return new AV.Op.Relation([], AV._decode(json.objects)); + }); +}; + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + AV.Installation = AV.Object.extend("_Installation"); + + /** + * @namespace + */ + AV.Push = AV.Push || {}; + + /** + * Sends a push notification. + * @param {Object} data The data of the push notification. + * @param {String[]} [data.channels] An Array of channels to push to. + * @param {Date} [data.push_time] A Date object for when to send the push. + * @param {Date} [data.expiration_time] A Date object for when to expire + * the push. + * @param {Number} [data.expiration_interval] The seconds from now to expire the push. + * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match + * a set of installations to push to. + * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match + * a set of installations to push to. + * @param {Date} data.data The data to send as part of the push + * @param {AuthOptions} [options] + * @return {Promise} + */ + AV.Push.send = function (data, options) { + if (data.where) { + data.where = data.where.toJSON().where; + } + + if (data.where && data.cql) { + throw new Error("Both where and cql can't be set"); + } + + if (data.push_time) { + data.push_time = data.push_time.toJSON(); + } + + if (data.expiration_time) { + data.expiration_time = data.expiration_time.toJSON(); + } + + if (data.expiration_time && data.expiration_time_interval) { + throw new Error("Both expiration_time and expiration_time_interval can't be set"); + } + + var request = AVRequest('push', null, null, 'POST', data, options); + return request; + }; +}; + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var debug = __webpack_require__(5)('leancloud:query'); +var Promise = __webpack_require__(1); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; + +var _require = __webpack_require__(4), + ensureArray = _require.ensureArray; + +var requires = function requires(value, message) { + if (value === undefined) { + throw new Error(message); + } +}; + +// AV.Query is a way to create a list of AV.Objects. +module.exports = function (AV) { + /** + * Creates a new AV.Query for the given AV.Object subclass. + * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string. + * @class + * + *

AV.Query defines a query that is used to fetch AV.Objects. The + * most common use case is finding all objects that match a query through the + * find method. For example, this sample code fetches all objects + * of class MyClass. It calls a different function depending on + * whether the fetch succeeded or not. + * + *

+   * var query = new AV.Query(MyClass);
+   * query.find().then(function(results) {
+   *   // results is an array of AV.Object.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ * + *

An AV.Query can also be used to retrieve a single object whose id is + * known, through the get method. For example, this sample code fetches an + * object of class MyClass and id myId. It calls a + * different function depending on whether the fetch succeeded or not. + * + *

+   * var query = new AV.Query(MyClass);
+   * query.get(myId).then(function(object) {
+   *   // object is an instance of AV.Object.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ * + *

An AV.Query can also be used to count the number of objects that match + * the query without retrieving all of those objects. For example, this + * sample code counts the number of objects of the class MyClass + *

+   * var query = new AV.Query(MyClass);
+   * query.count().then(function(number) {
+   *   // There are number instances of MyClass.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ */ + AV.Query = function (objectClass) { + if (_.isString(objectClass)) { + objectClass = AV.Object._getSubclass(objectClass); + } + + this.objectClass = objectClass; + + this.className = objectClass.prototype.className; + + this._where = {}; + this._include = []; + this._select = []; + this._limit = -1; // negative limit means, do not send a limit + this._skip = 0; + this._extraOptions = {}; + }; + + /** + * Constructs a AV.Query that is the OR of the passed in queries. For + * example: + *
var compoundQuery = AV.Query.or(query1, query2, query3);
+ * + * will create a compoundQuery that is an or of the query1, query2, and + * query3. + * @param {...AV.Query} var_args The list of queries to OR. + * @return {AV.Query} The query that is the OR of the passed in queries. + */ + AV.Query.or = function () { + var queries = _.toArray(arguments); + var className = null; + AV._arrayEach(queries, function (q) { + if (_.isNull(className)) { + className = q.className; + } + + if (className !== q.className) { + throw new Error('All queries must be for the same class'); + } + }); + var query = new AV.Query(className); + query._orQuery(queries); + return query; + }; + + /** + * Constructs a AV.Query that is the AND of the passed in queries. For + * example: + *
var compoundQuery = AV.Query.and(query1, query2, query3);
+ * + * will create a compoundQuery that is an 'and' of the query1, query2, and + * query3. + * @param {...AV.Query} var_args The list of queries to AND. + * @return {AV.Query} The query that is the AND of the passed in queries. + */ + AV.Query.and = function () { + var queries = _.toArray(arguments); + var className = null; + AV._arrayEach(queries, function (q) { + if (_.isNull(className)) { + className = q.className; + } + + if (className !== q.className) { + throw new Error('All queries must be for the same class'); + } + }); + var query = new AV.Query(className); + query._andQuery(queries); + return query; + }; + + /** + * Retrieves a list of AVObjects that satisfy the CQL. + * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}. + * + * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}. + * @param {Array} pvalues An array contains placeholder values. + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the results when + * the query completes. + */ + AV.Query.doCloudQuery = function (cql, pvalues, options) { + var params = { cql: cql }; + if (_.isArray(pvalues)) { + params.pvalues = pvalues; + } else { + options = pvalues; + } + + var request = AVRequest('cloudQuery', null, null, 'GET', params, options); + return request.then(function (response) { + //query to process results. + var query = new AV.Query(response.className); + var results = _.map(response.results, function (json) { + var obj = query._newObject(response); + if (obj._finishFetch) { + obj._finishFetch(query._processResult(json), true); + } + return obj; + }); + return { + results: results, + count: response.count, + className: response.className + }; + }); + }; + + AV.Query._extend = AV._extend; + + AV.Query.prototype = { + //hook to iterate result. Added by dennis. + _processResult: function _processResult(obj) { + return obj; + }, + + /** + * Constructs an AV.Object whose id is already known by fetching data from + * the server. + * + * @param {String} objectId The id of the object to be fetched. + * @param {AuthOptions} options + * @return {Promise.} + */ + get: function get(objectId, options) { + if (!objectId) { + var errorObject = new AVError(AVError.OBJECT_NOT_FOUND, "Object not found."); + throw errorObject; + } + + var self = this; + + var obj = self._newObject(); + obj.id = objectId; + + var queryJSON = self.toJSON(); + var fetchOptions = {}; + + if (queryJSON.keys) fetchOptions.keys = queryJSON.keys; + if (queryJSON.include) fetchOptions.include = queryJSON.include; + + return obj.fetch(fetchOptions, options); + }, + + /** + * Returns a JSON representation of this query. + * @return {Object} + */ + toJSON: function toJSON() { + var params = { + where: this._where + }; + + if (this._include.length > 0) { + params.include = this._include.join(","); + } + if (this._select.length > 0) { + params.keys = this._select.join(","); + } + if (this._limit >= 0) { + params.limit = this._limit; + } + if (this._skip > 0) { + params.skip = this._skip; + } + if (this._order !== undefined) { + params.order = this._order; + } + + AV._objectEach(this._extraOptions, function (v, k) { + params[k] = v; + }); + + return params; + }, + + _newObject: function _newObject(response) { + var obj; + if (response && response.className) { + obj = new AV.Object(response.className); + } else { + obj = new this.objectClass(); + } + return obj; + }, + _createRequest: function _createRequest() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.toJSON(); + var options = arguments[1]; + + if (JSON.stringify(params).length > 2000) { + var body = { + requests: [{ + method: 'GET', + path: '/1.1/classes/' + this.className, + params: params + }] + }; + return AVRequest('batch', null, null, 'POST', body, options).then(function (response) { + var result = response[0]; + if (result.success) { + return result.success; + } + var error = new Error(result.error.error || 'Unknown batch error'); + error.code = result.error.code; + throw error; + }); + } + return AVRequest('classes', this.className, null, "GET", params, options); + }, + _parseResponse: function _parseResponse(response) { + var _this = this; + + return _.map(response.results, function (json) { + var obj = _this._newObject(response); + if (obj._finishFetch) { + obj._finishFetch(_this._processResult(json), true); + } + return obj; + }); + }, + + + /** + * Retrieves a list of AVObjects that satisfy this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the results when + * the query completes. + */ + find: function find(options) { + var request = this._createRequest(undefined, options); + return request.then(this._parseResponse.bind(this)); + }, + + + /** + * scan a Query. masterKey required. + * + * @since 2.1.0 + * @param {object} [options] + * @param {string} [options.orderedBy] specify the key to sort + * @param {number} [options.batchSize] specify the batch size for each request + * @param {AuthOptions} [authOptions] + * @return {AsyncIterator.} + * @example const scan = new AV.Query(TestClass).scan({ + * orderedBy: 'objectId', + * batchSize: 10, + * }, { + * useMasterKey: true, + * }); + * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next())); + * getTen().then(results => { + * // results are fisrt 10 instances of TestClass + * return getTen(); + * }).then(results => { + * // 11 - 20 + * }); + */ + scan: function scan() { + var _this2 = this; + + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + orderedBy = _ref.orderedBy, + batchSize = _ref.batchSize; + + var authOptions = arguments[1]; + + var condition = this.toJSON(); + debug('scan %O', condition); + if (condition.order) { + console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.'); + delete condition.order; + } + if (condition.skip) { + console.warn('The skip option of the query is ignored for Query#scan.'); + delete condition.skip; + } + if (condition.limit) { + console.warn('The limit option of the query is ignored for Query#scan.'); + delete condition.limit; + } + if (orderedBy) condition.scan_key = orderedBy; + if (batchSize) condition.limit = batchSize; + var promise = Promise.resolve([]); + var cursor = void 0; + var done = false; + return { + next: function next() { + promise = promise.then(function (remainResults) { + if (done) return []; + if (remainResults.length > 1) return remainResults; + // no cursor means we have reached the end + // except for the first time + if (!cursor && remainResults.length !== 0) { + done = true; + return remainResults; + } + // when only 1 item left in queue + // start the next request to see if it is the last one + return AVRequest('scan/classes', _this2.className, null, 'GET', cursor ? _.extend({}, condition, { cursor: cursor }) : condition, authOptions).then(function (response) { + cursor = response.cursor; + return _this2._parseResponse(response); + }).then(function (results) { + if (!results.length) done = true; + return remainResults.concat(results); + }); + }); + return promise.then(function (remainResults) { + return remainResults.shift(); + }).then(function (result) { + return { + value: result, + done: done + }; + }); + } + }; + }, + + + /** + * Delete objects retrieved by this query. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the save + * completes. + */ + destroyAll: function destroyAll(options) { + var self = this; + return self.find(options).then(function (objects) { + return AV.Object.destroyAll(objects, options); + }); + }, + + /** + * Counts the number of objects that match this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the count when + * the query completes. + */ + count: function count(options) { + var params = this.toJSON(); + params.limit = 0; + params.count = 1; + var request = this._createRequest(params, options); + + return request.then(function (response) { + return response.count; + }); + }, + + /** + * Retrieves at most one AV.Object that satisfies this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the object when + * the query completes. + */ + first: function first(options) { + var self = this; + + var params = this.toJSON(); + params.limit = 1; + var request = this._createRequest(params, options); + + return request.then(function (response) { + return _.map(response.results, function (json) { + var obj = self._newObject(); + if (obj._finishFetch) { + obj._finishFetch(self._processResult(json), true); + } + return obj; + })[0]; + }); + }, + + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * @param {Number} n the number of results to skip. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + skip: function skip(n) { + requires(n, 'undefined is not a valid skip value'); + this._skip = n; + return this; + }, + + /** + * Sets the limit of the number of results to return. The default limit is + * 100, with a maximum of 1000 results being returned at a time. + * @param {Number} n the number of results to limit to. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + limit: function limit(n) { + requires(n, 'undefined is not a valid limit value'); + this._limit = n; + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be equal to the provided value. + * @param {String} key The key to check. + * @param value The value that the AV.Object must contain. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + equalTo: function equalTo(key, value) { + requires(key, 'undefined is not a valid key'); + requires(value, 'undefined is not a valid value'); + this._where[key] = AV._encode(value); + return this; + }, + + /** + * Helper for condition queries + * @private + */ + _addCondition: function _addCondition(key, condition, value) { + requires(key, 'undefined is not a valid condition key'); + requires(condition, 'undefined is not a valid condition'); + requires(value, 'undefined is not a valid condition value'); + + // Check if we already have a condition + if (!this._where[key]) { + this._where[key] = {}; + } + this._where[key][condition] = AV._encode(value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular + * array key's length to be equal to the provided value. + * @param {String} key The array key to check. + * @param value The length value. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + sizeEqualTo: function sizeEqualTo(key, value) { + this._addCondition(key, "$size", value); + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be not equal to the provided value. + * @param {String} key The key to check. + * @param value The value that must not be equalled. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + notEqualTo: function notEqualTo(key, value) { + this._addCondition(key, "$ne", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than the provided value. + * @param {String} key The key to check. + * @param value The value that provides an upper bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + lessThan: function lessThan(key, value) { + this._addCondition(key, "$lt", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than the provided value. + * @param {String} key The key to check. + * @param value The value that provides an lower bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + greaterThan: function greaterThan(key, value) { + this._addCondition(key, "$gt", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than or equal to the provided value. + * @param {String} key The key to check. + * @param value The value that provides an upper bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + lessThanOrEqualTo: function lessThanOrEqualTo(key, value) { + this._addCondition(key, "$lte", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than or equal to the provided value. + * @param {String} key The key to check. + * @param value The value that provides an lower bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + greaterThanOrEqualTo: function greaterThanOrEqualTo(key, value) { + this._addCondition(key, "$gte", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be contained in the provided list of values. + * @param {String} key The key to check. + * @param {Array} values The values that will match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + containedIn: function containedIn(key, values) { + this._addCondition(key, "$in", values); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * not be contained in the provided list of values. + * @param {String} key The key to check. + * @param {Array} values The values that will not match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + notContainedIn: function notContainedIn(key, values) { + this._addCondition(key, "$nin", values); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * contain each one of the provided list of values. + * @param {String} key The key to check. This key's value must be an array. + * @param {Array} values The values that will match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + containsAll: function containsAll(key, values) { + this._addCondition(key, "$all", values); + return this; + }, + + /** + * Add a constraint for finding objects that contain the given key. + * @param {String} key The key that should exist. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + exists: function exists(key) { + this._addCondition(key, "$exists", true); + return this; + }, + + /** + * Add a constraint for finding objects that do not contain a given key. + * @param {String} key The key that should not exist + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotExist: function doesNotExist(key) { + this._addCondition(key, "$exists", false); + return this; + }, + + /** + * Add a regular expression constraint for finding string values that match + * the provided regular expression. + * This may be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {RegExp} regex The regular expression pattern to match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matches: function matches(key, regex, modifiers) { + this._addCondition(key, "$regex", regex); + if (!modifiers) { + modifiers = ""; + } + // Javascript regex options support mig as inline options but store them + // as properties of the object. We support mi & should migrate them to + // modifiers + if (regex.ignoreCase) { + modifiers += 'i'; + } + if (regex.multiline) { + modifiers += 'm'; + } + + if (modifiers && modifiers.length) { + this._addCondition(key, "$options", modifiers); + } + return this; + }, + + /** + * Add a constraint that requires that a key's value matches a AV.Query + * constraint. + * @param {String} key The key that the contains the object to match the + * query. + * @param {AV.Query} query The query that should match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matchesQuery: function matchesQuery(key, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$inQuery", queryJSON); + return this; + }, + + /** + * Add a constraint that requires that a key's value not matches a + * AV.Query constraint. + * @param {String} key The key that the contains the object to match the + * query. + * @param {AV.Query} query The query that should not match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotMatchQuery: function doesNotMatchQuery(key, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$notInQuery", queryJSON); + return this; + }, + + /** + * Add a constraint that requires that a key's value matches a value in + * an object returned by a different AV.Query. + * @param {String} key The key that contains the value that is being + * matched. + * @param {String} queryKey The key in the objects returned by the query to + * match against. + * @param {AV.Query} query The query to run. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matchesKeyInQuery: function matchesKeyInQuery(key, queryKey, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$select", { key: queryKey, query: queryJSON }); + return this; + }, + + /** + * Add a constraint that requires that a key's value not match a value in + * an object returned by a different AV.Query. + * @param {String} key The key that contains the value that is being + * excluded. + * @param {String} queryKey The key in the objects returned by the query to + * match against. + * @param {AV.Query} query The query to run. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotMatchKeyInQuery: function doesNotMatchKeyInQuery(key, queryKey, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$dontSelect", { key: queryKey, query: queryJSON }); + return this; + }, + + /** + * Add constraint that at least one of the passed in queries matches. + * @param {Array} queries + * @return {AV.Query} Returns the query, so you can chain this call. + * @private + */ + _orQuery: function _orQuery(queries) { + var queryJSON = _.map(queries, function (q) { + return q.toJSON().where; + }); + + this._where.$or = queryJSON; + return this; + }, + + /** + * Add constraint that both of the passed in queries matches. + * @param {Array} queries + * @return {AV.Query} Returns the query, so you can chain this call. + * @private + */ + _andQuery: function _andQuery(queries) { + var queryJSON = _.map(queries, function (q) { + return q.toJSON().where; + }); + + this._where.$and = queryJSON; + return this; + }, + + /** + * Converts a string into a regex that matches it. + * Surrounding with \Q .. \E does this, we just need to escape \E's in + * the text separately. + * @private + */ + _quote: function _quote(s) { + return "\\Q" + s.replace("\\E", "\\E\\\\E\\Q") + "\\E"; + }, + + /** + * Add a constraint for finding string values that contain a provided + * string. This may be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} substring The substring that the value must contain. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + contains: function contains(key, value) { + this._addCondition(key, "$regex", this._quote(value)); + return this; + }, + + /** + * Add a constraint for finding string values that start with a provided + * string. This query will use the backend index, so it will be fast even + * for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} prefix The substring that the value must start with. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + startsWith: function startsWith(key, value) { + this._addCondition(key, "$regex", "^" + this._quote(value)); + return this; + }, + + /** + * Add a constraint for finding string values that end with a provided + * string. This will be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} suffix The substring that the value must end with. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + endsWith: function endsWith(key, value) { + this._addCondition(key, "$regex", this._quote(value) + "$"); + return this; + }, + + /** + * Sorts the results in ascending order by the given key. + * + * @param {String} key The key to order by. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + ascending: function ascending(key) { + requires(key, 'undefined is not a valid key'); + this._order = key; + return this; + }, + + /** + * Also sorts the results in ascending order by the given key. The previous sort keys have + * precedence over this key. + * + * @param {String} key The key to order by + * @return {AV.Query} Returns the query so you can chain this call. + */ + addAscending: function addAscending(key) { + requires(key, 'undefined is not a valid key'); + if (this._order) this._order += ',' + key;else this._order = key; + return this; + }, + + /** + * Sorts the results in descending order by the given key. + * + * @param {String} key The key to order by. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + descending: function descending(key) { + requires(key, 'undefined is not a valid key'); + this._order = "-" + key; + return this; + }, + + /** + * Also sorts the results in descending order by the given key. The previous sort keys have + * precedence over this key. + * + * @param {String} key The key to order by + * @return {AV.Query} Returns the query so you can chain this call. + */ + addDescending: function addDescending(key) { + requires(key, 'undefined is not a valid key'); + if (this._order) this._order += ',-' + key;else this._order = '-' + key; + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + near: function near(key, point) { + if (!(point instanceof AV.GeoPoint)) { + // Try to cast it to a GeoPoint, so that near("loc", [20,30]) works. + point = new AV.GeoPoint(point); + } + this._addCondition(key, "$nearSphere", point); + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param maxDistance Maximum distance (in radians) of results to return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinRadians: function withinRadians(key, point, distance) { + this.near(key, point); + this._addCondition(key, "$maxDistance", distance); + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 3958.8 miles. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Number} maxDistance Maximum distance (in miles) of results to + * return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinMiles: function withinMiles(key, point, distance) { + return this.withinRadians(key, point, distance / 3958.8); + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 6371.0 kilometers. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Number} maxDistance Maximum distance (in kilometers) of results + * to return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinKilometers: function withinKilometers(key, point, distance) { + return this.withinRadians(key, point, distance / 6371.0); + }, + + /** + * Add a constraint to the query that requires a particular key's + * coordinates be contained within a given rectangular geographic bounding + * box. + * @param {String} key The key to be constrained. + * @param {AV.GeoPoint} southwest + * The lower-left inclusive corner of the box. + * @param {AV.GeoPoint} northeast + * The upper-right inclusive corner of the box. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinGeoBox: function withinGeoBox(key, southwest, northeast) { + if (!(southwest instanceof AV.GeoPoint)) { + southwest = new AV.GeoPoint(southwest); + } + if (!(northeast instanceof AV.GeoPoint)) { + northeast = new AV.GeoPoint(northeast); + } + this._addCondition(key, '$within', { '$box': [southwest, northeast] }); + return this; + }, + + /** + * Include nested AV.Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetch. + * @param {String[]} keys The name of the key to include. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + include: function include(keys) { + var _this3 = this; + + requires(keys, 'undefined is not a valid key'); + _(arguments).forEach(function (keys) { + _this3._include = _this3._include.concat(ensureArray(keys)); + }); + return this; + }, + + /** + * Restrict the fields of the returned AV.Objects to include only the + * provided keys. If this is called multiple times, then all of the keys + * specified in each of the calls will be included. + * @param {String[]} keys The names of the keys to include. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + select: function select(keys) { + var _this4 = this; + + requires(keys, 'undefined is not a valid key'); + _(arguments).forEach(function (keys) { + _this4._select = _this4._select.concat(ensureArray(keys)); + }); + return this; + }, + + /** + * Iterates over each result of a query, calling a callback for each one. If + * the callback returns a promise, the iteration will not continue until + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are + * processed in an unspecified order. The query may not have any sort order, + * and may not use limit or skip. + * @param callback {Function} Callback that will be called with each result + * of the query. + * @return {Promise} A promise that will be fulfilled once the + * iteration has completed. + */ + each: function each(callback) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + + if (this._order || this._skip || this._limit >= 0) { + var error = new Error("Cannot iterate on a query with sort, skip, or limit."); + return AV.Promise.reject(error); + } + + var query = new AV.Query(this.objectClass); + // We can override the batch size from the options. + // This is undocumented, but useful for testing. + query._limit = options.batchSize || 100; + query._where = _.clone(this._where); + query._include = _.clone(this._include); + + query.ascending('objectId'); + + var finished = false; + return AV.Promise._continueWhile(function () { + return !finished; + }, function () { + return query.find(options).then(function (results) { + var callbacksDone = AV.Promise.resolve(); + _.each(results, function (result) { + callbacksDone = callbacksDone.then(function () { + return callback(result); + }); + }); + + return callbacksDone.then(function () { + if (results.length >= query._limit) { + query.greaterThan("objectId", results[results.length - 1].id); + } else { + finished = true; + } + }); + }); + }); + } + }; + + AV.FriendShipQuery = AV.Query._extend({ + _objectClass: AV.User, + _newObject: function _newObject() { + return new AV.User(); + }, + _processResult: function _processResult(json) { + if (json && json[this._friendshipTag]) { + var user = json[this._friendshipTag]; + if (user.__type === 'Pointer' && user.className === '_User') { + delete user.__type; + delete user.className; + } + return user; + } else { + return null; + } + } + }); +}; + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + /** + * Creates a new Relation for the given parent object and key. This + * constructor should rarely be used directly, but rather created by + * {@link AV.Object#relation}. + * @param {AV.Object} parent The parent of this relation. + * @param {String} key The key for this relation on the parent. + * @see AV.Object#relation + * @class + * + *

+ * A class that is used to access all of the children of a many-to-many + * relationship. Each instance of AV.Relation is associated with a + * particular parent object and key. + *

+ */ + AV.Relation = function (parent, key) { + if (!_.isString(key)) { + throw new TypeError('key must be a string'); + } + this.parent = parent; + this.key = key; + this.targetClassName = null; + }; + + /** + * Creates a query that can be used to query the parent objects in this relation. + * @param {String} parentClass The parent class or name. + * @param {String} relationKey The relation field key in parent. + * @param {AV.Object} child The child object. + * @return {AV.Query} + */ + AV.Relation.reverseQuery = function (parentClass, relationKey, child) { + var query = new AV.Query(parentClass); + query.equalTo(relationKey, child._toPointer()); + return query; + }; + + AV.Relation.prototype = { + /** + * Makes sure that this relation has the right parent and key. + * @private + */ + _ensureParentAndKey: function _ensureParentAndKey(parent, key) { + this.parent = this.parent || parent; + this.key = this.key || key; + if (this.parent !== parent) { + throw new Error("Internal Error. Relation retrieved from two different Objects."); + } + if (this.key !== key) { + throw new Error("Internal Error. Relation retrieved from two different keys."); + } + }, + + /** + * Adds a AV.Object or an array of AV.Objects to the relation. + * @param {AV.Object|AV.Object[]} objects The item or items to add. + */ + add: function add(objects) { + if (!_.isArray(objects)) { + objects = [objects]; + } + + var change = new AV.Op.Relation(objects, []); + this.parent.set(this.key, change); + this.targetClassName = change._targetClassName; + }, + + /** + * Removes a AV.Object or an array of AV.Objects from this relation. + * @param {AV.Object|AV.Object[]} objects The item or items to remove. + */ + remove: function remove(objects) { + if (!_.isArray(objects)) { + objects = [objects]; + } + + var change = new AV.Op.Relation([], objects); + this.parent.set(this.key, change); + this.targetClassName = change._targetClassName; + }, + + /** + * Returns a JSON version of the object suitable for saving to disk. + * @return {Object} + */ + toJSON: function toJSON() { + return { "__type": "Relation", "className": this.targetClassName }; + }, + + /** + * Returns a AV.Query that is limited to objects in this + * relation. + * @return {AV.Query} + */ + query: function query() { + var targetClass; + var query; + if (!this.targetClassName) { + targetClass = AV.Object._getSubclass(this.parent.className); + query = new AV.Query(targetClass); + query._extraOptions.redirectClassNameForKey = this.key; + } else { + targetClass = AV.Object._getSubclass(this.targetClassName); + query = new AV.Query(targetClass); + } + query._addCondition("$relatedTo", "object", this.parent._toPointer()); + query._addCondition("$relatedTo", "key", this.key); + + return query; + } + }; +}; + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); + +module.exports = function (AV) { + AV.Role = AV.Object.extend("_Role", /** @lends AV.Role.prototype */{ + // Instance Methods + + /** + * Represents a Role on the AV server. Roles represent groupings of + * Users for the purposes of granting permissions (e.g. specifying an ACL + * for an Object). Roles are specified by their sets of child users and + * child roles, all of which are granted any permissions that the parent + * role has. + * + *

Roles must have a name (which cannot be changed after creation of the + * role), and must specify an ACL.

+ * An AV.Role is a local representation of a role persisted to the AV + * cloud. + * @class AV.Role + * @param {String} name The name of the Role to create. + * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL + * `{'*': { read: true }}` will be used. + */ + constructor: function constructor(name, acl, noDefaultACL) { + if (_.isString(name)) { + AV.Object.prototype.constructor.call(this, null, null); + this.setName(name); + } else { + AV.Object.prototype.constructor.call(this, name, acl); + } + if (acl === undefined) { + if (!noDefaultACL) { + if (!this.getACL()) { + console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.'); + var defaultAcl = new AV.ACL(); + defaultAcl.setPublicReadAccess(true); + this.setACL(defaultAcl); + } + } + } else if (!(acl instanceof AV.ACL)) { + throw new TypeError('acl must be an instance of AV.ACL'); + } else { + this.setACL(acl); + } + }, + + /** + * Gets the name of the role. You can alternatively call role.get("name") + * + * @return {String} the name of the role. + */ + getName: function getName() { + return this.get("name"); + }, + + /** + * Sets the name for a role. This value must be set before the role has + * been saved to the server, and cannot be set once the role has been + * saved. + * + *

+ * A role's name can only contain alphanumeric characters, _, -, and + * spaces. + *

+ * + *

This is equivalent to calling role.set("name", name)

+ * + * @param {String} name The name of the role. + */ + setName: function setName(name, options) { + return this.set("name", name, options); + }, + + /** + * Gets the AV.Relation for the AV.Users that are direct + * children of this role. These users are granted any privileges that this + * role has been granted (e.g. read or write access through ACLs). You can + * add or remove users from the role through this relation. + * + *

This is equivalent to calling role.relation("users")

+ * + * @return {AV.Relation} the relation for the users belonging to this + * role. + */ + getUsers: function getUsers() { + return this.relation("users"); + }, + + /** + * Gets the AV.Relation for the AV.Roles that are direct + * children of this role. These roles' users are granted any privileges that + * this role has been granted (e.g. read or write access through ACLs). You + * can add or remove child roles from this role through this relation. + * + *

This is equivalent to calling role.relation("roles")

+ * + * @return {AV.Relation} the relation for the roles belonging to this + * role. + */ + getRoles: function getRoles() { + return this.relation("roles"); + }, + + /** + * @ignore + */ + validate: function validate(attrs, options) { + if ("name" in attrs && attrs.name !== this.getName()) { + var newName = attrs.name; + if (this.id && this.id !== attrs.objectId) { + // Check to see if the objectId being set matches this.id. + // This happens during a fetch -- the id is set before calling fetch. + // Let the name be set in this case. + return new AVError(AVError.OTHER_CAUSE, "A role's name can only be set before it has been saved."); + } + if (!_.isString(newName)) { + return new AVError(AVError.OTHER_CAUSE, "A role's name must be a String."); + } + if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) { + return new AVError(AVError.OTHER_CAUSE, "A role's name can only contain alphanumeric characters, _," + " -, and spaces."); + } + } + if (AV.Object.prototype.validate) { + return AV.Object.prototype.validate.call(this, attrs, options); + } + return false; + } + }); +}; + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * A builder to generate sort string for app searching.For example: + * @class + * @since 0.5.1 + * @example + * var builder = new AV.SearchSortBuilder(); + * builder.ascending('key1').descending('key2','max'); + * var query = new AV.SearchQuery('Player'); + * query.sortBy(builder); + * query.find().then(); + */ + AV.SearchSortBuilder = function () { + this._sortFields = []; + }; + + AV.SearchSortBuilder.prototype = { + _addField: function _addField(key, order, mode, missing) { + var field = {}; + field[key] = { + order: order || 'asc', + mode: mode || 'avg', + missing: '_' + (missing || 'last') + }; + this._sortFields.push(field); + return this; + }, + + /** + * Sorts the results in ascending order by the given key and options. + * + * @param {String} key The key to order by. + * @param {String} mode The sort mode, default is 'avg', you can choose + * 'max' or 'min' too. + * @param {String} missing The missing key behaviour, default is 'last', + * you can choose 'first' too. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + ascending: function ascending(key, mode, missing) { + return this._addField(key, 'asc', mode, missing); + }, + + /** + * Sorts the results in descending order by the given key and options. + * + * @param {String} key The key to order by. + * @param {String} mode The sort mode, default is 'avg', you can choose + * 'max' or 'min' too. + * @param {String} missing The missing key behaviour, default is 'last', + * you can choose 'first' too. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + descending: function descending(key, mode, missing) { + return this._addField(key, 'desc', mode, missing); + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Object} options The other options such as mode,order, unit etc. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + whereNear: function whereNear(key, point, options) { + options = options || {}; + var field = {}; + var geo = { + lat: point.latitude, + lon: point.longitude + }; + var m = { + order: options.order || 'asc', + mode: options.mode || 'avg', + unit: options.unit || 'km' + }; + m[key] = geo; + field['_geo_distance'] = m; + + this._sortFields.push(field); + return this; + }, + + /** + * Build a sort string by configuration. + * @return {String} the sort string. + */ + build: function build() { + return JSON.stringify(AV._encode(this._sortFields)); + } + }; + + /** + * App searching query.Use just like AV.Query: + * + * Visit App Searching Guide + * for more details. + * @class + * @since 0.5.1 + * @example + * var query = new AV.SearchQuery('Player'); + * query.queryString('*'); + * query.find().then(function(results) { + * console.log('Found %d objects', query.hits()); + * //Process results + * }); + */ + AV.SearchQuery = AV.Query._extend( /** @lends AV.SearchQuery.prototype */{ + _sid: null, + _hits: 0, + _queryString: null, + _highlights: null, + _sortBuilder: null, + _createRequest: function _createRequest(params, options) { + return AVRequest('search/select', null, null, 'GET', params || this.toJSON(), options); + }, + + /** + * Sets the sid of app searching query.Default is null. + * @param {String} sid Scroll id for searching. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + sid: function sid(_sid) { + this._sid = _sid; + return this; + }, + + /** + * Sets the query string of app searching. + * @param {String} q The query string. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + queryString: function queryString(q) { + this._queryString = q; + return this; + }, + + /** + * Sets the highlight fields. Such as + *

+     *   query.highlights('title');
+     *   //or pass an array.
+     *   query.highlights(['title', 'content'])
+     * 
+ * @param {String[]} highlights a list of fields. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + highlights: function highlights(_highlights) { + var objects; + if (_highlights && _.isString(_highlights)) { + objects = arguments; + } else { + objects = _highlights; + } + this._highlights = objects; + return this; + }, + + /** + * Sets the sort builder for this query. + * @see AV.SearchSortBuilder + * @param { AV.SearchSortBuilder} builder The sort builder. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + * + */ + sortBy: function sortBy(builder) { + this._sortBuilder = builder; + return this; + }, + + /** + * Returns the number of objects that match this query. + * @return {Number} + */ + hits: function hits() { + if (!this._hits) { + this._hits = 0; + } + return this._hits; + }, + + _processResult: function _processResult(json) { + delete json['className']; + delete json['_app_url']; + delete json['_deeplink']; + return json; + }, + + /** + * Returns true when there are more documents can be retrieved by this + * query instance, you can call find function to get more results. + * @see AV.SearchQuery#find + * @return {Boolean} + */ + hasMore: function hasMore() { + return !this._hitEnd; + }, + + /** + * Reset current query instance state(such as sid, hits etc) except params + * for a new searching. After resetting, hasMore() will return true. + */ + reset: function reset() { + this._hitEnd = false; + this._sid = null; + this._hits = 0; + }, + + /** + * Retrieves a list of AVObjects that satisfy this query. + * Either options.success or options.error is called when the find + * completes. + * + * @see AV.Query#find + * @return {AV.Promise} A promise that is resolved with the results when + * the query completes. + */ + find: function find() { + var self = this; + + var request = this._createRequest(); + + return request.then(function (response) { + //update sid for next querying. + if (response.sid) { + self._oldSid = self._sid; + self._sid = response.sid; + } else { + self._sid = null; + self._hitEnd = true; + } + self._hits = response.hits || 0; + + return _.map(response.results, function (json) { + if (json.className) { + response.className = json.className; + } + var obj = self._newObject(response); + obj.appURL = json['_app_url']; + obj._finishFetch(self._processResult(json), true); + return obj; + }); + }); + }, + + toJSON: function toJSON() { + var params = AV.SearchQuery.__super__.toJSON.call(this); + delete params.where; + if (this.className) { + params.clazz = this.className; + } + if (this._sid) { + params.sid = this._sid; + } + if (!this._queryString) { + throw new Error('Please set query string.'); + } else { + params.q = this._queryString; + } + if (this._highlights) { + params.highlights = this._highlights.join(','); + } + if (this._sortBuilder && params.order) { + throw new Error('sort and order can not be set at same time.'); + } + if (this._sortBuilder) { + params.sort = this._sortBuilder.build(); + } + + return params; + } + }); +}; + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + var getUser = function getUser() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return AV.User.currentAsync().then(function (currUser) { + return currUser || AV.User._fetchUserBySessionToken(options.sessionToken); + }); + }; + + var getUserPointer = function getUserPointer(options) { + return getUser(options).then(function (currUser) { + return AV.Object.createWithoutData('_User', currUser.id)._toPointer(); + }); + }; + + /** + * Contains functions to deal with Status in LeanCloud. + * @class + */ + AV.Status = function (imageUrl, message) { + this.data = {}; + this.inboxType = 'default'; + this.query = null; + if (imageUrl && (typeof imageUrl === 'undefined' ? 'undefined' : _typeof(imageUrl)) === 'object') { + this.data = imageUrl; + } else { + if (imageUrl) { + this.data.image = imageUrl; + } + if (message) { + this.data.message = message; + } + } + return this; + }; + + AV.Status.prototype = { + /** + * Gets the value of an attribute in status data. + * @param {String} attr The string name of an attribute. + */ + get: function get(attr) { + return this.data[attr]; + }, + /** + * Sets a hash of model attributes on the status data. + * @param {String} key The key to set. + * @param {} value The value to give it. + */ + set: function set(key, value) { + this.data[key] = value; + return this; + }, + /** + * Destroy this status,then it will not be avaiable in other user's inboxes. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + if (!this.id) return AV.Promise.reject(new Error('The status id is not exists.')); + var request = AVRequest('statuses', null, this.id, 'DELETE', options); + return request; + }, + /** + * Cast the AV.Status object to an AV.Object pointer. + * @return {AV.Object} A AV.Object pointer. + */ + toObject: function toObject() { + if (!this.id) return null; + return AV.Object.createWithoutData('_Status', this.id); + }, + _getDataJSON: function _getDataJSON() { + var json = _.clone(this.data); + return AV._encode(json); + }, + /** + * Send a status by a AV.Query object. + * @since 0.3.0 + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * // send a status to male users + * var status = new AVStatus('image url', 'a message'); + * status.query = new AV.Query('_User'); + * status.query.equalTo('gender', 'male'); + * status.send().then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + send: function send() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + if (!this.query) { + return AV.Status.sendStatusToFollowers(this, options); + } + + return getUserPointer(options).then(function (currUser) { + var query = _this.query.toJSON(); + query.className = _this.query.className; + var data = {}; + data.query = query; + _this.data = _this.data || {}; + _this.data.source = _this.data.source || currUser; + data.data = _this._getDataJSON(); + data.inboxType = _this.inboxType || 'default'; + + return AVRequest('statuses', null, null, 'POST', data, options); + }).then(function (response) { + _this.id = response.objectId; + _this.createdAt = AV._parseDate(response.createdAt); + return _this; + }); + }, + + _finishFetch: function _finishFetch(serverData) { + this.id = serverData.objectId; + this.createdAt = AV._parseDate(serverData.createdAt); + this.updatedAt = AV._parseDate(serverData.updatedAt); + this.messageId = serverData.messageId; + delete serverData.messageId; + delete serverData.objectId; + delete serverData.createdAt; + delete serverData.updatedAt; + this.data = AV._decode(serverData); + } + }; + + /** + * Send a status to current signined user's followers. + * @since 0.3.0 + * @param {AV.Status} status A status object to be send to followers. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * var status = new AVStatus('image url', 'a message'); + * AV.Status.sendStatusToFollowers(status).then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + AV.Status.sendStatusToFollowers = function (status) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + return getUserPointer(options).then(function (currUser) { + var query = {}; + query.className = '_Follower'; + query.keys = 'follower'; + query.where = { user: currUser }; + var data = {}; + data.query = query; + status.data = status.data || {}; + status.data.source = status.data.source || currUser; + data.data = status._getDataJSON(); + data.inboxType = status.inboxType || 'default'; + + var request = AVRequest('statuses', null, null, 'POST', data, options); + return request.then(function (response) { + status.id = response.objectId; + status.createdAt = AV._parseDate(response.createdAt); + return status; + }); + }); + }; + + /** + *

Send a status from current signined user to other user's private status inbox.

+ * @since 0.3.0 + * @param {AV.Status} status A status object to be send to followers. + * @param {String} target The target user or user's objectId. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * // send a private status to user '52e84e47e4b0f8de283b079b' + * var status = new AVStatus('image url', 'a message'); + * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + AV.Status.sendPrivateStatus = function (status, target) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + if (!target) { + throw new Error("Invalid target user."); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error("Invalid target user."); + } + return getUserPointer(options).then(function (currUser) { + var query = {}; + query.className = '_User'; + query.where = { objectId: userObjectId }; + var data = {}; + data.query = query; + status.data = status.data || {}; + status.data.source = status.data.source || currUser; + data.data = status._getDataJSON(); + data.inboxType = 'private'; + status.inboxType = 'private'; + + var request = AVRequest('statuses', null, null, 'POST', data, options); + return request.then(function (response) { + status.id = response.objectId; + status.createdAt = AV._parseDate(response.createdAt); + return status; + }); + }); + }; + + /** + * Count unread statuses in someone's inbox. + * @since 0.3.0 + * @param {Object} owner The status owner. + * @param {String} inboxType The inbox type, 'default' by default. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the count + * completes. + * @example + * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){ + * console.log(response.unread); //unread statuses number. + * console.log(response.total); //total statuses number. + * }); + */ + AV.Status.countUnreadStatuses = function (owner) { + var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!_.isString(inboxType)) options = inboxType; + if (!options.sessionToken && owner == null && !AV.User.current()) { + throw new Error('Please signin an user or pass the owner objectId.'); + } + return getUser(options).then(function (owner) { + var params = {}; + params.inboxType = AV._encode(inboxType); + params.owner = AV._encode(owner); + return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options); + }); + }; + + /** + * reset unread statuses count in someone's inbox. + * @since 2.1.0 + * @param {Object} owner The status owner. + * @param {String} inboxType The inbox type, 'default' by default. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the reset + * completes. + * @example + * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){ + * console.log(response.unread); //unread statuses number. + * console.log(response.total); //total statuses number. + * }); + */ + AV.Status.resetUnreadCount = function (owner) { + var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!_.isString(inboxType)) options = inboxType; + if (!options.sessionToken && owner == null && !AV.User.current()) { + throw new Error('Please signin an user or pass the owner objectId.'); + } + return getUser(options).then(function (owner) { + var params = {}; + params.inboxType = AV._encode(inboxType); + params.owner = AV._encode(owner); + return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options); + }); + }; + + /** + * Create a status query to find someone's published statuses. + * @since 0.3.0 + * @param {Object} source The status source. + * @return {AV.Query} The query object for status. + * @example + * //Find current user's published statuses. + * var query = AV.Status.statusQuery(AV.User.current()); + * query.find().then(function(statuses){ + * //process statuses + * }); + */ + AV.Status.statusQuery = function (source) { + var query = new AV.Query('_Status'); + if (source) { + query.equalTo('source', source); + } + return query; + }; + + /** + *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

+ * @class + */ + AV.InboxQuery = AV.Query._extend( /** @lends AV.InboxQuery.prototype */{ + _objectClass: AV.Status, + _sinceId: 0, + _maxId: 0, + _inboxType: 'default', + _owner: null, + _newObject: function _newObject() { + return new AV.Status(); + }, + _createRequest: function _createRequest(params, options) { + return AVRequest('subscribe/statuses', null, null, 'GET', params || this.toJSON(), options); + }, + + /** + * Sets the messageId of results to skip before returning any results. + * This is useful for pagination. + * Default is zero. + * @param {Number} n the mesage id. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + sinceId: function sinceId(id) { + this._sinceId = id; + return this; + }, + /** + * Sets the maximal messageId of results。 + * This is useful for pagination. + * Default is zero that is no limition. + * @param {Number} n the mesage id. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + maxId: function maxId(id) { + this._maxId = id; + return this; + }, + /** + * Sets the owner of the querying inbox. + * @param {Object} owner The inbox owner. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + owner: function owner(_owner) { + this._owner = _owner; + return this; + }, + /** + * Sets the querying inbox type.default is 'default'. + * @param {Object} owner The inbox type. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + inboxType: function inboxType(type) { + this._inboxType = type; + return this; + }, + toJSON: function toJSON() { + var params = AV.InboxQuery.__super__.toJSON.call(this); + params.owner = AV._encode(this._owner); + params.inboxType = AV._encode(this._inboxType); + params.sinceId = AV._encode(this._sinceId); + params.maxId = AV._encode(this._maxId); + return params; + } + }); + + /** + * Create a inbox status query to find someone's inbox statuses. + * @since 0.3.0 + * @param {Object} owner The inbox's owner + * @param {String} inboxType The inbox type,'default' by default. + * @return {AV.InboxQuery} The inbox query object. + * @see AV.InboxQuery + * @example + * //Find current user's default inbox statuses. + * var query = AV.Status.inboxQuery(AV.User.current()); + * //find the statuses after the last message id + * query.sinceId(lastMessageId); + * query.find().then(function(statuses){ + * //process statuses + * }); + */ + AV.Status.inboxQuery = function (owner, inboxType) { + var query = new AV.InboxQuery(AV.Status); + if (owner) { + query._owner = owner; + } + if (inboxType) { + query._inboxType = inboxType; + } + return query; + }; +}; + +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = []; + +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var version = __webpack_require__(18); +var comments = ["Weapp" || 'Node.js'].concat(__webpack_require__(41)); + +module.exports = 'LeanCloud-JS-SDK/' + version + ' (' + comments.join('; ') + ')'; + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var debug = __webpack_require__(5)('cos'); +var Promise = __webpack_require__(1); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + var uploadUrl = uploadInfo.upload_url + "?sign=" + encodeURIComponent(uploadInfo.token); + + return new Promise(function (resolve, reject) { + var req = request('POST', uploadUrl).field('fileContent', data).field('op', 'upload'); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (res) { + debug(res.status, res.body, res.text); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var Promise = __webpack_require__(1); +var debug = __webpack_require__(5)('qiniu'); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + // Get the uptoken to upload files to qiniu. + var uptoken = uploadInfo.token; + return new Promise(function (resolve, reject) { + var req = request('POST', 'https://up.qbox.me').field('file', data).field('name', file.attributes.name).field('key', file._qiniu_key).field('token', uptoken); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (res) { + debug(res.status, res.body, res.text); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var AVPromise = __webpack_require__(1); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + return new Promise(function (resolve, reject) { + // 海外节点,针对 S3 才会返回 upload_url + var req = request('PUT', uploadInfo.upload_url).set('Content-Type', file.get('mime_type')).send(data); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var Promise = __webpack_require__(1); + +var getWeappLoginCode = function getWeappLoginCode() { + if (typeof wx === 'undefined' || typeof wx.login !== 'function') { + throw new Error('Weapp Login is only available in Weapp'); + } + return new Promise(function (resolve, reject) { + wx.login({ + success: function success(_ref) { + var code = _ref.code, + errMsg = _ref.errMsg; + + if (code) { + resolve(code); + } else { + reject(new Error(errMsg)); + } + } + }); + }); +}; + +module.exports = function (AV) { + /** + * @class + * + *

An AV.User object is a local representation of a user persisted to the + * LeanCloud server. This class is a subclass of an AV.Object, and retains the + * same functionality of an AV.Object, but also extends it with various + * user specific methods, like authentication, signing up, and validation of + * uniqueness.

+ */ + AV.User = AV.Object.extend("_User", /** @lends AV.User.prototype */{ + // Instance Variables + _isCurrentUser: false, + + // Instance Methods + + /** + * Internal method to handle special fields in a _User response. + * @private + */ + _mergeMagicFields: function _mergeMagicFields(attrs) { + if (attrs.sessionToken) { + this._sessionToken = attrs.sessionToken; + delete attrs.sessionToken; + } + AV.User.__super__._mergeMagicFields.call(this, attrs); + }, + + /** + * Removes null values from authData (which exist temporarily for + * unlinking) + * @private + */ + _cleanupAuthData: function _cleanupAuthData() { + if (!this.isCurrent()) { + return; + } + var authData = this.get('authData'); + if (!authData) { + return; + } + AV._objectEach(this.get('authData'), function (value, key) { + if (!authData[key]) { + delete authData[key]; + } + }); + }, + + /** + * Synchronizes authData for all providers. + * @private + */ + _synchronizeAllAuthData: function _synchronizeAllAuthData() { + var authData = this.get('authData'); + if (!authData) { + return; + } + + var self = this; + AV._objectEach(this.get('authData'), function (value, key) { + self._synchronizeAuthData(key); + }); + }, + + /** + * Synchronizes auth data for a provider (e.g. puts the access token in the + * right place to be used by the Facebook SDK). + * @private + */ + _synchronizeAuthData: function _synchronizeAuthData(provider) { + if (!this.isCurrent()) { + return; + } + var authType; + if (_.isString(provider)) { + authType = provider; + provider = AV.User._authProviders[authType]; + } else { + authType = provider.getAuthType(); + } + var authData = this.get('authData'); + if (!authData || !provider) { + return; + } + var success = provider.restoreAuthentication(authData[authType]); + if (!success) { + this._unlinkFrom(provider); + } + }, + + _handleSaveResult: function _handleSaveResult(makeCurrent) { + // Clean up and synchronize the authData object, removing any unset values + if (makeCurrent && !AV._config.disableCurrentUser) { + this._isCurrentUser = true; + } + this._cleanupAuthData(); + this._synchronizeAllAuthData(); + // Don't keep the password around. + delete this._serverData.password; + this._rebuildEstimatedDataForKey("password"); + this._refreshCache(); + if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) { + // Some old version of leanengine-node-sdk will overwrite + // AV.User._saveCurrentUser which returns no Promise. + // So we need a Promise wrapper. + return Promise.resolve(AV.User._saveCurrentUser(this)); + } else { + return Promise.resolve(); + } + }, + + /** + * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can + * call linkWith on the user (even if it doesn't exist yet on the server). + * @private + */ + _linkWith: function _linkWith(provider, data) { + var _this = this; + + var authType; + if (_.isString(provider)) { + authType = provider; + provider = AV.User._authProviders[provider]; + } else { + authType = provider.getAuthType(); + } + if (data) { + var authData = this.get('authData') || {}; + authData[authType] = data; + return this.save({ authData: authData }).then(function (model) { + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + } else { + return provider.authenticate().then(function (result) { + return _this._linkWith(provider, result); + }); + } + }, + + /** + * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。 + * 仅在小程序中可用。 + * + * @return {AV.User} + */ + linkWithWeapp: function linkWithWeapp() { + var _this2 = this; + + return getWeappLoginCode().then(function (code) { + return _this2._linkWith('lc_weapp', { code: code }); + }); + }, + + + /** + * Unlinks a user from a service. + * @private + */ + _unlinkFrom: function _unlinkFrom(provider) { + var _this3 = this; + + if (_.isString(provider)) { + provider = AV.User._authProviders[provider]; + } + return this._linkWith(provider, null).then(function (model) { + _this3._synchronizeAuthData(provider); + return model; + }); + }, + + /** + * Checks whether a user is linked to a service. + * @private + */ + _isLinked: function _isLinked(provider) { + var authType; + if (_.isString(provider)) { + authType = provider; + } else { + authType = provider.getAuthType(); + } + var authData = this.get('authData') || {}; + return !!authData[authType]; + }, + + logOut: function logOut() { + this._logOutWithAll(); + this._isCurrentUser = false; + }, + + /** + * Deauthenticates all providers. + * @private + */ + _logOutWithAll: function _logOutWithAll() { + var authData = this.get('authData'); + if (!authData) { + return; + } + var self = this; + AV._objectEach(this.get('authData'), function (value, key) { + self._logOutWith(key); + }); + }, + + /** + * Deauthenticates a single provider (e.g. removing access tokens from the + * Facebook SDK). + * @private + */ + _logOutWith: function _logOutWith(provider) { + if (!this.isCurrent()) { + return; + } + if (_.isString(provider)) { + provider = AV.User._authProviders[provider]; + } + if (provider && provider.deauthenticate) { + provider.deauthenticate(); + } + }, + + /** + * Signs up a new user. You should call this instead of save for + * new AV.Users. This will create a new AV.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {Object} attrs Extra fields to set on the new user, or null. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the signup + * finishes. + * @see AV.User.signUp + */ + signUp: function signUp(attrs, options) { + var error; + + var username = attrs && attrs.username || this.get("username"); + if (!username || username === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up user with an empty name."); + throw error; + } + + var password = attrs && attrs.password || this.get("password"); + if (!password || password === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up user with an empty password."); + throw error; + } + + return this.save(attrs, options).then(function (model) { + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + }, + + /** + * Signs up a new user with mobile phone and sms code. + * You should call this instead of save for + * new AV.Users. This will create a new AV.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {Object} attrs Extra fields to set on the new user, or null. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the signup + * finishes. + * @see AV.User.signUpOrlogInWithMobilePhone + * @see AV.Cloud.requestSmsCode + */ + signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(attrs) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var error; + + var mobilePhoneNumber = attrs && attrs.mobilePhoneNumber || this.get("mobilePhoneNumber"); + if (!mobilePhoneNumber || mobilePhoneNumber === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up or login user by mobilePhoneNumber " + "with an empty mobilePhoneNumber."); + throw error; + } + + var smsCode = attrs && attrs.smsCode || this.get("smsCode"); + if (!smsCode || smsCode === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up or login user by mobilePhoneNumber " + "with an empty smsCode."); + throw error; + } + + options._makeRequest = function (route, className, id, method, json) { + return AVRequest('usersByMobilePhone', null, null, "POST", json); + }; + return this.save(attrs, options).then(function (model) { + delete model.attributes.smsCode; + delete model._serverData.smsCode; + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + }, + + /** + * Logs in a AV.User. On success, this saves the session to localStorage, + * so you can retrieve the currently logged in user using + * current. + * + *

A username and password must be set before calling logIn.

+ * + * @see AV.User.logIn + * @return {Promise} A promise that is fulfilled with the user when + * the login is complete. + */ + logIn: function logIn() { + var model = this; + var request = AVRequest('login', null, null, 'POST', this.toJSON()); + return request.then(function (resp) { + var serverAttrs = model.parse(resp); + model._finishFetch(serverAttrs); + return model._handleSaveResult(true).then(function () { + if (!serverAttrs.smsCode) delete model.attributes['smsCode']; + return model; + }); + }); + }, + /** + * @see AV.Object#save + */ + save: function save(arg1, arg2, arg3) { + var i, attrs, current, options, saved; + if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) { + attrs = arg1; + options = arg2; + } else { + attrs = {}; + attrs[arg1] = arg2; + options = arg3; + } + options = options || {}; + + return AV.Object.prototype.save.call(this, attrs, options).then(function (model) { + return model._handleSaveResult(false).then(function () { + return model; + }); + }); + }, + + /** + * Follow a user + * @since 0.3.0 + * @param {AV.User | String} target The target user or user's objectId to follow. + * @param {AuthOptions} options + */ + follow: function follow(target, options) { + if (!this.id) { + throw new Error('Please signin.'); + } + if (!target) { + throw new Error('Invalid target user.'); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error('Invalid target user.'); + } + var route = 'users/' + this.id + '/friendship/' + userObjectId; + var request = AVRequest(route, null, null, 'POST', null, options); + return request; + }, + + /** + * Unfollow a user. + * @since 0.3.0 + * @param {AV.User | String} target The target user or user's objectId to unfollow. + * @param {AuthOptions} options + */ + unfollow: function unfollow(target, options) { + if (!this.id) { + throw new Error('Please signin.'); + } + if (!target) { + throw new Error('Invalid target user.'); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error('Invalid target user.'); + } + var route = 'users/' + this.id + '/friendship/' + userObjectId; + var request = AVRequest(route, null, null, 'DELETE', null, options); + return request; + }, + + /** + *Create a follower query to query the user's followers. + * @since 0.3.0 + * @see AV.User#followerQuery + */ + followerQuery: function followerQuery() { + return AV.User.followerQuery(this.id); + }, + + /** + *Create a followee query to query the user's followees. + * @since 0.3.0 + * @see AV.User#followeeQuery + */ + followeeQuery: function followeeQuery() { + return AV.User.followeeQuery(this.id); + }, + + /** + * @see AV.Object#fetch + */ + fetch: function fetch(fetchOptions, options) { + return AV.Object.prototype.fetch.call(this, fetchOptions, options).then(function (model) { + return model._handleSaveResult(false).then(function () { + return model; + }); + }); + }, + + /** + * Update user's new password safely based on old password. + * @param {String} oldPassword the old password. + * @param {String} newPassword the new password. + * @param {AuthOptions} options + */ + updatePassword: function updatePassword(oldPassword, newPassword, options) { + var route = 'users/' + this.id + '/updatePassword'; + var params = { + old_password: oldPassword, + new_password: newPassword + }; + var request = AVRequest(route, null, null, 'PUT', params, options); + return request; + }, + + /** + * Returns true if current would return this user. + * @see AV.User#current + */ + isCurrent: function isCurrent() { + return this._isCurrentUser; + }, + + /** + * Returns get("username"). + * @return {String} + * @see AV.Object#get + */ + getUsername: function getUsername() { + return this.get("username"); + }, + + /** + * Returns get("mobilePhoneNumber"). + * @return {String} + * @see AV.Object#get + */ + getMobilePhoneNumber: function getMobilePhoneNumber() { + return this.get("mobilePhoneNumber"); + }, + + /** + * Calls set("mobilePhoneNumber", phoneNumber, options) and returns the result. + * @param {String} mobilePhoneNumber + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setMobilePhoneNumber: function setMobilePhoneNumber(phone, options) { + return this.set("mobilePhoneNumber", phone, options); + }, + + /** + * Calls set("username", username, options) and returns the result. + * @param {String} username + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setUsername: function setUsername(username, options) { + return this.set("username", username, options); + }, + + /** + * Calls set("password", password, options) and returns the result. + * @param {String} password + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setPassword: function setPassword(password, options) { + return this.set("password", password, options); + }, + + /** + * Returns get("email"). + * @return {String} + * @see AV.Object#get + */ + getEmail: function getEmail() { + return this.get("email"); + }, + + /** + * Calls set("email", email, options) and returns the result. + * @param {String} email + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setEmail: function setEmail(email, options) { + return this.set("email", email, options); + }, + + /** + * Checks whether this user is the current user and has been authenticated. + * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(), + * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id + * @return (Boolean) whether this user is the current user and is logged in. + */ + authenticated: function authenticated() { + console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。'); + return !!this._sessionToken && !AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id; + }, + + /** + * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。 + * + * @since 2.0.0 + * @return Promise. + */ + isAuthenticated: function isAuthenticated() { + var _this4 = this; + + return Promise.resolve().then(function () { + return !!_this4._sessionToken && AV.User._fetchUserBySessionToken(_this4._sessionToken).then(function () { + return true; + }, function (error) { + if (error.code === 211) { + return false; + } + throw error; + }); + }); + }, + + + /** + * Get sessionToken of current user. + * @return {String} sessionToken + */ + getSessionToken: function getSessionToken() { + return this._sessionToken; + }, + + + /** + * Refresh sessionToken of current user. + * @since 2.1.0 + * @param {AuthOptions} [options] + * @return {Promise.} user with refreshed sessionToken + */ + refreshSessionToken: function refreshSessionToken(options) { + var _this5 = this; + + return AVRequest('users/' + this.id + '/refreshSessionToken', null, null, 'PUT', null, options).then(function (response) { + _this5._finishFetch(response); + return _this5._handleSaveResult(true).then(function () { + return _this5; + }); + }); + }, + + + /** + * Get this user's Roles. + * @param {AuthOptions} [options] + * @return {Promise} A promise that is fulfilled with the roles when + * the query is complete. + */ + getRoles: function getRoles(options) { + return AV.Relation.reverseQuery("_Role", "users", this).find(options); + } + }, /** @lends AV.User */{ + // Class Variables + + // The currently logged-in user. + _currentUser: null, + + // Whether currentUser is known to match the serialized version on disk. + // This is useful for saving a localstorage check if you try to load + // _currentUser frequently while there is none stored. + _currentUserMatchesDisk: false, + + // The localStorage key suffix that the current user is stored under. + _CURRENT_USER_KEY: "currentUser", + + // The mapping of auth provider names to actual providers + _authProviders: {}, + + // Class Methods + + /** + * Signs up a new user with a username (or email) and password. + * This will create a new AV.User on the server, and also persist the + * session in localStorage so that you can access the user using + * {@link #current}. + * + * @param {String} username The username (or email) to sign up with. + * @param {String} password The password to sign up with. + * @param {Object} attrs Extra fields to set on the new user. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the signup completes. + * @see AV.User#signUp + */ + signUp: function signUp(username, password, attrs, options) { + attrs = attrs || {}; + attrs.username = username; + attrs.password = password; + var user = AV.Object._create("_User"); + return user.signUp(attrs, options); + }, + + /** + * Logs in a user with a username (or email) and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} username The username (or email) to log in with. + * @param {String} password The password to log in with. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logIn: function logIn(username, password, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ username: username, password: password }); + return user.logIn(options); + }, + + /** + * Logs in a user with a session token. On success, this saves the session + * to disk, so you can retrieve the currently logged in user using + * current. + * + * @param {String} sessionToken The sessionToken to log in with. + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + become: function become(sessionToken) { + return this._fetchUserBySessionToken(sessionToken).then(function (user) { + return user._handleSaveResult(true).then(function () { + return user; + }); + }); + }, + + _fetchUserBySessionToken: function _fetchUserBySessionToken(sessionToken) { + var user = AV.Object._create("_User"); + return AVRequest("users", "me", null, "GET", { + session_token: sessionToken + }).then(function (resp) { + var serverAttrs = user.parse(resp); + user._finishFetch(serverAttrs); + return user; + }); + }, + + /** + * Logs in a user with a mobile phone number and sms code sent by + * AV.User.requestLoginSmsCode.On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} mobilePhone The user's mobilePhoneNumber + * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logInWithMobilePhoneSmsCode: function logInWithMobilePhoneSmsCode(mobilePhone, smsCode, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode }); + return user.logIn(options); + }, + + /** + * Sign up or logs in a user with a mobilePhoneNumber and smsCode. + * On success, this saves the session to disk, so you can retrieve the currently + * logged in user using current. + * + * @param {String} mobilePhoneNumber The user's mobilePhoneNumber. + * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode + * @param {Object} attributes The user's other attributes such as username etc. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#signUpOrlogInWithMobilePhone + * @see AV.Cloud.requestSmsCode + */ + signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(mobilePhoneNumber, smsCode, attrs, options) { + attrs = attrs || {}; + attrs.mobilePhoneNumber = mobilePhoneNumber; + attrs.smsCode = smsCode; + var user = AV.Object._create("_User"); + return user.signUpOrlogInWithMobilePhone(attrs, options); + }, + + /** + * Logs in a user with a mobile phone number and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} mobilePhone The user's mobilePhoneNumber + * @param {String} password The password to log in with. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logInWithMobilePhone: function logInWithMobilePhone(mobilePhone, password, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password }); + return user.logIn(options); + }, + + /** + * Sign up or logs in a user with a third party auth data(AccessToken). + * On success, this saves the session to disk, so you can retrieve the currently + * logged in user using current. + * + * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 } + * @param {string} platform Available platform for sign up. + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) { + * //Access user here + * }).catch(function(error) { + * //console.error("error: ", error); + * }); + * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户} + */ + signUpOrlogInWithAuthData: function signUpOrlogInWithAuthData(authData, platform) { + return AV.User._logInWith(platform, authData); + }, + + + /** + * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。 + * 仅在小程序中可用。 + * + * @since 2.0.0 + * @return {AV.User} + */ + loginWithWeapp: function loginWithWeapp() { + var _this6 = this; + + return getWeappLoginCode().then(function (code) { + return _this6.signUpOrlogInWithAuthData({ code: code }, 'lc_weapp'); + }); + }, + + + /** + * Associate a user with a third party auth data(AccessToken). + * + * @param {AV.User} userObj A user which you want to associate. + * @param {string} platform Available platform for sign up. + * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 } + * @return {Promise} A promise that is fulfilled with the user when completed. + * @example AV.User.associateWithAuthData(loginUser, 'weixin', { + * openid: 'abc123', + * access_token: '123abc', + * expires_in: 1382686496 + * }).then(function(user) { + * //Access user here + * }).catch(function(error) { + * //console.error("error: ", error); + * }); + */ + associateWithAuthData: function associateWithAuthData(userObj, platform, authData) { + return userObj._linkWith(platform, authData); + }, + + /** + * Logs out the currently logged in user session. This will remove the + * session from disk, log out of linked services, and future calls to + * current will return null. + * @return {Promise} + */ + logOut: function logOut() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return Promise.resolve(null); + } + + if (AV.User._currentUser !== null) { + AV.User._currentUser._logOutWithAll(); + AV.User._currentUser._isCurrentUser = false; + } + AV.User._currentUserMatchesDisk = true; + AV.User._currentUser = null; + return AV.localStorage.removeItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)); + }, + + /** + *Create a follower query for special user to query the user's followers. + * @param {String} userObjectId The user object id. + * @return {AV.FriendShipQuery} + * @since 0.3.0 + */ + followerQuery: function followerQuery(userObjectId) { + if (!userObjectId || !_.isString(userObjectId)) { + throw new Error('Invalid user object id.'); + } + var query = new AV.FriendShipQuery('_Follower'); + query._friendshipTag = 'follower'; + query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId)); + return query; + }, + + /** + *Create a followee query for special user to query the user's followees. + * @param {String} userObjectId The user object id. + * @return {AV.FriendShipQuery} + * @since 0.3.0 + */ + followeeQuery: function followeeQuery(userObjectId) { + if (!userObjectId || !_.isString(userObjectId)) { + throw new Error('Invalid user object id.'); + } + var query = new AV.FriendShipQuery('_Followee'); + query._friendshipTag = 'followee'; + query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId)); + return query; + }, + + /** + * Requests a password reset email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * reset their password on the AV site. + * + * @param {String} email The email address associated with the user that + * forgot their password. + * @return {Promise} + */ + requestPasswordReset: function requestPasswordReset(email) { + var json = { email: email }; + var request = AVRequest("requestPasswordReset", null, null, "POST", json); + return request; + }, + + /** + * Requests a verify email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * verify their email address on the AV site. + * + * @param {String} email The email address associated with the user that + * doesn't verify their email address. + * @return {Promise} + */ + requestEmailVerify: function requestEmailVerify(email) { + var json = { email: email }; + var request = AVRequest("requestEmailVerify", null, null, "POST", json); + return request; + }, + + /** + * Requests a verify sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * verify their mobile phone number by calling AV.User.verifyMobilePhone + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that doesn't verify their mobile phone number. + * @return {Promise} + */ + requestMobilePhoneVerify: function requestMobilePhoneVerify(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestMobilePhoneVerify", null, null, "POST", json); + return request; + }, + + /** + * Requests a reset password sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * reset their account's password by calling AV.User.resetPasswordBySmsCode + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that doesn't verify their mobile phone number. + * @return {Promise} + */ + requestPasswordResetBySmsCode: function requestPasswordResetBySmsCode(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestPasswordResetBySmsCode", null, null, "POST", json); + return request; + }, + + /** + * Makes a call to reset user's account password by sms code and new password. + * The sms code is sent by AV.User.requestPasswordResetBySmsCode. + * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode + * @param {String} password The new password. + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + resetPasswordBySmsCode: function resetPasswordBySmsCode(code, password) { + var json = { password: password }; + var request = AVRequest("resetPasswordBySmsCode", null, code, "PUT", json); + return request; + }, + + /** + * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode + * If verify successfully,the user mobilePhoneVerified attribute will be true. + * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + verifyMobilePhone: function verifyMobilePhone(code) { + var request = AVRequest("verifyMobilePhone", null, code, "POST", null); + return request; + }, + + /** + * Requests a logIn sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * login by AV.User.logInWithMobilePhoneSmsCode function. + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that want to login by AV.User.logInWithMobilePhoneSmsCode + * @return {Promise} + */ + requestLoginSmsCode: function requestLoginSmsCode(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestLoginSmsCode", null, null, "POST", json); + return request; + }, + + /** + * Retrieves the currently logged in AVUser with a valid session, + * either from memory or localStorage, if necessary. + * @return {Promise.} resolved with the currently logged in AV.User. + */ + currentAsync: function currentAsync() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return Promise.resolve(null); + } + + if (AV.User._currentUser) { + return Promise.resolve(AV.User._currentUser); + } + + if (AV.User._currentUserMatchesDisk) { + + return Promise.resolve(AV.User._currentUser); + } + + return AV.localStorage.getItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)).then(function (userData) { + if (!userData) { + return null; + } + + // Load the user from local storage. + AV.User._currentUserMatchesDisk = true; + + AV.User._currentUser = AV.Object._create("_User"); + AV.User._currentUser._isCurrentUser = true; + + var json = JSON.parse(userData); + AV.User._currentUser.id = json._id; + delete json._id; + AV.User._currentUser._sessionToken = json._sessionToken; + delete json._sessionToken; + AV.User._currentUser._finishFetch(json); + //AV.User._currentUser.set(json); + + AV.User._currentUser._synchronizeAllAuthData(); + AV.User._currentUser._refreshCache(); + AV.User._currentUser._opSetQueue = [{}]; + return AV.User._currentUser; + }); + }, + + /** + * Retrieves the currently logged in AVUser with a valid session, + * either from memory or localStorage, if necessary. + * @return {AV.User} The currently logged in AV.User. + */ + current: function current() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return null; + } + + if (AV.User._currentUser) { + return AV.User._currentUser; + } + + if (AV.User._currentUserMatchesDisk) { + + return AV.User._currentUser; + } + + // Load the user from local storage. + AV.User._currentUserMatchesDisk = true; + + var userData = AV.localStorage.getItem(AV._getAVPath(AV.User._CURRENT_USER_KEY)); + if (!userData) { + + return null; + } + AV.User._currentUser = AV.Object._create("_User"); + AV.User._currentUser._isCurrentUser = true; + + var json = JSON.parse(userData); + AV.User._currentUser.id = json._id; + delete json._id; + AV.User._currentUser._sessionToken = json._sessionToken; + delete json._sessionToken; + AV.User._currentUser._finishFetch(json); + //AV.User._currentUser.set(json); + + AV.User._currentUser._synchronizeAllAuthData(); + AV.User._currentUser._refreshCache(); + AV.User._currentUser._opSetQueue = [{}]; + return AV.User._currentUser; + }, + + /** + * Persists a user as currentUser to localStorage, and into the singleton. + * @private + */ + _saveCurrentUser: function _saveCurrentUser(user) { + var promise; + if (AV.User._currentUser !== user) { + promise = AV.User.logOut(); + } else { + promise = Promise.resolve(); + } + return promise.then(function () { + user._isCurrentUser = true; + AV.User._currentUser = user; + + var json = user.toJSON(); + json._id = user.id; + json._sessionToken = user._sessionToken; + return AV.localStorage.setItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY), JSON.stringify(json)).then(function () { + AV.User._currentUserMatchesDisk = true; + }); + }); + }, + + _registerAuthenticationProvider: function _registerAuthenticationProvider(provider) { + AV.User._authProviders[provider.getAuthType()] = provider; + // Synchronize the current user with the auth provider. + if (!AV._config.disableCurrentUser && AV.User.current()) { + AV.User.current()._synchronizeAuthData(provider.getAuthType()); + } + }, + + _logInWith: function _logInWith(provider, options) { + var user = AV.Object._create("_User"); + return user._linkWith(provider, options); + } + + }); +}; + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(1); + +// interface Storage { +// readonly attribute boolean async; +// string getItem(string key); +// void setItem(string key, string value); +// void removeItem(string key); +// void clear(); +// Promise getItemAsync(string key); +// Promise setItemAsync(string key, string value); +// Promise removeItemAsync(string key); +// Promise clearAsync(); +// } +var Storage = {}; +var apiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +var localStorage = global.localStorage; + +try { + var testKey = '__storejs__'; + localStorage.setItem(testKey, testKey); + if (localStorage.getItem(testKey) != testKey) { + throw new Error(); + } + localStorage.removeItem(testKey); +} catch (e) { + localStorage = __webpack_require__(56); +} + +// in browser, `localStorage.async = false` will excute `localStorage.setItem('async', false)` +_(apiNames).each(function (apiName) { + Storage[apiName] = function () { + return global.localStorage[apiName].apply(global.localStorage, arguments); + }; +}); +Storage.async = false; + +module.exports = Storage; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var dataURItoBlob = function dataURItoBlob(dataURI, type) { + var byteString; + + // 传入的 base64,不是 dataURL + if (dataURI.indexOf('base64') < 0) { + byteString = atob(dataURI); + } else if (dataURI.split(',')[0].indexOf('base64') >= 0) { + type = type || dataURI.split(',')[0].split(':')[1].split(';')[0]; + byteString = atob(dataURI.split(',')[1]); + } else { + byteString = unescape(dataURI.split(',')[1]); + } + var ia = new Uint8Array(byteString.length); + for (var i = 0; i < byteString.length; i++) { + ia[i] = byteString.charCodeAt(i); + } + return new Blob([ia], { type: type }); +}; + +module.exports = dataURItoBlob; + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + + +/***/ }), +/* 50 */ +/***/ (function(module, exports) { + +(function() { + var base64map + = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', + + crypt = { + // Bit-wise rotation left + rotl: function(n, b) { + return (n << b) | (n >>> (32 - b)); + }, + + // Bit-wise rotation right + rotr: function(n, b) { + return (n << (32 - b)) | (n >>> b); + }, + + // Swap big-endian to little-endian and vice versa + endian: function(n) { + // If number given, swap endian + if (n.constructor == Number) { + return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; + } + + // Else, assume array and swap all items + for (var i = 0; i < n.length; i++) + n[i] = crypt.endian(n[i]); + return n; + }, + + // Generate an array of any length of random bytes + randomBytes: function(n) { + for (var bytes = []; n > 0; n--) + bytes.push(Math.floor(Math.random() * 256)); + return bytes; + }, + + // Convert a byte array to big-endian 32-bit words + bytesToWords: function(bytes) { + for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) + words[b >>> 5] |= bytes[i] << (24 - b % 32); + return words; + }, + + // Convert big-endian 32-bit words to a byte array + wordsToBytes: function(words) { + for (var bytes = [], b = 0; b < words.length * 32; b += 8) + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); + return bytes; + }, + + // Convert a byte array to a hex string + bytesToHex: function(bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + } + return hex.join(''); + }, + + // Convert a hex string to a byte array + hexToBytes: function(hex) { + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.substr(c, 2), 16)); + return bytes; + }, + + // Convert a byte array to a base-64 string + bytesToBase64: function(bytes) { + for (var base64 = [], i = 0; i < bytes.length; i += 3) { + var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + for (var j = 0; j < 4; j++) + if (i * 8 + j * 6 <= bytes.length * 8) + base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); + else + base64.push('='); + } + return base64.join(''); + }, + + // Convert a base-64 string to a byte array + base64ToBytes: function(base64) { + // Remove non-base-64 characters + base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); + + for (var bytes = [], i = 0, imod4 = 0; i < base64.length; + imod4 = ++i % 4) { + if (imod4 == 0) continue; + bytes.push(((base64map.indexOf(base64.charAt(i - 1)) + & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) + | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); + } + return bytes; + } + }; + + module.exports = crypt; +})(); + + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __webpack_require__(58); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (namespaces || '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var require;/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version 4.1.0 + */ + +(function (global, factory) { + true ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; +} + +function isFunction(x) { + return typeof x === 'function'; +} + +var _isArray = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +var isArray = _isArray; + +var len = 0; +var vertxNext = undefined; +var customSchedulerFn = undefined; + +var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +}; + +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = typeof window !== 'undefined' ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + + return useSetTimeout(); +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + node.data = iterations = ++iterations % 2; + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } + + len = 0; +} + +function attemptVertx() { + try { + var r = require; + var vertx = __webpack_require__(64); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} + +var scheduleFlush = undefined; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && "function" === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} + +function then(onFulfillment, onRejection) { + var _arguments = arguments; + + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var _state = parent._state; + + if (_state) { + (function () { + var callback = _arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; +} + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} + +var PROMISE_ID = Math.random().toString(36).substring(16); + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + _resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + _reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return _resolve(promise, value); + }, function (reason) { + return _reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then$$) { + if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$ === GET_THEN_ERROR) { + _reject(promise, GET_THEN_ERROR.error); + GET_THEN_ERROR.error = null; + } else if (then$$ === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$)) { + handleForeignThenable(promise, maybeThenable, then$$); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + + parent._onerror = null; + + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { + return; + } + + var child = undefined, + callback = undefined, + detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value.error = null; + } else { + succeeded = true; + } + + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + _resolve(promise, value); + } else if (failed) { + _reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + _reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + _resolve(promise, value); + }, function rejectPromise(reason) { + _reject(promise, reason); + }); + } catch (e) { + _reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + _reject(this.promise, validationError()); + } +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._enumerate = function () { + var length = this.length; + var _input = this._input; + + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(_input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + + if (resolve$$ === resolve) { + var _then = getThen(entry); + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$) { + return resolve$$(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$(entry), i); + } +}; + +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; + +Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); +}; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +function all(entries) { + return new Enumerator(this, entries).promise; +} + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = resolve; +Promise.reject = reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; + +Promise.prototype = { + constructor: Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + let result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + let author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: then, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function _catch(onRejection) { + return this.then(null, onRejection); + } +}; + +function polyfill() { + var local = undefined; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } + + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + + local.Promise = Promise; +} + +// Strange compat.. +Promise.polyfill = polyfill; +Promise.Promise = Promise; + +return Promise; + +}))); +//# sourceMappingURL=es6-promise.map + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ + + + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +var Commons = __webpack_require__(10); +var LISTENERS = Commons.LISTENERS; +var ATTRIBUTE = Commons.ATTRIBUTE; +var newNode = Commons.newNode; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Gets a specified attribute listener from a given EventTarget object. + * + * @param {EventTarget} eventTarget - An EventTarget object to get. + * @param {string} type - An event type to get. + * @returns {function|null} The found attribute listener. + */ +function getAttributeListener(eventTarget, type) { + var node = eventTarget[LISTENERS][type]; + while (node != null) { + if (node.kind === ATTRIBUTE) { + return node.listener; + } + node = node.next; + } + return null; +} + +/** + * Sets a specified attribute listener to a given EventTarget object. + * + * @param {EventTarget} eventTarget - An EventTarget object to set. + * @param {string} type - An event type to set. + * @param {function|null} listener - A listener to be set. + * @returns {void} + */ +function setAttributeListener(eventTarget, type, listener) { + if (typeof listener !== "function" && typeof listener !== "object") { + listener = null; // eslint-disable-line no-param-reassign + } + + var prev = null; + var node = eventTarget[LISTENERS][type]; + while (node != null) { + if (node.kind === ATTRIBUTE) { + // Remove old value. + if (prev == null) { + eventTarget[LISTENERS][type] = node.next; + } + else { + prev.next = node.next; + } + } + else { + prev = node; + } + + node = node.next; + } + + // Add new value. + if (listener != null) { + if (prev == null) { + eventTarget[LISTENERS][type] = newNode(listener, ATTRIBUTE); + } + else { + prev.next = newNode(listener, ATTRIBUTE); + } + } +} + +//----------------------------------------------------------------------------- +// Public Interface +//----------------------------------------------------------------------------- + +/** + * Defines an `EventTarget` implementation which has `onfoobar` attributes. + * + * @param {EventTarget} EventTargetBase - A base implementation of EventTarget. + * @param {string[]} types - A list of event types which are defined as attribute listeners. + * @returns {EventTarget} The defined `EventTarget` implementation which has attribute listeners. + */ +exports.defineCustomEventTarget = function(EventTargetBase, types) { + function EventTarget() { + EventTargetBase.call(this); + } + + var descripter = { + constructor: { + value: EventTarget, + configurable: true, + writable: true + } + }; + + types.forEach(function(type) { + descripter["on" + type] = { + get: function() { return getAttributeListener(this, type); }, + set: function(listener) { setAttributeListener(this, type, listener); }, + configurable: true, + enumerable: true + }; + }); + + EventTarget.prototype = Object.create(EventTargetBase.prototype, descripter); + + return EventTarget; +}; + + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ + + + +//----------------------------------------------------------------------------- +// Requirements +//----------------------------------------------------------------------------- + +var createUniqueKey = __webpack_require__(10).createUniqueKey; + +//----------------------------------------------------------------------------- +// Constsnts +//----------------------------------------------------------------------------- + +/** + * The key of the flag which is turned on by `stopImmediatePropagation` method. + * + * @type {symbol|string} + * @private + */ +var STOP_IMMEDIATE_PROPAGATION_FLAG = + createUniqueKey("stop_immediate_propagation_flag"); + +/** + * The key of the flag which is turned on by `preventDefault` method. + * + * @type {symbol|string} + * @private + */ +var CANCELED_FLAG = createUniqueKey("canceled_flag"); + +/** + * The key of the original event object. + * + * @type {symbol|string} + * @private + */ +var ORIGINAL_EVENT = createUniqueKey("original_event"); + +/** + * Method definitions for the event wrapper. + * + * @type {object} + * @private + */ +var wrapperPrototypeDefinition = Object.freeze({ + stopPropagation: Object.freeze({ + value: function stopPropagation() { + var e = this[ORIGINAL_EVENT]; + if (typeof e.stopPropagation === "function") { + e.stopPropagation(); + } + }, + writable: true, + configurable: true + }), + + stopImmediatePropagation: Object.freeze({ + value: function stopImmediatePropagation() { + this[STOP_IMMEDIATE_PROPAGATION_FLAG] = true; + + var e = this[ORIGINAL_EVENT]; + if (typeof e.stopImmediatePropagation === "function") { + e.stopImmediatePropagation(); + } + }, + writable: true, + configurable: true + }), + + preventDefault: Object.freeze({ + value: function preventDefault() { + if (this.cancelable === true) { + this[CANCELED_FLAG] = true; + } + + var e = this[ORIGINAL_EVENT]; + if (typeof e.preventDefault === "function") { + e.preventDefault(); + } + }, + writable: true, + configurable: true + }), + + defaultPrevented: Object.freeze({ + get: function defaultPrevented() { return this[CANCELED_FLAG]; }, + enumerable: true, + configurable: true + }) +}); + +//----------------------------------------------------------------------------- +// Public Interface +//----------------------------------------------------------------------------- + +exports.STOP_IMMEDIATE_PROPAGATION_FLAG = STOP_IMMEDIATE_PROPAGATION_FLAG; + +/** + * Creates an event wrapper. + * + * We cannot modify several properties of `Event` object, so we need to create the wrapper. + * Plus, this wrapper supports non `Event` objects. + * + * @param {Event|{type: string}} event - An original event to create the wrapper. + * @param {EventTarget} eventTarget - The event target of the event. + * @returns {Event} The created wrapper. This object is implemented `Event` interface. + * @private + */ +exports.createEventWrapper = function createEventWrapper(event, eventTarget) { + var timeStamp = ( + typeof event.timeStamp === "number" ? event.timeStamp : Date.now() + ); + var propertyDefinition = { + type: {value: event.type, enumerable: true}, + target: {value: eventTarget, enumerable: true}, + currentTarget: {value: eventTarget, enumerable: true}, + eventPhase: {value: 2, enumerable: true}, + bubbles: {value: Boolean(event.bubbles), enumerable: true}, + cancelable: {value: Boolean(event.cancelable), enumerable: true}, + timeStamp: {value: timeStamp, enumerable: true}, + isTrusted: {value: false, enumerable: true} + }; + propertyDefinition[STOP_IMMEDIATE_PROPAGATION_FLAG] = {value: false, writable: true}; + propertyDefinition[CANCELED_FLAG] = {value: false, writable: true}; + propertyDefinition[ORIGINAL_EVENT] = {value: event}; + + // For CustomEvent. + if (typeof event.detail !== "undefined") { + propertyDefinition.detail = {value: event.detail, enumerable: true}; + } + + return Object.create( + Object.create(event, wrapperPrototypeDefinition), + propertyDefinition + ); +}; + + +/***/ }), +/* 55 */ +/***/ (function(module, exports) { + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +(function(root) { + var localStorageMemory = {}; + var cache = {}; + + /** + * number of stored items. + */ + localStorageMemory.length = 0; + + /** + * returns item for passed key, or null + * + * @para {String} key + * name of item to be returned + * @returns {String|null} + */ + localStorageMemory.getItem = function(key) { + return cache[key] || null; + }; + + /** + * sets item for key to passed value, as String + * + * @para {String} key + * name of item to be set + * @para {String} value + * value, will always be turned into a String + * @returns {undefined} + */ + localStorageMemory.setItem = function(key, value) { + if (typeof value === 'undefined') { + localStorageMemory.removeItem(key); + } else { + if (!(cache.hasOwnProperty(key))) { + localStorageMemory.length++; + } + + cache[key] = '' + value; + } + }; + + /** + * removes item for passed key + * + * @para {String} key + * name of item to be removed + * @returns {undefined} + */ + localStorageMemory.removeItem = function(key) { + if (cache.hasOwnProperty(key)) { + delete cache[key]; + localStorageMemory.length--; + } + }; + + /** + * returns name of key at passed index + * + * @para {Number} index + * Position for key to be returned (starts at 0) + * @returns {String|null} + */ + localStorageMemory.key = function(index) { + return Object.keys(cache)[index] || null; + }; + + /** + * removes all stored items and sets length to 0 + * + * @returns {undefined} + */ + localStorageMemory.clear = function() { + cache = {}; + localStorageMemory.length = 0; + }; + + if (true) { + module.exports = localStorageMemory; + } else { + root.localStorageMemory = localStorageMemory; + } +})(this); + + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + +(function(){ + var crypt = __webpack_require__(50), + utf8 = __webpack_require__(19).utf8, + isBuffer = __webpack_require__(55), + bin = __webpack_require__(19).bin, + + // The core + md5 = function (message, options) { + // Convert to byte array + if (message.constructor == String) + if (options && options.encoding === 'binary') + message = bin.stringToBytes(message); + else + message = utf8.stringToBytes(message); + else if (isBuffer(message)) + message = Array.prototype.slice.call(message, 0); + else if (!Array.isArray(message)) + message = message.toString(); + // else, assume byte array already + + var m = crypt.bytesToWords(message), + l = message.length * 8, + a = 1732584193, + b = -271733879, + c = -1732584194, + d = 271733878; + + // Swap endian + for (var i = 0; i < m.length; i++) { + m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF | + ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00; + } + + // Padding + m[l >>> 5] |= 0x80 << (l % 32); + m[(((l + 64) >>> 9) << 4) + 14] = l; + + // Method shortcuts + var FF = md5._ff, + GG = md5._gg, + HH = md5._hh, + II = md5._ii; + + for (var i = 0; i < m.length; i += 16) { + + var aa = a, + bb = b, + cc = c, + dd = d; + + a = FF(a, b, c, d, m[i+ 0], 7, -680876936); + d = FF(d, a, b, c, m[i+ 1], 12, -389564586); + c = FF(c, d, a, b, m[i+ 2], 17, 606105819); + b = FF(b, c, d, a, m[i+ 3], 22, -1044525330); + a = FF(a, b, c, d, m[i+ 4], 7, -176418897); + d = FF(d, a, b, c, m[i+ 5], 12, 1200080426); + c = FF(c, d, a, b, m[i+ 6], 17, -1473231341); + b = FF(b, c, d, a, m[i+ 7], 22, -45705983); + a = FF(a, b, c, d, m[i+ 8], 7, 1770035416); + d = FF(d, a, b, c, m[i+ 9], 12, -1958414417); + c = FF(c, d, a, b, m[i+10], 17, -42063); + b = FF(b, c, d, a, m[i+11], 22, -1990404162); + a = FF(a, b, c, d, m[i+12], 7, 1804603682); + d = FF(d, a, b, c, m[i+13], 12, -40341101); + c = FF(c, d, a, b, m[i+14], 17, -1502002290); + b = FF(b, c, d, a, m[i+15], 22, 1236535329); + + a = GG(a, b, c, d, m[i+ 1], 5, -165796510); + d = GG(d, a, b, c, m[i+ 6], 9, -1069501632); + c = GG(c, d, a, b, m[i+11], 14, 643717713); + b = GG(b, c, d, a, m[i+ 0], 20, -373897302); + a = GG(a, b, c, d, m[i+ 5], 5, -701558691); + d = GG(d, a, b, c, m[i+10], 9, 38016083); + c = GG(c, d, a, b, m[i+15], 14, -660478335); + b = GG(b, c, d, a, m[i+ 4], 20, -405537848); + a = GG(a, b, c, d, m[i+ 9], 5, 568446438); + d = GG(d, a, b, c, m[i+14], 9, -1019803690); + c = GG(c, d, a, b, m[i+ 3], 14, -187363961); + b = GG(b, c, d, a, m[i+ 8], 20, 1163531501); + a = GG(a, b, c, d, m[i+13], 5, -1444681467); + d = GG(d, a, b, c, m[i+ 2], 9, -51403784); + c = GG(c, d, a, b, m[i+ 7], 14, 1735328473); + b = GG(b, c, d, a, m[i+12], 20, -1926607734); + + a = HH(a, b, c, d, m[i+ 5], 4, -378558); + d = HH(d, a, b, c, m[i+ 8], 11, -2022574463); + c = HH(c, d, a, b, m[i+11], 16, 1839030562); + b = HH(b, c, d, a, m[i+14], 23, -35309556); + a = HH(a, b, c, d, m[i+ 1], 4, -1530992060); + d = HH(d, a, b, c, m[i+ 4], 11, 1272893353); + c = HH(c, d, a, b, m[i+ 7], 16, -155497632); + b = HH(b, c, d, a, m[i+10], 23, -1094730640); + a = HH(a, b, c, d, m[i+13], 4, 681279174); + d = HH(d, a, b, c, m[i+ 0], 11, -358537222); + c = HH(c, d, a, b, m[i+ 3], 16, -722521979); + b = HH(b, c, d, a, m[i+ 6], 23, 76029189); + a = HH(a, b, c, d, m[i+ 9], 4, -640364487); + d = HH(d, a, b, c, m[i+12], 11, -421815835); + c = HH(c, d, a, b, m[i+15], 16, 530742520); + b = HH(b, c, d, a, m[i+ 2], 23, -995338651); + + a = II(a, b, c, d, m[i+ 0], 6, -198630844); + d = II(d, a, b, c, m[i+ 7], 10, 1126891415); + c = II(c, d, a, b, m[i+14], 15, -1416354905); + b = II(b, c, d, a, m[i+ 5], 21, -57434055); + a = II(a, b, c, d, m[i+12], 6, 1700485571); + d = II(d, a, b, c, m[i+ 3], 10, -1894986606); + c = II(c, d, a, b, m[i+10], 15, -1051523); + b = II(b, c, d, a, m[i+ 1], 21, -2054922799); + a = II(a, b, c, d, m[i+ 8], 6, 1873313359); + d = II(d, a, b, c, m[i+15], 10, -30611744); + c = II(c, d, a, b, m[i+ 6], 15, -1560198380); + b = II(b, c, d, a, m[i+13], 21, 1309151649); + a = II(a, b, c, d, m[i+ 4], 6, -145523070); + d = II(d, a, b, c, m[i+11], 10, -1120210379); + c = II(c, d, a, b, m[i+ 2], 15, 718787259); + b = II(b, c, d, a, m[i+ 9], 21, -343485551); + + a = (a + aa) >>> 0; + b = (b + bb) >>> 0; + c = (c + cc) >>> 0; + d = (d + dd) >>> 0; + } + + return crypt.endian([a, b, c, d]); + }; + + // Auxiliary functions + md5._ff = function (a, b, c, d, x, s, t) { + var n = a + (b & c | ~b & d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._gg = function (a, b, c, d, x, s, t) { + var n = a + (b & d | c & ~d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._hh = function (a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._ii = function (a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + + // Package private blocksize + md5._blocksize = 16; + md5._digestsize = 16; + + module.exports = function (message, options) { + if (message === undefined || message === null) + throw new Error('Illegal argument ' + message); + + var digestbytes = crypt.wordsToBytes(md5(message, options)); + return options && options.asBytes ? digestbytes : + options && options.asString ? bin.bytesToString(digestbytes) : + crypt.bytesToHex(digestbytes); + }; + +})(); + + +/***/ }), +/* 58 */ +/***/ (function(module, exports) { + +/** + * Helpers. + */ + +var s = 1000 +var m = s * 60 +var h = m * 60 +var d = h * 24 +var y = d * 365.25 + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {} + var type = typeof val + if (type === 'string' && val.length > 0) { + return parse(val) + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? + fmtLong(val) : + fmtShort(val) + } + throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) +} + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str) + if (str.length > 10000) { + return + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) + if (!match) { + return + } + var n = parseFloat(match[1]) + var type = (match[2] || 'ms').toLowerCase() + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y + case 'days': + case 'day': + case 'd': + return n * d + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n + default: + return undefined + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd' + } + if (ms >= h) { + return Math.round(ms / h) + 'h' + } + if (ms >= m) { + return Math.round(ms / m) + 'm' + } + if (ms >= s) { + return Math.round(ms / s) + 's' + } + return ms + 'ms' +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms' +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name + } + return Math.ceil(ms / n) + ' ' + name + 's' +} + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Check if `fn` is a function. + * + * @param {Function} fn + * @return {Boolean} + * @api private + */ +var isObject = __webpack_require__(11); + +function isFunction(fn) { + var tag = isObject(fn) ? Object.prototype.toString.call(fn) : ''; + return tag === '[object Function]'; +} + +module.exports = isFunction; + + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Module of mixed-in functions shared between node and client code + */ +var isObject = __webpack_require__(11); + +/** + * Expose `RequestBase`. + */ + +module.exports = RequestBase; + +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in RequestBase.prototype) { + obj[key] = RequestBase.prototype[key]; + } + return obj; +} + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.clearTimeout = function _clearTimeout(){ + clearTimeout(this._timer); + clearTimeout(this._responseTimeoutTimer); + delete this._timer; + delete this._responseTimeoutTimer; + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.parse = function parse(fn){ + this._parser = fn; + return this; +}; + +/** + * Set format of binary response body. + * In browser valid formats are 'blob' and 'arraybuffer', + * which return Blob and ArrayBuffer, respectively. + * + * In Node all values result in Buffer. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.responseType = function(val){ + this._responseType = val; + return this; +}; + +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.serialize = function serialize(fn){ + this._serializer = fn; + return this; +}; + +/** + * Set timeouts. + * + * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. + * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. + * + * Value of 0 or false means no timeout. + * + * @param {Number|Object} ms or {response, read, deadline} + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.timeout = function timeout(options){ + if (!options || 'object' !== typeof options) { + this._timeout = options; + this._responseTimeout = 0; + return this; + } + + for(var option in options) { + switch(option) { + case 'deadline': + this._timeout = options.deadline; + break; + case 'response': + this._responseTimeout = options.response; + break; + default: + console.warn("Unknown timeout option", option); + } + } + return this; +}; + +/** + * Set number of retry attempts on error. + * + * Failed requests will be retried 'count' times if timeout or err.code >= 500. + * + * @param {Number} count + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.retry = function retry(count){ + // Default to 1 if no count passed or true + if (arguments.length === 0 || count === true) count = 1; + if (count <= 0) count = 0; + this._maxRetries = count; + this._retries = 0; + return this; +}; + +/** + * Retry request + * + * @return {Request} for chaining + * @api private + */ + +RequestBase.prototype._retry = function() { + this.clearTimeout(); + + // node + if (this.req) { + this.req = null; + this.req = this.request(); + } + + this._aborted = false; + this.timedout = false; + + return this._end(); +}; + +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} [reject] + * @return {Request} + */ + +RequestBase.prototype.then = function then(resolve, reject) { + if (!this._fullfilledPromise) { + var self = this; + if (this._endCalled) { + console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"); + } + this._fullfilledPromise = new Promise(function(innerResolve, innerReject){ + self.end(function(err, res){ + if (err) innerReject(err); else innerResolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +} + +RequestBase.prototype.catch = function(cb) { + return this.then(undefined, cb); +}; + +/** + * Allow for extension + */ + +RequestBase.prototype.use = function use(fn) { + fn(this); + return this; +} + +RequestBase.prototype.ok = function(cb) { + if ('function' !== typeof cb) throw Error("Callback required"); + this._okCallback = cb; + return this; +}; + +RequestBase.prototype._isResponseOK = function(res) { + if (!res) { + return false; + } + + if (this._okCallback) { + return this._okCallback(res); + } + + return res.status >= 200 && res.status < 300; +}; + + +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + +RequestBase.prototype.get = function(field){ + return this._header[field.toLowerCase()]; +}; + +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + +RequestBase.prototype.getHeader = RequestBase.prototype.get; + +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function(field, val){ + if (isObject(field)) { + for (var key in field) { + this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; + +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + */ +RequestBase.prototype.unset = function(field){ + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; + +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name + * @param {String|Blob|File|Buffer|fs.ReadStream} val + * @return {Request} for chaining + * @api public + */ +RequestBase.prototype.field = function(name, val) { + + // name should be either a string or an object. + if (null === name || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + + if (this._data) { + console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObject(name)) { + for (var key in name) { + this.field(key, name[key]); + } + return this; + } + + if (Array.isArray(val)) { + for (var i in val) { + this.field(name, val[i]); + } + return this; + } + + // val should be defined now + if (null === val || undefined === val) { + throw new Error('.field(name, val) val can not be empty'); + } + if ('boolean' === typeof val) { + val = '' + val; + } + this._getFormData().append(name, val); + return this; +}; + +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */ +RequestBase.prototype.abort = function(){ + if (this._aborted) { + return this; + } + this._aborted = true; + this.xhr && this.xhr.abort(); // browser + this.req && this.req.abort(); // node + this.clearTimeout(); + this.emit('abort'); + return this; +}; + +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ + +RequestBase.prototype.withCredentials = function(on){ + // This is browser-only functionality. Node side is no-op. + if(on==undefined) on = true; + this._withCredentials = on; + return this; +}; + +/** + * Set the max redirects to `n`. Does noting in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.redirects = function(n){ + this._maxRedirects = n; + return this; +}; + +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + +RequestBase.prototype.toJSON = function(){ + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; + + +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.send = function(data){ + var isObj = isObject(data); + var type = this._header['content-type']; + + if (this._formData) { + console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObj && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw Error("Can't merge these send calls"); + } + + // merge + if (isObj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + + if (!isObj || this._isHost(data)) { + return this; + } + + // default to json + if (!type) this.type('json'); + return this; +}; + + +/** + * Sort `querystring` by the sort function + * + * + * Examples: + * + * // default order + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery() + * .end(callback) + * + * // customized sort function + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery(function(a, b){ + * return a.length - b.length; + * }) + * .end(callback) + * + * + * @param {Function} sort + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.sortQuery = function(sort) { + // _sort default to true but otherwise can be a function or boolean + this._sort = typeof sort === 'undefined' ? true : sort; + return this; +}; + +/** + * Invoke callback with timeout error. + * + * @api private + */ + +RequestBase.prototype._timeoutError = function(reason, timeout, errno){ + if (this._aborted) { + return; + } + var err = new Error(reason + timeout + 'ms exceeded'); + err.timeout = timeout; + err.code = 'ECONNABORTED'; + err.errno = errno; + this.timedout = true; + this.abort(); + this.callback(err); +}; + +RequestBase.prototype._setTimeouts = function() { + var self = this; + + // deadline + if (this._timeout && !this._timer) { + this._timer = setTimeout(function(){ + self._timeoutError('Timeout of ', self._timeout, 'ETIME'); + }, this._timeout); + } + // response timeout + if (this._responseTimeout && !this._responseTimeoutTimer) { + this._responseTimeoutTimer = setTimeout(function(){ + self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); + }, this._responseTimeout); + } +} + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * Module dependencies. + */ + +var utils = __webpack_require__(63); + +/** + * Expose `ResponseBase`. + */ + +module.exports = ResponseBase; + +/** + * Initialize a new `ResponseBase`. + * + * @api public + */ + +function ResponseBase(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in ResponseBase.prototype) { + obj[key] = ResponseBase.prototype[key]; + } + return obj; +} + +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + +ResponseBase.prototype.get = function(field){ + return this.header[field.toLowerCase()]; +}; + +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + +ResponseBase.prototype._setHeaderProperties = function(header){ + // TODO: moar! + // TODO: make this a util + + // content-type + var ct = header['content-type'] || ''; + this.type = utils.type(ct); + + // params + var params = utils.params(ct); + for (var key in params) this[key] = params[key]; + + this.links = {}; + + // links + try { + if (header.link) { + this.links = utils.parseLinks(header.link); + } + } catch (err) { + // ignore + } +}; + +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + +ResponseBase.prototype._setStatusProperties = function(status){ + var type = status / 100 | 0; + + // status / class + this.status = this.statusCode = status; + this.statusType = type; + + // basics + this.info = 1 == type; + this.ok = 2 == type; + this.redirect = 3 == type; + this.clientError = 4 == type; + this.serverError = 5 == type; + this.error = (4 == type || 5 == type) + ? this.toError() + : false; + + // sugar + this.accepted = 202 == status; + this.noContent = 204 == status; + this.badRequest = 400 == status; + this.unauthorized = 401 == status; + this.notAcceptable = 406 == status; + this.forbidden = 403 == status; + this.notFound = 404 == status; +}; + + +/***/ }), +/* 62 */ +/***/ (function(module, exports) { + +var ERROR_CODES = [ + 'ECONNRESET', + 'ETIMEDOUT', + 'EADDRINFO', + 'ESOCKETTIMEDOUT' +]; + +/** + * Determine if a request should be retried. + * (Borrowed from segmentio/superagent-retry) + * + * @param {Error} err + * @param {Response} [res] + * @returns {Boolean} + */ +module.exports = function shouldRetry(err, res) { + if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true; + if (res && res.status && res.status >= 500) return true; + // Superagent timeout + if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true; + if (err && 'crossDomain' in err) return true; + return false; +}; + + +/***/ }), +/* 63 */ +/***/ (function(module, exports) { + + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.type = function(str){ + return str.split(/ *; */).shift(); +}; + +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.params = function(str){ + return str.split(/ *; */).reduce(function(obj, str){ + var parts = str.split(/ *= */); + var key = parts.shift(); + var val = parts.shift(); + + if (key && val) obj[key] = val; + return obj; + }, {}); +}; + +/** + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.parseLinks = function(str){ + return str.split(/ *, */).reduce(function(obj, str){ + var parts = str.split(/ *; */); + var url = parts[0].slice(1, -1); + var rel = parts[1].split(/ *= */)[1].slice(1, -1); + obj[rel] = url; + return obj; + }, {}); +}; + +/** + * Strip content related fields from `header`. + * + * @param {Object} header + * @return {Object} header + * @api private + */ + +exports.cleanHeader = function(header, shouldStripCookie){ + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header['host']; + if (shouldStripCookie) { + delete header['cookie']; + } + return header; +}; + +/***/ }), +/* 64 */ +/***/ (function(module, exports) { + +/* (ignored) */ + +/***/ }) +/******/ ]); +}); +//# sourceMappingURL=av-weapp.js.map \ No newline at end of file diff --git a/dist/av-weapp.js.map b/dist/av-weapp.js.map new file mode 100644 index 000000000..6be526425 --- /dev/null +++ b/dist/av-weapp.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 49fd826478e50efdbf60","webpack:///./~/underscore/underscore.js","webpack:///./src/promise.js","webpack:///./src/request.js","webpack:///./src/error.js","webpack:///./src/utils/index.js","webpack:///./~/debug/src/browser.js","webpack:///./src/av.js","webpack:///./~/superagent/lib/client.js","webpack:///(webpack)/buildin/global.js","webpack:///./~/weapp-polyfill/formdata.js","webpack:///./~/event-target-shim/lib/commons.js","webpack:///./~/superagent/lib/is-object.js","webpack:///./~/weapp-polyfill/localstorage.js","webpack:///./~/weapp-polyfill/navigator.js","webpack:///./~/weapp-polyfill/websocket.js","webpack:///./~/weapp-polyfill/xmlhttprequest.js","webpack:///./src/cache.js","webpack:///./src/localstorage.js","webpack:///./src/version.js","webpack:///./~/charenc/charenc.js","webpack:///./~/event-target-shim/lib/event-target.js","webpack:///./~/object-assign/index.js","webpack:///./~/weapp-polyfill/auto-polyfill.js","webpack:///./src/index.js","webpack:///./~/weapp-polyfill/index.js","webpack:///./src/acl.js","webpack:///./src/cloudfunction.js","webpack:///./src/event.js","webpack:///./src/file.js","webpack:///./src/geopoint.js","webpack:///./src/index-weapp.js","webpack:///./src/init.js","webpack:///./src/insight.js","webpack:///./src/object.js","webpack:///./src/op.js","webpack:///./src/push.js","webpack:///./src/query.js","webpack:///./src/relation.js","webpack:///./src/role.js","webpack:///./src/search.js","webpack:///./src/status.js","webpack:///./src/ua/comments-browser.js","webpack:///./src/ua/index.js","webpack:///./src/uploader/cos.js","webpack:///./src/uploader/qiniu-browser.js","webpack:///./src/uploader/s3.js","webpack:///./src/user.js","webpack:///./src/utils/localstorage-browser.js","webpack:///./src/utils/parse-base64-browser.js","webpack:///./~/component-emitter/index.js","webpack:///./~/crypt/crypt.js","webpack:///./~/debug/src/debug.js","webpack:///./~/es6-promise/dist/es6-promise.js","webpack:///./~/event-target-shim/lib/custom-event-target.js","webpack:///./~/event-target-shim/lib/event-wrapper.js","webpack:///./~/is-buffer/index.js","webpack:///./~/localstorage-memory/lib/localstorage-memory.js","webpack:///./~/md5/md5.js","webpack:///./~/ms/index.js","webpack:///./~/superagent/lib/is-function.js","webpack:///./~/superagent/lib/request-base.js","webpack:///./~/superagent/lib/response-base.js","webpack:///./~/superagent/lib/should-retry.js","webpack:///./~/superagent/lib/utils.js","webpack:///vertx (ignored)"],"names":["_","require","Promise","_continueWhile","predicate","asyncFunction","then","resolve","module","exports","request","debug","md5","Cache","AVError","AV","getSessionToken","getServerURLPromise","API_HOST","cn","us","sign","key","isMasterKey","now","Date","getTime","signature","requestsCount","ajax","method","resourceUrl","data","headers","onprogress","count","reject","req","set","send","on","end","err","res","status","body","text","header","statusCode","responseText","response","setAppKey","signKey","applicationKey","setHeaders","authOptions","applicationId","useMasterKey","_useMasterKey","masterKey","console","warn","hookKey","_config","applicationProduction","String","userAgent","sessionToken","disableCurrentUser","User","currentAsync","currentUser","_sessionToken","createApiUrl","route","className","objectId","dataObject","serverURL","APIServerURL","apiURL","charAt","length","_fetchWhenSave","_where","encodeURIComponent","JSON","stringify","toLowerCase","indexOf","k","cacheServerURL","ttl","setAsync","handleError","error","api_server","location","catch","errorJSON","code","message","parse","e","setServerUrl","newRegion","findKey","item","region","refreshServerUrlByRouter","url","servers","setServerUrlByRegion","getAsync","AVRequest","Error","extend","OTHER_CAUSE","INTERNAL_SERVER_ERROR","CONNECTION_FAILED","OBJECT_NOT_FOUND","INVALID_QUERY","INVALID_CLASS_NAME","MISSING_OBJECT_ID","INVALID_KEY_NAME","INVALID_POINTER","INVALID_JSON","COMMAND_UNAVAILABLE","NOT_INITIALIZED","INCORRECT_TYPE","INVALID_CHANNEL_NAME","PUSH_MISCONFIGURED","OBJECT_TOO_LARGE","OPERATION_FORBIDDEN","CACHE_MISS","INVALID_NESTED_KEY","INVALID_FILE_NAME","INVALID_ACL","TIMEOUT","INVALID_EMAIL_ADDRESS","MISSING_CONTENT_TYPE","MISSING_CONTENT_LENGTH","INVALID_CONTENT_LENGTH","FILE_TOO_LARGE","FILE_SAVE_ERROR","FILE_DELETE_ERROR","DUPLICATE_VALUE","INVALID_ROLE_NAME","EXCEEDED_QUOTA","SCRIPT_FAILED","VALIDATION_ERROR","INVALID_IMAGE_DATA","UNSAVED_FILE_ERROR","INVALID_PUSH_TIME_ERROR","USERNAME_MISSING","PASSWORD_MISSING","USERNAME_TAKEN","EMAIL_TAKEN","EMAIL_MISSING","EMAIL_NOT_FOUND","SESSION_MISSING","MUST_CREATE_USER_THROUGH_SIGNUP","ACCOUNT_ALREADY_LINKED","LINKED_ID_MISSING","INVALID_LINKED_SESSION","UNSUPPORTED_SERVICE","X_DOMAIN_REQUEST","isNullOrUndefined","x","isNull","isUndefined","ensureArray","isArray","target","undefined","user","tap","interceptor","value","global","AVConfig","EmptyConstructor","inherits","parent","protoProps","staticProps","child","hasOwnProperty","constructor","apply","arguments","prototype","__super__","setProduction","production","_getAVPath","path","isString","substring","_installationId","_getInstallationId","localStorage","getItemAsync","hexOctet","Math","floor","random","toString","setItemAsync","_parseDate","iso8601","regexp","RegExp","match","exec","year","month","day","hour","minute","second","milli","UTC","_extend","classProps","_getValue","object","prop","isFunction","_encode","seenObjects","disallowObjects","Object","include","_hasData","_toPointer","dirty","concat","_toFullJSON","ACL","toJSON","isDate","GeoPoint","map","isRegExp","source","Relation","Op","File","id","isObject","mapObject","v","_decode","__op","__type","pointer","_create","keys","clone","_finishFetch","iso","latitude","longitude","relation","targetClassName","file","name","_encodeObjectOrArray","encodeAVObject","_arrayEach","each","_traverse","func","seen","push","attributes","index","newChild","_each","_objectEach","obj","callback","FormData","_entries","TypeError","uri","entry","get","append","filter","find","some","Storage","wx","getStorageSync","setStorageSync","setItem","clearStorageSync","assign","EventTarget","CONNECTING","OPEN","CLOSING","CLOSED","EVENTS","instance","errorHandler","event","_readyState","dispatchEvent","type","errMsg","WebSocket","protocal","_url","_protocal","onSocketOpen","onSocketError","onSocketMessage","origin","ports","onSocketClose","reason","wasClean","connectSocket","fail","setTimeout","readyState","closeSocket","sendSocketMessage","UNSENT","OPENED","HEADERS_RECEIVED","LOADING","DONE","REQUEST_EVENTS","successCallback","statusText","XMLHttpRequest","_headers","async","_method","entries","blobs","restData","reduce","result","uploadFile","filePath","formData","success","bind","toUpperCase","storage","removeAsync","removeItemAsync","getCacheData","cacheData","expired","expiredAt","cache","syncApiNames","apiName","polyfill","window","navigator","version","polyfills","PUBLIC_KEY","arg1","self","permissionsById","setReadAccess","setWriteAccess","accessList","userId","allowed","permission","isBoolean","_setAccess","accessType","Role","getName","permissions","isEmpty","_getAccess","getReadAccess","getWriteAccess","setPublicReadAccess","getPublicReadAccess","setPublicWriteAccess","getPublicWriteAccess","getRoleReadAccess","role","getRoleWriteAccess","setRoleReadAccess","setRoleWriteAccess","Cloud","run","options","resp","rpc","getServerDate","requestSmsCode","mobilePhoneNumber","verifySmsCode","phone","params","eventSplitter","slice","Array","Events","events","context","calls","node","tail","list","split","_callbacks","shift","next","off","cb","ctx","trigger","args","all","rest","call","unbind","cos","qiniu","s3","parseBase64","avConfig","extname","b64Digit","number","fromCharCode","encodeBase64","array","chunks","ceil","times","i","b1","b2","b3","has2","has3","join","mimeType","metaData","base64","size","_extName","_data","owner","current","withURL","__source","createWithoutData","json","val","_operations","has","getACL","_acl","setACL","acl","attrName","attr","thumbnailURL","width","height","quality","scaleToFit","fmt","mode","ownerId","destroy","_fileToken","extName","mime_type","_qiniu_key","save","_previousSave","uploadInfo","_token","token","blob","Buffer","isBuffer","uploadPromise","provider","_callback","fetch","bucket","arg2","_validate","isNumber","__defineGetter__","__defineSetter__","_latitude","_longitude","geolocation","getCurrentPosition","coords","radiansTo","point","d2r","PI","lat1rad","long1rad","lat2rad","long2rad","deltaLat","deltaLong","sinDeltaLatDiv2","sin","sinDeltaLongDiv2","a","min","asin","sqrt","kilometersTo","milesTo","initialize","appId","appKey","process","env","LEANCLOUD_APP_HOOK_KEY","masterKeyWarn","init","Insight","startJob","jobConfig","sql","JobQuery","_skip","_limit","skip","n","limit","utils","RESERVED_KEYS","checkReservedKey","_mergeMagicFields","defaults","collection","_serverData","_opSetQueue","_flags","_hashedJSON","_escapedAttributes","cid","uniqueId","changed","_silent","_pending","silent","_previousAttributes","saveAll","_deepSaveAsync","fetchAll","objects","requests","forEach","fetchWhenSave","enable","getObjectId","getCreatedAt","createdAt","getUpdatedAt","updatedAt","_refreshCache","_refreshingCache","_resetCacheForKey","Set","currentChanges","last","_ensureParentAndKey","escape","html","escaped","attrs","model","specialFields","_startSave","_cancelSave","failedChanges","first","nextChanges","op","op1","op2","_mergeWithPrevious","_saving","_finishSave","serverData","fetchedObjects","savedChanges","_applyOpSet","fetched","_rebuildAllEstimatedData","hasData","opSet","change","_estimate","_UNSET","wasSet","_rebuildEstimatedDataForKey","previousAttributes","oldValue","newValue","unset","unused_value","Unset","dataToValidate","changes","prev","isRealChange","isEqual","increment","amount","Increment","add","Add","addUnique","AddUnique","remove","Remove","clear","keysToClear","_getSaveJSON","_canBeSerialized","_canBeSerializedAsValue","fetchOptions","arg3","saved","wait","setOptions","unsavedChildren","unsavedFiles","_findUnsavedChildren","_allPreviousSaves","query","queryJSON","where","makeRequest","_makeRequest","serverAttrs","triggerDestroy","output","isNew","changing","_changing","deleteChanged","hasChanged","changedAttributes","diff","old","diffVal","previous","isValid","validate","disableBeforeHook","ignoreHook","disableAfterHook","hookName","contains","trace","__ignore_hooks","destroyAll","objectsByClassNameAndFlags","groupBy","flags","ids","_getSubclass","ObjectClass","_classMap","noDefaultACL","NewClassObject","OldClassObject","_className","arg0","newArguments","toArray","defineProperty","_LCClassName","register","klass","children","files","canBeSerializedAsValue","promise","uniq","remaining","batch","newRemaining","readyToStart","bathSavePromise","_initialize","_opDecoderMap","_registerDecoder","opName","decoder","ops","nextOp","_value","_amount","_objects","matchingObj","anObj","union","difference","other","adds","removes","_targetClassName","pointerToId","relationsToAdd","relationsToRemove","added","removed","idToPointer","pointers","newAdd","newRemove","newRelation","Installation","Push","cql","push_time","expiration_time","expiration_time_interval","requires","Query","objectClass","_include","_select","_extraOptions","or","queries","q","_orQuery","and","_andQuery","doCloudQuery","pvalues","results","_newObject","_processResult","errorObject","_order","order","_createRequest","_parseResponse","scan","orderedBy","batchSize","condition","scan_key","cursor","done","remainResults","equalTo","_addCondition","sizeEqualTo","notEqualTo","lessThan","greaterThan","lessThanOrEqualTo","greaterThanOrEqualTo","containedIn","values","notContainedIn","containsAll","exists","doesNotExist","matches","regex","modifiers","ignoreCase","multiline","matchesQuery","doesNotMatchQuery","matchesKeyInQuery","queryKey","doesNotMatchKeyInQuery","$or","$and","_quote","s","replace","startsWith","endsWith","ascending","addAscending","descending","addDescending","near","withinRadians","distance","withinMiles","withinKilometers","withinGeoBox","southwest","northeast","select","finished","callbacksDone","FriendShipQuery","_objectClass","_friendshipTag","reverseQuery","parentClass","relationKey","targetClass","redirectClassNameForKey","setName","defaultAcl","getUsers","getRoles","newName","test","SearchSortBuilder","_sortFields","_addField","missing","field","whereNear","geo","lat","lon","m","unit","build","SearchQuery","_sid","_hits","_queryString","_highlights","_sortBuilder","sid","queryString","highlights","sortBy","builder","hits","hasMore","_hitEnd","reset","_oldSid","appURL","clazz","sort","getUser","currUser","_fetchUserBySessionToken","getUserPointer","Status","imageUrl","inboxType","image","toObject","_getDataJSON","sendStatusToFollowers","messageId","sendPrivateStatus","userObjectId","countUnreadStatuses","resetUnreadCount","statusQuery","InboxQuery","_sinceId","_maxId","_inboxType","_owner","sinceId","maxId","inboxQuery","comments","upload","saveOptions","_bucket","uploadUrl","upload_url","uptoken","AVPromise","getWeappLoginCode","login","_isCurrentUser","_cleanupAuthData","isCurrent","authData","_synchronizeAllAuthData","_synchronizeAuthData","authType","_authProviders","getAuthType","restoreAuthentication","_unlinkFrom","_handleSaveResult","makeCurrent","password","_saveCurrentUser","_linkWith","authenticate","linkWithWeapp","_isLinked","logOut","_logOutWithAll","_logOutWith","deauthenticate","signUp","username","signUpOrlogInWithMobilePhone","smsCode","logIn","follow","unfollow","followerQuery","followeeQuery","updatePassword","oldPassword","newPassword","old_password","new_password","getUsername","getMobilePhoneNumber","setMobilePhoneNumber","setUsername","setPassword","getEmail","setEmail","email","authenticated","isAuthenticated","refreshSessionToken","_currentUser","_currentUserMatchesDisk","_CURRENT_USER_KEY","become","session_token","logInWithMobilePhoneSmsCode","mobilePhone","logInWithMobilePhone","signUpOrlogInWithAuthData","platform","_logInWith","loginWithWeapp","associateWithAuthData","userObj","requestPasswordReset","requestEmailVerify","requestMobilePhoneVerify","requestPasswordResetBySmsCode","resetPasswordBySmsCode","verifyMobilePhone","requestLoginSmsCode","userData","_id","getItem","_registerAuthenticationProvider","apiNames","testKey","removeItem","dataURItoBlob","dataURI","byteString","atob","unescape","ia","Uint8Array","charCodeAt","Blob"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA,mDAA2C,cAAc;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;AAEA;AACA;;;;;;;AChEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,gBAAgB;AACzC;AACA;AACA;AACA,uBAAuB,OAAO;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,YAAY;AAClD;AACA;AACA,KAAK;AACL;AACA,uCAAuC,YAAY;AACnD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,8BAA8B;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,YAAY;AACtD;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,YAAY;AACtD;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B,gBAAgB;AAC7C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA,oDAAoD;AACpD,GAAG;;AAEH;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA,0CAA0C;AAC1C,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,4DAA4D,YAAY;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,YAAY;AAC1D;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,8CAA8C,YAAY;AAC1D;AACA;AACA,qBAAqB,gBAAgB;AACrC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,6CAA6C,YAAY;AACzD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,8BAA8B;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD;AACtD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,0BAA0B;AACpE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,qBAAqB,cAAc;AACnC;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,YAAY;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,OAAO,eAAe;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,qBAAqB,eAAe;AACpC;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,yBAAyB,gBAAgB;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB;AACnB;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,4CAA4C,mBAAmB;AAC/D;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,qDAAqD;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6EAA6E;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,qCAAqC;AACrC;AACA;AACA;;AAEA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,mBAAmB,OAAO;AAC1B;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe;AACf,cAAc;AACd,cAAc;AACd,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;;AAE5B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA,OAAO;AACP,qBAAqB;AACrB;;AAEA;AACA;AACA,KAAK;AACL,iBAAiB;;AAEjB;AACA,kDAAkD,EAAE,iBAAiB;;AAErE;AACA,wBAAwB,8BAA8B;AACtD,2BAA2B;;AAE3B;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,kDAAkD,iBAAiB;;AAEnE;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AAAA;AACL;AACA,CAAC;;;;;;;;;;AC3gDD,IAAIA,IAAI,mBAAAC,CAAQ,CAAR,CAAR;AACA,IAAIC,UAAU,mBAAAD,CAAQ,EAAR,EAAuBC,OAArC;;AAEAA,QAAQC,c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C;;;;;;AC5BA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;;;;;;;;;;ACxLA,IAAMhL,IAAI,mBAAAC,CAAQ,CAAR,CAAV;AACA,IAAMiE,YAAY,mBAAAjE,CAAQ,EAAR,CAAlB;;eAGI,mBAAAA,CAAQ,CAAR,C;IADFsK,iB,YAAAA,iB;;AAGF,IAAMxJ,KAAKoK,OAAOpK,EAAP,IAAa,EAAxB;;AAEA;AACAA,GAAGgD,OAAH,GAAahD,GAAGgD,OAAH,IAAc,EAA3B;AACA,IAAMqH,WAAWrK,GAAGgD,OAApB;;AAEA/D,EAAEo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,GAAJ,CAAT,EAAmBA,GAAnB;AACD,KAFD;AAGD,GAJD,MAIO;AACLtB,MAAE+Q,IAAF,CAAOU,GAAP,EAAYC,QAAZ;AACD;AACF,CARD;;AAUAlR,OAAOC,OAAP,GAAiBM,EAAjB,C;;;;;;;ACvaA;AACA;AACA;;AAEA;AACA,oCAAoC;AACpC;AACA,CAAC,wCAAwC;AACzC;AACA,CAAC,OAAO;AACR;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH,SAAS,+CAA+C,EAAE;AAC1D,SAAS,gDAAgD,EAAE;AAC3D,SAAS,gDAAgD,EAAE;AAC3D,SAAS,4CAA4C,EAAE;AACvD;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA,iBAAiB,iBAAiB;AAClC,iBAAiB,sCAAsC;;AAEvD;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,qCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,cAAc;;AAEd,qCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C;AAC5C,wCAAwC;AACxC;AACA;AACA;AACA;AACA;AACA,iBAAiB,aAAa;AAC9B,8BAA8B;AAC9B;AACA;AACA;AACA;AACA;AACA,iBAAiB,aAAa,iBAAiB;AAC/C;AACA;AACA;AACA;AACA,0BAA0B,aAAa;AACvC,8BAA8B;AAC9B;AACA;AACA;AACA;AACA,0BAA0B,aAAa,iBAAiB;AACxD;AACA,WAAW,eAAe;AAC1B,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB;AACnB,oBAAoB;AACpB;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC;AACpC,OAAO;AACP;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,kBAAkB;AAClB;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA,kDAAkD;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,yDAAyD,iBAAiB;AAC1E;AACA,U;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,gBAAgB;AAC/B;AACA,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,wEAAwE,mBAAmB;AAC3F;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,UAAU;AACrB,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,SAAS,sBAAsB,WAAW,YAAY;;AAEtD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,4FAA4F;AAC5F;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,eAAe;AAC1B,WAAW,SAAS;AACpB,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CAAqB,UAAS4F,OAAT,EAAkB;AACrC,QAAI,OAAOlK,aAAakK,OAAb,CAAP,KAAiC,UAArC,EAAiD;AAC/ClK,mBAAakK,OAAb,IAAwB,YAAW;AACjC,YAAM5Q,QAAQ,IAAIoB,KAAJ,CAAU,sBAAsBwP,OAAtB,GAAgC,qCAA1C,CAAd;AACA5Q,cAAMK,IAAN,GAAa,wBAAb;AACA,cAAML,KAAN;AACD,OAJD;AAKD;AACF,GARD;AASD;;AAEDvF,OAAOC,OAAP,GAAiBgM,YAAjB,C;;;;;;;;;AChCAjM,OAAOC,OAAP,GAAiB,OAAjB,C;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA,iCAAiC,gBAAgB;AACjD;AACA;AACA,KAAK;;AAEL;AACA;AACA,+BAA+B,kBAAkB;AACjD;AACA;AACA;AACA;AACA;;AAEA;;;;;;;;AChCA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gDAAgD,2BAA2B;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,sBAAsB;AAC7C;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA,aAAa;AACb;AACA;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;;;;;;;;AC7LA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,gCAAgC;AAChC;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,QAAQ;AACzB;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH,kCAAkC;AAClC;AACA;AACA;;AAEA;AACA,EAAE;AACF;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,gBAAgB,sBAAsB;AACtC;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,kBAAkB,oBAAoB;AACtC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;;;;;;;;;ACzFA,IAAImW,WAAW,mBAAA3W,CAAQ,EAAR,EAAsB2W,QAArC;AACAC,SAASA,UAAU,EAAnB;AACAD;AACAA,SAASC,MAAT;AACA,IAAI;AACFpK,iBAAeA,gBAAgB,mBAAAxM,CAAQ,EAAR,CAA/B;AACD,CAFD,CAEE,OAAOsG,CAAP,EAAU,CAAE;AACd,IAAI;AACF4O,mBAAiBA,kBAAkB,mBAAAlV,CAAQ,EAAR,CAAnC;AACD,CAFD,CAEE,OAAOsG,CAAP,EAAU,CAAE;AACd,IAAI;AACFoL,aAAWA,YAAY,mBAAA1R,CAAQ,CAAR,CAAvB;AACD,CAFD,CAEE,OAAOs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A;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,sBAAsB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB,YAAY;AACZ;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,2CAA2C,SAAS;AACpD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;;;;;;AClKA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qBAAqB,cAAc;AACnC;AACA;AACA,KAAK;;AAEL;AACA;AACA,0BAA0B,OAAO;AACjC;AACA;AACA,KAAK;;AAEL;AACA;AACA,wCAAwC,kBAAkB;AAC1D;AACA;AACA,KAAK;;AAEL;AACA;AACA,iCAAiC,uBAAuB;AACxD;AACA;AACA,KAAK;;AAEL;AACA;AACA,+BAA+B,kBAAkB;AACjD;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA,iCAAiC,gBAAgB;AACjD;AACA;AACA,KAAK;;AAEL;AACA;AACA,kCAAkC,kBAAkB;AACpD;AACA,uBAAuB,OAAO;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;;AAEA,4CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,CAAC;;;;;;;;AC9FD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;;AAEA;AACA;AACA,cAAc;AACd;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB,iBAAiB;AACpC;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,iBAAiB,SAAS;AAC1B,4BAA4B;AAC5B;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA,yCAAyC,SAAS;AAClD;AACA;AACA;AACA;AACA,yCAAyC,SAAS;AAClD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,MAAM;AACjB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;;;;;;8CCzMA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC,qBAAqB;;AAEtB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,iFAAiF;;AAEjF;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,0BAA0B,sBAAsB;;AAEhD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,IAAI;AACd;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,iBAAiB,wBAAwB;AACzC;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,iBAAiB,uCAAuC;AACxD;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,OAAO;AACP;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,MAAM;AAChB,UAAU,OAAO;AACjB;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,UAAU,MAAM;AAChB;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA,qBAAqB,YAAY;AACjC;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,IAAI;AACd;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;AACH;;AAEA;AACA,UAAU,SAAS;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,KAAK;;AAEL;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,eAAe;AACf;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA,YAAY,SAAS;AACrB,YAAY,SAAS;AACrB;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA,YAAY,SAAS;AACrB;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA,CAAC;AACD;;;;;;;;;ACroCA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,YAAY;AACvB,WAAW,OAAO;AAClB,aAAa,cAAc;AAC3B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,YAAY;AACvB,WAAW,OAAO;AAClB,WAAW,cAAc;AACzB,aAAa;AACb;AACA;AACA;AACA,wBAAwB;AACxB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,YAAY;AACvB,WAAW,SAAS;AACpB,aAAa,YAAY;AACzB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,6BAA6B,yCAAyC,EAAE;AACxE,qCAAqC,4CAA4C,EAAE;AACnF;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;AACA;;;;;;;;ACtHA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,KAAK;;AAEL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,KAAK;;AAEL;AACA,0CAA0C,4BAA4B,EAAE;AACxE;AACA;AACA,KAAK;AACL,CAAC;;AAED;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO,cAAc;AAChC,WAAW,YAAY;AACvB,aAAa,MAAM;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,oCAAoC;AACnD,iBAAiB,qCAAqC;AACtD,wBAAwB,qCAAqC;AAC7D,qBAAqB,2BAA2B;AAChD,kBAAkB,gDAAgD;AAClE,qBAAqB,mDAAmD;AACxE,oBAAoB,mCAAmC;AACvD,oBAAoB;AACpB;AACA,2DAA2D;AAC3D,yCAAyC;AACzC,0CAA0C;;AAE1C;AACA;AACA,qCAAqC;AACrC;;AAEA;AACA;AACA;AACA;AACA;;;;;;;AC5IA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;ACpBA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA,eAAe;AACf;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA,YAAY,OAAO;AACnB;AACA,eAAe;AACf;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA,eAAe;AACf;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA,CAAC;;;;;;;ACjFD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,mBAAmB,cAAc;AACjC;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,mBAAmB,cAAc;;AAEjC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,CAAC;;;;;;;AC/JD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,OAAO;AAClB,YAAY,MAAM;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpJA;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;;;;;;ACdA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc,QAAQ;AACjC,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB,YAAY;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC;AAClC,OAAO;AACP,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,oDAAoD;AACpE;AACA;AACA,WAAW,cAAc;AACzB,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,yBAAyB;AACtC;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,sCAAsC;AACjD,YAAY,QAAQ;AACpB;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B;AAC/B,+BAA+B;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA,kBAAkB,aAAa;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,aAAa;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;;;;;;;AC7kBA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2CAA2C;AAC3C;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpIA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrBA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA,uBAAuB;AACvB;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA,uBAAuB;AACvB;AACA;AACA;;AAEA;AACA;AACA,GAAG,IAAI;AACP;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA,8BAA8B;AAC9B;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;;;;;;ACnEA,e","file":"av-weapp.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"AV\"] = factory();\n\telse\n\t\troot[\"AV\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// identity function for calling harmony imports with the correct context\n \t__webpack_require__.i = function(value) { return value; };\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 30);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 49fd826478e50efdbf60","// Underscore.js 1.8.3\n// http://underscorejs.org\n// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n// Underscore may be freely distributed under the MIT license.\n\n(function() {\n\n // Baseline setup\n // --------------\n\n // Establish the root object, `window` in the browser, or `exports` on the server.\n var root = this;\n\n // Save the previous value of the `_` variable.\n var previousUnderscore = root._;\n\n // Save bytes in the minified (but not gzipped) version:\n var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;\n\n // Create quick reference variables for speed access to core prototypes.\n var\n push = ArrayProto.push,\n slice = ArrayProto.slice,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty;\n\n // All **ECMAScript 5** native function implementations that we hope to use\n // are declared here.\n var\n nativeIsArray = Array.isArray,\n nativeKeys = Object.keys,\n nativeBind = FuncProto.bind,\n nativeCreate = Object.create;\n\n // Naked function reference for surrogate-prototype-swapping.\n var Ctor = function(){};\n\n // Create a safe reference to the Underscore object for use below.\n var _ = function(obj) {\n if (obj instanceof _) return obj;\n if (!(this instanceof _)) return new _(obj);\n this._wrapped = obj;\n };\n\n // Export the Underscore object for **Node.js**, with\n // backwards-compatibility for the old `require()` API. If we're in\n // the browser, add `_` as a global object.\n if (typeof exports !== 'undefined') {\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = _;\n }\n exports._ = _;\n } else {\n root._ = _;\n }\n\n // Current version.\n _.VERSION = '1.8.3';\n\n // Internal function that returns an efficient (for current engines) version\n // of the passed-in callback, to be repeatedly applied in other Underscore\n // functions.\n var optimizeCb = function(func, context, argCount) {\n if (context === void 0) return func;\n switch (argCount == null ? 3 : argCount) {\n case 1: return function(value) {\n return func.call(context, value);\n };\n case 2: return function(value, other) {\n return func.call(context, value, other);\n };\n case 3: return function(value, index, collection) {\n return func.call(context, value, index, collection);\n };\n case 4: return function(accumulator, value, index, collection) {\n return func.call(context, accumulator, value, index, collection);\n };\n }\n return function() {\n return func.apply(context, arguments);\n };\n };\n\n // A mostly-internal function to generate callbacks that can be applied\n // to each element in a collection, returning the desired result — either\n // identity, an arbitrary callback, a property matcher, or a property accessor.\n var cb = function(value, context, argCount) {\n if (value == null) return _.identity;\n if (_.isFunction(value)) return optimizeCb(value, context, argCount);\n if (_.isObject(value)) return _.matcher(value);\n return _.property(value);\n };\n _.iteratee = function(value, context) {\n return cb(value, context, Infinity);\n };\n\n // An internal function for creating assigner functions.\n var createAssigner = function(keysFunc, undefinedOnly) {\n return function(obj) {\n var length = arguments.length;\n if (length < 2 || obj == null) return obj;\n for (var index = 1; index < length; index++) {\n var source = arguments[index],\n keys = keysFunc(source),\n l = keys.length;\n for (var i = 0; i < l; i++) {\n var key = keys[i];\n if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];\n }\n }\n return obj;\n };\n };\n\n // An internal function for creating a new object that inherits from another.\n var baseCreate = function(prototype) {\n if (!_.isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n };\n\n var property = function(key) {\n return function(obj) {\n return obj == null ? void 0 : obj[key];\n };\n };\n\n // Helper for collection methods to determine whether a collection\n // should be iterated as an array or as an object\n // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength\n // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094\n var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;\n var getLength = property('length');\n var isArrayLike = function(collection) {\n var length = getLength(collection);\n return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;\n };\n\n // Collection Functions\n // --------------------\n\n // The cornerstone, an `each` implementation, aka `forEach`.\n // Handles raw objects in addition to array-likes. Treats all\n // sparse array-likes as if they were dense.\n _.each = _.forEach = function(obj, iteratee, context) {\n iteratee = optimizeCb(iteratee, context);\n var i, length;\n if (isArrayLike(obj)) {\n for (i = 0, length = obj.length; i < length; i++) {\n iteratee(obj[i], i, obj);\n }\n } else {\n var keys = _.keys(obj);\n for (i = 0, length = keys.length; i < length; i++) {\n iteratee(obj[keys[i]], keys[i], obj);\n }\n }\n return obj;\n };\n\n // Return the results of applying the iteratee to each element.\n _.map = _.collect = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n results = Array(length);\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n results[index] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Create a reducing function iterating left or right.\n function createReduce(dir) {\n // Optimized iterator function as using arguments.length\n // in the main function will deoptimize the, see #1991.\n function iterator(obj, iteratee, memo, keys, index, length) {\n for (; index >= 0 && index < length; index += dir) {\n var currentKey = keys ? keys[index] : index;\n memo = iteratee(memo, obj[currentKey], currentKey, obj);\n }\n return memo;\n }\n\n return function(obj, iteratee, memo, context) {\n iteratee = optimizeCb(iteratee, context, 4);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n index = dir > 0 ? 0 : length - 1;\n // Determine the initial value if none is provided.\n if (arguments.length < 3) {\n memo = obj[keys ? keys[index] : index];\n index += dir;\n }\n return iterator(obj, iteratee, memo, keys, index, length);\n };\n }\n\n // **Reduce** builds up a single result from a list of values, aka `inject`,\n // or `foldl`.\n _.reduce = _.foldl = _.inject = createReduce(1);\n\n // The right-associative version of reduce, also known as `foldr`.\n _.reduceRight = _.foldr = createReduce(-1);\n\n // Return the first value which passes a truth test. Aliased as `detect`.\n _.find = _.detect = function(obj, predicate, context) {\n var key;\n if (isArrayLike(obj)) {\n key = _.findIndex(obj, predicate, context);\n } else {\n key = _.findKey(obj, predicate, context);\n }\n if (key !== void 0 && key !== -1) return obj[key];\n };\n\n // Return all the elements that pass a truth test.\n // Aliased as `select`.\n _.filter = _.select = function(obj, predicate, context) {\n var results = [];\n predicate = cb(predicate, context);\n _.each(obj, function(value, index, list) {\n if (predicate(value, index, list)) results.push(value);\n });\n return results;\n };\n\n // Return all the elements for which a truth test fails.\n _.reject = function(obj, predicate, context) {\n return _.filter(obj, _.negate(cb(predicate)), context);\n };\n\n // Determine whether all of the elements match a truth test.\n // Aliased as `all`.\n _.every = _.all = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (!predicate(obj[currentKey], currentKey, obj)) return false;\n }\n return true;\n };\n\n // Determine if at least one element in the object matches a truth test.\n // Aliased as `any`.\n _.some = _.any = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (predicate(obj[currentKey], currentKey, obj)) return true;\n }\n return false;\n };\n\n // Determine if the array or object contains a given item (using `===`).\n // Aliased as `includes` and `include`.\n _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n if (typeof fromIndex != 'number' || guard) fromIndex = 0;\n return _.indexOf(obj, item, fromIndex) >= 0;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n var isFunc = _.isFunction(method);\n return _.map(obj, function(value) {\n var func = isFunc ? method : value[method];\n return func == null ? func : func.apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, _.property(key));\n };\n\n // Convenience version of a common use case of `filter`: selecting only objects\n // containing specific `key:value` pairs.\n _.where = function(obj, attrs) {\n return _.filter(obj, _.matcher(attrs));\n };\n\n // Convenience version of a common use case of `find`: getting the first object\n // containing specific `key:value` pairs.\n _.findWhere = function(obj, attrs) {\n return _.find(obj, _.matcher(attrs));\n };\n\n // Return the maximum element (or element-based computation).\n _.max = function(obj, iteratee, context) {\n var result = -Infinity, lastComputed = -Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value > result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed > lastComputed || computed === -Infinity && result === -Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iteratee, context) {\n var result = Infinity, lastComputed = Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value < result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed < lastComputed || computed === Infinity && result === Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Shuffle a collection, using the modern version of the\n // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).\n _.shuffle = function(obj) {\n var set = isArrayLike(obj) ? obj : _.values(obj);\n var length = set.length;\n var shuffled = Array(length);\n for (var index = 0, rand; index < length; index++) {\n rand = _.random(0, index);\n if (rand !== index) shuffled[index] = shuffled[rand];\n shuffled[rand] = set[index];\n }\n return shuffled;\n };\n\n // Sample **n** random values from a collection.\n // If **n** is not specified, returns a single random element.\n // The internal `guard` argument allows it to work with `map`.\n _.sample = function(obj, n, guard) {\n if (n == null || guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n return obj[_.random(obj.length - 1)];\n }\n return _.shuffle(obj).slice(0, Math.max(0, n));\n };\n\n // Sort the object's values by a criterion produced by an iteratee.\n _.sortBy = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value: value,\n index: index,\n criteria: iteratee(value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria;\n var b = right.criteria;\n if (a !== b) {\n if (a > b || a === void 0) return 1;\n if (a < b || b === void 0) return -1;\n }\n return left.index - right.index;\n }), 'value');\n };\n\n // An internal function used for aggregate \"group by\" operations.\n var group = function(behavior) {\n return function(obj, iteratee, context) {\n var result = {};\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index) {\n var key = iteratee(value, index, obj);\n behavior(result, value, key);\n });\n return result;\n };\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key].push(value); else result[key] = [value];\n });\n\n // Indexes the object's values by a criterion, similar to `groupBy`, but for\n // when you know that your index values will be unique.\n _.indexBy = group(function(result, value, key) {\n result[key] = value;\n });\n\n // Counts instances of an object that group by a certain criterion. Pass\n // either a string attribute to count by, or a function that returns the\n // criterion.\n _.countBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key]++; else result[key] = 1;\n });\n\n // Safely create a real, live array from anything iterable.\n _.toArray = function(obj) {\n if (!obj) return [];\n if (_.isArray(obj)) return slice.call(obj);\n if (isArrayLike(obj)) return _.map(obj, _.identity);\n return _.values(obj);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n if (obj == null) return 0;\n return isArrayLike(obj) ? obj.length : _.keys(obj).length;\n };\n\n // Split a collection into two arrays: one whose elements all satisfy the given\n // predicate, and one whose elements all do not satisfy the predicate.\n _.partition = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var pass = [], fail = [];\n _.each(obj, function(value, key, obj) {\n (predicate(value, key, obj) ? pass : fail).push(value);\n });\n return [pass, fail];\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head` and `take`. The **guard** check\n // allows it to work with `_.map`.\n _.first = _.head = _.take = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[0];\n return _.initial(array, array.length - n);\n };\n\n // Returns everything but the last entry of the array. Especially useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array.\n _.last = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[array.length - 1];\n return _.rest(array, Math.max(0, array.length - n));\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.\n // Especially useful on the arguments object. Passing an **n** will return\n // the rest N values in the array.\n _.rest = _.tail = _.drop = function(array, n, guard) {\n return slice.call(array, n == null || guard ? 1 : n);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, _.identity);\n };\n\n // Internal implementation of a recursive `flatten` function.\n var flatten = function(input, shallow, strict, startIndex) {\n var output = [], idx = 0;\n for (var i = startIndex || 0, length = getLength(input); i < length; i++) {\n var value = input[i];\n if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {\n //flatten current level of array or arguments object\n if (!shallow) value = flatten(value, shallow, strict);\n var j = 0, len = value.length;\n output.length += len;\n while (j < len) {\n output[idx++] = value[j++];\n }\n } else if (!strict) {\n output[idx++] = value;\n }\n }\n return output;\n };\n\n // Flatten out an array, either recursively (by default), or just one level.\n _.flatten = function(array, shallow) {\n return flatten(array, shallow, false);\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iteratee, context) {\n if (!_.isBoolean(isSorted)) {\n context = iteratee;\n iteratee = isSorted;\n isSorted = false;\n }\n if (iteratee != null) iteratee = cb(iteratee, context);\n var result = [];\n var seen = [];\n for (var i = 0, length = getLength(array); i < length; i++) {\n var value = array[i],\n computed = iteratee ? iteratee(value, i, array) : value;\n if (isSorted) {\n if (!i || seen !== computed) result.push(value);\n seen = computed;\n } else if (iteratee) {\n if (!_.contains(seen, computed)) {\n seen.push(computed);\n result.push(value);\n }\n } else if (!_.contains(result, value)) {\n result.push(value);\n }\n }\n return result;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(flatten(arguments, true, true));\n };\n\n // Produce an array that contains every item shared between all the\n // passed-in arrays.\n _.intersection = function(array) {\n var result = [];\n var argsLength = arguments.length;\n for (var i = 0, length = getLength(array); i < length; i++) {\n var item = array[i];\n if (_.contains(result, item)) continue;\n for (var j = 1; j < argsLength; j++) {\n if (!_.contains(arguments[j], item)) break;\n }\n if (j === argsLength) result.push(item);\n }\n return result;\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = flatten(arguments, true, true, 1);\n return _.filter(array, function(value){\n return !_.contains(rest, value);\n });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function() {\n return _.unzip(arguments);\n };\n\n // Complement of _.zip. Unzip accepts an array of arrays and groups\n // each array's elements on shared indices\n _.unzip = function(array) {\n var length = array && _.max(array, getLength).length || 0;\n var result = Array(length);\n\n for (var index = 0; index < length; index++) {\n result[index] = _.pluck(array, index);\n }\n return result;\n };\n\n // Converts lists into objects. Pass either a single array of `[key, value]`\n // pairs, or two parallel arrays of the same length -- one of keys, and one of\n // the corresponding values.\n _.object = function(list, values) {\n var result = {};\n for (var i = 0, length = getLength(list); i < length; i++) {\n if (values) {\n result[list[i]] = values[i];\n } else {\n result[list[i][0]] = list[i][1];\n }\n }\n return result;\n };\n\n // Generator function to create the findIndex and findLastIndex functions\n function createPredicateIndexFinder(dir) {\n return function(array, predicate, context) {\n predicate = cb(predicate, context);\n var length = getLength(array);\n var index = dir > 0 ? 0 : length - 1;\n for (; index >= 0 && index < length; index += dir) {\n if (predicate(array[index], index, array)) return index;\n }\n return -1;\n };\n }\n\n // Returns the first index on an array-like that passes a predicate test\n _.findIndex = createPredicateIndexFinder(1);\n _.findLastIndex = createPredicateIndexFinder(-1);\n\n // Use a comparator function to figure out the smallest index at which\n // an object should be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iteratee, context) {\n iteratee = cb(iteratee, context, 1);\n var value = iteratee(obj);\n var low = 0, high = getLength(array);\n while (low < high) {\n var mid = Math.floor((low + high) / 2);\n if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;\n }\n return low;\n };\n\n // Generator function to create the indexOf and lastIndexOf functions\n function createIndexFinder(dir, predicateFind, sortedIndex) {\n return function(array, item, idx) {\n var i = 0, length = getLength(array);\n if (typeof idx == 'number') {\n if (dir > 0) {\n i = idx >= 0 ? idx : Math.max(idx + length, i);\n } else {\n length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;\n }\n } else if (sortedIndex && idx && length) {\n idx = sortedIndex(array, item);\n return array[idx] === item ? idx : -1;\n }\n if (item !== item) {\n idx = predicateFind(slice.call(array, i, length), _.isNaN);\n return idx >= 0 ? idx + i : -1;\n }\n for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {\n if (array[idx] === item) return idx;\n }\n return -1;\n };\n }\n\n // Return the position of the first occurrence of an item in an array,\n // or -1 if the item is not included in the array.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);\n _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (stop == null) {\n stop = start || 0;\n start = 0;\n }\n step = step || 1;\n\n var length = Math.max(Math.ceil((stop - start) / step), 0);\n var range = Array(length);\n\n for (var idx = 0; idx < length; idx++, start += step) {\n range[idx] = start;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Determines whether to execute a function as a constructor\n // or a normal function with the provided arguments\n var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {\n if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);\n var self = baseCreate(sourceFunc.prototype);\n var result = sourceFunc.apply(self, args);\n if (_.isObject(result)) return result;\n return self;\n };\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if\n // available.\n _.bind = function(func, context) {\n if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');\n var args = slice.call(arguments, 2);\n var bound = function() {\n return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));\n };\n return bound;\n };\n\n // Partially apply a function by creating a version that has had some of its\n // arguments pre-filled, without changing its dynamic `this` context. _ acts\n // as a placeholder, allowing any combination of arguments to be pre-filled.\n _.partial = function(func) {\n var boundArgs = slice.call(arguments, 1);\n var bound = function() {\n var position = 0, length = boundArgs.length;\n var args = Array(length);\n for (var i = 0; i < length; i++) {\n args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];\n }\n while (position < arguments.length) args.push(arguments[position++]);\n return executeBound(func, bound, this, this, args);\n };\n return bound;\n };\n\n // Bind a number of an object's methods to that object. Remaining arguments\n // are the method names to be bound. Useful for ensuring that all callbacks\n // defined on an object belong to it.\n _.bindAll = function(obj) {\n var i, length = arguments.length, key;\n if (length <= 1) throw new Error('bindAll must be passed function names');\n for (i = 1; i < length; i++) {\n key = arguments[i];\n obj[key] = _.bind(obj[key], obj);\n }\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memoize = function(key) {\n var cache = memoize.cache;\n var address = '' + (hasher ? hasher.apply(this, arguments) : key);\n if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);\n return cache[address];\n };\n memoize.cache = {};\n return memoize;\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){\n return func.apply(null, args);\n }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack has\n // cleared.\n _.defer = _.partial(_.delay, _, 1);\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time. Normally, the throttled function will run\n // as much as it can, without ever going more than once per `wait` duration;\n // but if you'd like to disable the execution on the leading edge, pass\n // `{leading: false}`. To disable execution on the trailing edge, ditto.\n _.throttle = function(func, wait, options) {\n var context, args, result;\n var timeout = null;\n var previous = 0;\n if (!options) options = {};\n var later = function() {\n previous = options.leading === false ? 0 : _.now();\n timeout = null;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n };\n return function() {\n var now = _.now();\n if (!previous && options.leading === false) previous = now;\n var remaining = wait - (now - previous);\n context = this;\n args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(later, remaining);\n }\n return result;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being called for\n // N milliseconds. If `immediate` is passed, trigger the function on the\n // leading edge, instead of the trailing.\n _.debounce = function(func, wait, immediate) {\n var timeout, args, context, timestamp, result;\n\n var later = function() {\n var last = _.now() - timestamp;\n\n if (last < wait && last >= 0) {\n timeout = setTimeout(later, wait - last);\n } else {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n }\n }\n };\n\n return function() {\n context = this;\n args = arguments;\n timestamp = _.now();\n var callNow = immediate && !timeout;\n if (!timeout) timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n context = args = null;\n }\n\n return result;\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return _.partial(wrapper, func);\n };\n\n // Returns a negated version of the passed-in predicate.\n _.negate = function(predicate) {\n return function() {\n return !predicate.apply(this, arguments);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var args = arguments;\n var start = args.length - 1;\n return function() {\n var i = start;\n var result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n };\n\n // Returns a function that will only be executed on and after the Nth call.\n _.after = function(times, func) {\n return function() {\n if (--times < 1) {\n return func.apply(this, arguments);\n }\n };\n };\n\n // Returns a function that will only be executed up to (but not including) the Nth call.\n _.before = function(times, func) {\n var memo;\n return function() {\n if (--times > 0) {\n memo = func.apply(this, arguments);\n }\n if (times <= 1) func = null;\n return memo;\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = _.partial(_.before, 2);\n\n // Object Functions\n // ----------------\n\n // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.\n var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n function collectNonEnumProps(obj, keys) {\n var nonEnumIdx = nonEnumerableProps.length;\n var constructor = obj.constructor;\n var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;\n\n // Constructor is a special case.\n var prop = 'constructor';\n if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);\n\n while (nonEnumIdx--) {\n prop = nonEnumerableProps[nonEnumIdx];\n if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {\n keys.push(prop);\n }\n }\n }\n\n // Retrieve the names of an object's own properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = function(obj) {\n if (!_.isObject(obj)) return [];\n if (nativeKeys) return nativeKeys(obj);\n var keys = [];\n for (var key in obj) if (_.has(obj, key)) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve all the property names of an object.\n _.allKeys = function(obj) {\n if (!_.isObject(obj)) return [];\n var keys = [];\n for (var key in obj) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var values = Array(length);\n for (var i = 0; i < length; i++) {\n values[i] = obj[keys[i]];\n }\n return values;\n };\n\n // Returns the results of applying the iteratee to each element of the object\n // In contrast to _.map it returns an object\n _.mapObject = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = _.keys(obj),\n length = keys.length,\n results = {},\n currentKey;\n for (var index = 0; index < length; index++) {\n currentKey = keys[index];\n results[currentKey] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Convert an object into a list of `[key, value]` pairs.\n _.pairs = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var pairs = Array(length);\n for (var i = 0; i < length; i++) {\n pairs[i] = [keys[i], obj[keys[i]]];\n }\n return pairs;\n };\n\n // Invert the keys and values of an object. The values must be serializable.\n _.invert = function(obj) {\n var result = {};\n var keys = _.keys(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n result[obj[keys[i]]] = keys[i];\n }\n return result;\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = createAssigner(_.allKeys);\n\n // Assigns a given object with all the own properties in the passed-in object(s)\n // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n _.extendOwn = _.assign = createAssigner(_.keys);\n\n // Returns the first key on an object that passes a predicate test\n _.findKey = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = _.keys(obj), key;\n for (var i = 0, length = keys.length; i < length; i++) {\n key = keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n };\n\n // Return a copy of the object only containing the whitelisted properties.\n _.pick = function(object, oiteratee, context) {\n var result = {}, obj = object, iteratee, keys;\n if (obj == null) return result;\n if (_.isFunction(oiteratee)) {\n keys = _.allKeys(obj);\n iteratee = optimizeCb(oiteratee, context);\n } else {\n keys = flatten(arguments, false, false, 1);\n iteratee = function(value, key, obj) { return key in obj; };\n obj = Object(obj);\n }\n for (var i = 0, length = keys.length; i < length; i++) {\n var key = keys[i];\n var value = obj[key];\n if (iteratee(value, key, obj)) result[key] = value;\n }\n return result;\n };\n\n // Return a copy of the object without the blacklisted properties.\n _.omit = function(obj, iteratee, context) {\n if (_.isFunction(iteratee)) {\n iteratee = _.negate(iteratee);\n } else {\n var keys = _.map(flatten(arguments, false, false, 1), String);\n iteratee = function(value, key) {\n return !_.contains(keys, key);\n };\n }\n return _.pick(obj, iteratee, context);\n };\n\n // Fill in a given object with default properties.\n _.defaults = createAssigner(_.allKeys, true);\n\n // Creates an object that inherits from the given prototype object.\n // If additional properties are provided then they will be added to the\n // created object.\n _.create = function(prototype, props) {\n var result = baseCreate(prototype);\n if (props) _.extendOwn(result, props);\n return result;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Returns whether an object has a given set of `key:value` pairs.\n _.isMatch = function(object, attrs) {\n var keys = _.keys(attrs), length = keys.length;\n if (object == null) return !length;\n var obj = Object(object);\n for (var i = 0; i < length; i++) {\n var key = keys[i];\n if (attrs[key] !== obj[key] || !(key in obj)) return false;\n }\n return true;\n };\n\n\n // Internal recursive comparison function for `isEqual`.\n var eq = function(a, b, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) return a !== 0 || 1 / a === 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwrap any wrapped objects.\n if (a instanceof _) a = a._wrapped;\n if (b instanceof _) b = b._wrapped;\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case '[object RegExp]':\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return '' + a === '' + b;\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN\n if (+a !== +a) return +b !== +b;\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case '[object Date]':\n case '[object Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n }\n\n var areArrays = className === '[object Array]';\n if (!areArrays) {\n if (typeof a != 'object' || typeof b != 'object') return false;\n\n // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n var aCtor = a.constructor, bCtor = b.constructor;\n if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&\n _.isFunction(bCtor) && bCtor instanceof bCtor)\n && ('constructor' in a && 'constructor' in b)) {\n return false;\n }\n }\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) return bStack[length] === b;\n }\n\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n\n // Recursively compare objects and arrays.\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n if (length !== b.length) return false;\n // Deep compare the contents, ignoring non-numeric properties.\n while (length--) {\n if (!eq(a[length], b[length], aStack, bStack)) return false;\n }\n } else {\n // Deep compare objects.\n var keys = _.keys(a), key;\n length = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n if (_.keys(b).length !== length) return false;\n while (length--) {\n // Deep compare each member\n key = keys[length];\n if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return true;\n };\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (obj == null) return true;\n if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;\n return _.keys(obj).length === 0;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj.nodeType === 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) === '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n var type = typeof obj;\n return type === 'function' || type === 'object' && !!obj;\n };\n\n // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.\n _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {\n _['is' + name] = function(obj) {\n return toString.call(obj) === '[object ' + name + ']';\n };\n });\n\n // Define a fallback version of the method in browsers (ahem, IE < 9), where\n // there isn't any inspectable \"Arguments\" type.\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return _.has(obj, 'callee');\n };\n }\n\n // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,\n // IE 11 (#1621), and in Safari 8 (#1929).\n if (typeof /./ != 'function' && typeof Int8Array != 'object') {\n _.isFunction = function(obj) {\n return typeof obj == 'function' || false;\n };\n }\n\n // Is a given object a finite number?\n _.isFinite = function(obj) {\n return isFinite(obj) && !isNaN(parseFloat(obj));\n };\n\n // Is the given value `NaN`? (NaN is the only number which does not equal itself).\n _.isNaN = function(obj) {\n return _.isNumber(obj) && obj !== +obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) === '[object Boolean]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Shortcut function for checking if an object has a given property directly\n // on itself (in other words, not on a prototype).\n _.has = function(obj, key) {\n return obj != null && hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning the `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iteratees.\n _.identity = function(value) {\n return value;\n };\n\n // Predicate-generating functions. Often useful outside of Underscore.\n _.constant = function(value) {\n return function() {\n return value;\n };\n };\n\n _.noop = function(){};\n\n _.property = property;\n\n // Generates a function for a given object that returns a given property.\n _.propertyOf = function(obj) {\n return obj == null ? function(){} : function(key) {\n return obj[key];\n };\n };\n\n // Returns a predicate for checking whether an object has a given set of\n // `key:value` pairs.\n _.matcher = _.matches = function(attrs) {\n attrs = _.extendOwn({}, attrs);\n return function(obj) {\n return _.isMatch(obj, attrs);\n };\n };\n\n // Run a function **n** times.\n _.times = function(n, iteratee, context) {\n var accum = Array(Math.max(0, n));\n iteratee = optimizeCb(iteratee, context, 1);\n for (var i = 0; i < n; i++) accum[i] = iteratee(i);\n return accum;\n };\n\n // Return a random integer between min and max (inclusive).\n _.random = function(min, max) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n };\n\n // A (possibly faster) way to get the current timestamp as an integer.\n _.now = Date.now || function() {\n return new Date().getTime();\n };\n\n // List of HTML entities for escaping.\n var escapeMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`'\n };\n var unescapeMap = _.invert(escapeMap);\n\n // Functions for escaping and unescaping strings to/from HTML interpolation.\n var createEscaper = function(map) {\n var escaper = function(match) {\n return map[match];\n };\n // Regexes for identifying a key that needs to be escaped\n var source = '(?:' + _.keys(map).join('|') + ')';\n var testRegexp = RegExp(source);\n var replaceRegexp = RegExp(source, 'g');\n return function(string) {\n string = string == null ? '' : '' + string;\n return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;\n };\n };\n _.escape = createEscaper(escapeMap);\n _.unescape = createEscaper(unescapeMap);\n\n // If the value of the named `property` is a function then invoke it with the\n // `object` as context; otherwise, return it.\n _.result = function(object, property, fallback) {\n var value = object == null ? void 0 : object[property];\n if (value === void 0) {\n value = fallback;\n }\n return _.isFunction(value) ? value.call(object) : value;\n };\n\n // Generate a unique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = ++idCounter + '';\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /(.)^/;\n\n // Certain characters need to be escaped so that they can be put into a\n // string literal.\n var escapes = {\n \"'\": \"'\",\n '\\\\': '\\\\',\n '\\r': 'r',\n '\\n': 'n',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n var escaper = /\\\\|'|\\r|\\n|\\u2028|\\u2029/g;\n\n var escapeChar = function(match) {\n return '\\\\' + escapes[match];\n };\n\n // JavaScript micro-templating, similar to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n // NB: `oldSettings` only exists for backwards compatibility.\n _.template = function(text, settings, oldSettings) {\n if (!settings && oldSettings) settings = oldSettings;\n settings = _.defaults({}, settings, _.templateSettings);\n\n // Combine delimiters into one regular expression via alternation.\n var matcher = RegExp([\n (settings.escape || noMatch).source,\n (settings.interpolate || noMatch).source,\n (settings.evaluate || noMatch).source\n ].join('|') + '|$', 'g');\n\n // Compile the template source, escaping string literals appropriately.\n var index = 0;\n var source = \"__p+='\";\n text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {\n source += text.slice(index, offset).replace(escaper, escapeChar);\n index = offset + match.length;\n\n if (escape) {\n source += \"'+\\n((__t=(\" + escape + \"))==null?'':_.escape(__t))+\\n'\";\n } else if (interpolate) {\n source += \"'+\\n((__t=(\" + interpolate + \"))==null?'':__t)+\\n'\";\n } else if (evaluate) {\n source += \"';\\n\" + evaluate + \"\\n__p+='\";\n }\n\n // Adobe VMs need the match returned to produce the correct offest.\n return match;\n });\n source += \"';\\n\";\n\n // If a variable is not specified, place data values in local scope.\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = \"var __t,__p='',__j=Array.prototype.join,\" +\n \"print=function(){__p+=__j.call(arguments,'');};\\n\" +\n source + 'return __p;\\n';\n\n try {\n var render = new Function(settings.variable || 'obj', '_', source);\n } catch (e) {\n e.source = source;\n throw e;\n }\n\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n // Provide the compiled source as a convenience for precompilation.\n var argument = settings.variable || 'obj';\n template.source = 'function(' + argument + '){\\n' + source + '}';\n\n return template;\n };\n\n // Add a \"chain\" function. Start chaining a wrapped Underscore object.\n _.chain = function(obj) {\n var instance = _(obj);\n instance._chain = true;\n return instance;\n };\n\n // OOP\n // ---------------\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n\n // Helper function to continue chaining intermediate results.\n var result = function(instance, obj) {\n return instance._chain ? _(obj).chain() : obj;\n };\n\n // Add your own custom functions to the Underscore object.\n _.mixin = function(obj) {\n _.each(_.functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return result(this, func.apply(_, args));\n };\n });\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n var obj = this._wrapped;\n method.apply(obj, arguments);\n if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];\n return result(this, obj);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n _.each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n return result(this, method.apply(this._wrapped, arguments));\n };\n });\n\n // Extracts the result from a wrapped and chained object.\n _.prototype.value = function() {\n return this._wrapped;\n };\n\n // Provide unwrapping proxy for some methods used in engine operations\n // such as arithmetic and JSON stringification.\n _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;\n\n _.prototype.toString = function() {\n return '' + this._wrapped;\n };\n\n // AMD registration happens at the end for compatibility with AMD loaders\n // that may not enforce next-turn semantics on modules. Even though general\n // practice for AMD registration is to be anonymous, underscore registers\n // as a named module because, like jQuery, it is a base library that is\n // popular enough to be bundled in a third party lib, but not be part of\n // an AMD load request. Those cases could generate an error when an\n // anonymous define() is called outside of a loader request.\n if (typeof define === 'function' && define.amd) {\n define('underscore', [], function() {\n return _;\n });\n }\n}.call(this));\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/underscore/underscore.js\n// module id = 0\n// module chunks = 0","var _ = require('underscore');\nvar Promise = require('es6-promise').Promise;\n\nPromise._continueWhile = function(predicate, asyncFunction) {\n if (predicate()) {\n return asyncFunction().then(function() {\n return Promise._continueWhile(predicate, asyncFunction);\n });\n }\n return Promise.resolve();\n};\n\nmodule.exports = Promise;\n\n\n\n// WEBPACK FOOTER //\n// ./src/promise.js","const request = require('superagent');\nconst debug = require('debug')('leancloud:request');\nconst md5 = require('md5');\nconst Promise = require('./promise');\nconst Cache = require('./cache');\nconst AVError = require('./error');\nconst AV = require('./av');\nconst _ = require('underscore');\nconst {\n getSessionToken,\n} = require('./utils');\n\nlet getServerURLPromise;\n\n// 服务器请求的节点 host\nconst API_HOST = {\n cn: 'https://api.leancloud.cn',\n us: 'https://us-api.leancloud.cn',\n};\n\n// 计算 X-LC-Sign 的签名方法\nconst sign = (key, isMasterKey) => {\n const now = new Date().getTime();\n const signature = md5(now + key);\n if (isMasterKey) {\n return `${signature},${now},master`;\n }\n return `${signature},${now}`;\n};\n\nlet requestsCount = 0;\n\nconst ajax = (method, resourceUrl, data, headers = {}, onprogress) => {\n const count = requestsCount++;\n\n debug(`request(${count})`, method, resourceUrl, data, headers);\n\n return new Promise((resolve, reject) => {\n const req = request(method, resourceUrl)\n .set(headers)\n .send(data);\n if (onprogress) {\n req.on('progress', onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(`response(${count})`, res.status, res.body || res.text, res.header);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n return resolve(res.body);\n });\n });\n};\n\nconst setAppKey = (headers, signKey) => {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.applicationKey);\n } else {\n headers['X-LC-Key'] = AV.applicationKey;\n }\n};\n\nconst setHeaders = (authOptions = {}, signKey) => {\n const headers = {\n 'X-LC-Id': AV.applicationId,\n 'Content-Type': 'application/json;charset=UTF-8',\n };\n let useMasterKey = false;\n if (typeof authOptions.useMasterKey === 'boolean') {\n useMasterKey = authOptions.useMasterKey;\n } else if (typeof AV._useMasterKey === 'boolean') {\n useMasterKey = AV._useMasterKey;\n }\n if (useMasterKey) {\n if (AV.masterKey) {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.masterKey, true);\n } else {\n headers['X-LC-Key'] = `${AV.masterKey},master`;\n }\n } else {\n console.warn('masterKey is not set, fall back to use appKey');\n setAppKey(headers, signKey);\n }\n } else {\n setAppKey(headers, signKey);\n }\n if (AV.hookKey) {\n headers['X-LC-Hook-Key'] = AV.hookKey;\n }\n if (AV._config.applicationProduction !== null) {\n headers['X-LC-Prod'] = String(AV._config.applicationProduction);\n }\n headers[!process.env.CLIENT_PLATFORM ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent;\n\n return Promise.resolve().then(() => {\n // Pass the session token\n const sessionToken = getSessionToken(authOptions);\n if (sessionToken) {\n headers['X-LC-Session'] = sessionToken;\n } else if (!AV._config.disableCurrentUser) {\n return AV.User.currentAsync().then((currentUser) => {\n if (currentUser && currentUser._sessionToken) {\n headers['X-LC-Session'] = currentUser._sessionToken;\n }\n return headers;\n });\n }\n return headers;\n });\n};\n\nconst createApiUrl = (route, className, objectId, method, dataObject) => {\n // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉\n if (AV.serverURL) {\n AV._config.APIServerURL = AV.serverURL;\n console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.');\n }\n\n let apiURL = AV._config.APIServerURL || API_HOST.cn;\n\n if (apiURL.charAt(apiURL.length - 1) !== '/') {\n apiURL += '/';\n }\n apiURL += `1.1/${route}`;\n if (className) {\n apiURL += `/${className}`;\n }\n if (objectId) {\n apiURL += `/${objectId}`;\n }\n if ((route === 'users' || route === 'classes') && dataObject) {\n apiURL += '?';\n if (dataObject._fetchWhenSave) {\n delete dataObject._fetchWhenSave;\n apiURL += '&new=true';\n }\n if (dataObject._where) {\n apiURL += `&where=${encodeURIComponent(JSON.stringify(dataObject._where))}`;\n delete dataObject._where;\n }\n }\n\n if (method.toLowerCase() === 'get') {\n if (apiURL.indexOf('?') === -1) {\n apiURL += '?';\n }\n for (const k in dataObject) {\n if (typeof dataObject[k] === 'object') {\n dataObject[k] = JSON.stringify(dataObject[k]);\n }\n apiURL += `&${k}=${encodeURIComponent(dataObject[k])}`;\n }\n }\n\n return apiURL;\n};\n\nconst cacheServerURL = (serverURL, ttl) => {\n if (typeof ttl !== 'number') {\n ttl = 3600;\n }\n return Cache.setAsync('APIServerURL', serverURL, ttl * 1000);\n};\n\n// handle AV._request Error\nconst handleError = (error) => {\n return new Promise((resolve, reject) => {\n /**\n When API request need to redirect to the right location,\n can't use browser redirect by http status 307, as the reason of CORS,\n so API server response http status 410 and the param \"location\" for this case.\n */\n if (error.statusCode === 410) {\n cacheServerURL(error.response.api_server, error.response.ttl).then(() => {\n resolve(error.response.location);\n }).catch(reject);\n } else {\n let errorJSON = {\n code: error.code || -1,\n error: error.message || error.responseText\n };\n if (error.response && error.response.code) {\n errorJSON = error.response;\n } else if (error.responseText) {\n try {\n errorJSON = JSON.parse(error.responseText);\n } catch (e) {\n // If we fail to parse the error text, that's okay.\n }\n }\n\n // Transform the error into an instance of AVError by trying to parse\n // the error string as JSON.\n reject(new AVError(errorJSON.code, errorJSON.error));\n }\n });\n};\n\nconst setServerUrl = (serverURL) => {\n AV._config.APIServerURL = `https://${serverURL}`;\n\n // 根据新 URL 重新设置区域\n const newRegion = _.findKey(API_HOST, item => item === AV._config.APIServerURL);\n if (newRegion) {\n AV._config.region = newRegion;\n }\n};\n\nconst refreshServerUrlByRouter = () => {\n const url = `https://app-router.leancloud.cn/1/route?appId=${AV.applicationId}`;\n return ajax('get', url).then(servers => {\n if (servers.api_server) {\n setServerUrl(servers.api_server);\n return cacheServerURL(servers.api_server, servers.ttl);\n }\n }, error => {\n // bypass all non-4XX errors\n if (error.statusCode >= 400 && error.statusCode < 500) {\n throw error;\n }\n });\n};\n\nconst setServerUrlByRegion = (region = 'cn') => {\n getServerURLPromise = new Promise((resolve, reject) => {\n // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router\n if (AV._config.APIServerURL) {\n resolve();\n return;\n }\n // if not china server region, do not use router\n if (region === 'cn') {\n return Cache.getAsync('APIServerURL').then((serverURL) => {\n if (serverURL) {\n setServerUrl(serverURL);\n } else {\n return refreshServerUrlByRouter();\n }\n }).then(() => {\n resolve();\n }).catch((error) => {\n reject(error);\n });\n } else {\n AV._config.region = region;\n AV._config.APIServerURL = API_HOST[region];\n resolve();\n }\n });\n};\n\n/**\n * route is classes, users, login, etc.\n * objectId is null if there is no associated objectId.\n * method is the http method for the REST API.\n * dataObject is the payload as an object, or null if there is none.\n * @ignore\n */\nconst AVRequest = (route, className, objectId, method, dataObject = {}, authOptions) => {\n if (!AV.applicationId) {\n throw new Error('You must specify your applicationId using AV.init()');\n }\n\n if (!AV.applicationKey && !AV.masterKey) {\n throw new Error('You must specify a AppKey using AV.init()');\n }\n\n if (!getServerURLPromise) {\n return Promise.reject(new Error('Not initialized'));\n }\n return getServerURLPromise.then(() => {\n const apiURL = createApiUrl(route, className, objectId, method, dataObject);\n return setHeaders(authOptions, route !== 'bigquery').then(\n headers => ajax(method, apiURL, dataObject, headers)\n .then(\n null,\n res => handleError(res)\n .then(location => ajax(method, location, dataObject, headers))\n )\n );\n });\n};\n\nmodule.exports = {\n ajax,\n request: AVRequest,\n setServerUrlByRegion,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/request.js","const _ = require('underscore');\n\n/**\n * @class AV.Error\n */\n\nfunction AVError(code, message) {\n const error = new Error(message);\n error.code = code;\n return error;\n}\n\n_.extend(AVError, /** @lends AV.Error */ {\n /**\n * Error code indicating some error other than those enumerated here.\n * @constant\n */\n OTHER_CAUSE: -1,\n\n /**\n * Error code indicating that something has gone wrong with the server.\n * If you get this error code, it is AV's fault. Contact us at\n * https://avoscloud.com/help\n * @constant\n */\n INTERNAL_SERVER_ERROR: 1,\n\n /**\n * Error code indicating the connection to the AV servers failed.\n * @constant\n */\n CONNECTION_FAILED: 100,\n\n /**\n * Error code indicating the specified object doesn't exist.\n * @constant\n */\n OBJECT_NOT_FOUND: 101,\n\n /**\n * Error code indicating you tried to query with a datatype that doesn't\n * support it, like exact matching an array or object.\n * @constant\n */\n INVALID_QUERY: 102,\n\n /**\n * Error code indicating a missing or invalid classname. Classnames are\n * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the\n * only valid characters.\n * @constant\n */\n INVALID_CLASS_NAME: 103,\n\n /**\n * Error code indicating an unspecified object id.\n * @constant\n */\n MISSING_OBJECT_ID: 104,\n\n /**\n * Error code indicating an invalid key name. Keys are case-sensitive. They\n * must start with a letter, and a-zA-Z0-9_ are the only valid characters.\n * @constant\n */\n INVALID_KEY_NAME: 105,\n\n /**\n * Error code indicating a malformed pointer. You should not see this unless\n * you have been mucking about changing internal AV code.\n * @constant\n */\n INVALID_POINTER: 106,\n\n /**\n * Error code indicating that badly formed JSON was received upstream. This\n * either indicates you have done something unusual with modifying how\n * things encode to JSON, or the network is failing badly.\n * @constant\n */\n INVALID_JSON: 107,\n\n /**\n * Error code indicating that the feature you tried to access is only\n * available internally for testing purposes.\n * @constant\n */\n COMMAND_UNAVAILABLE: 108,\n\n /**\n * You must call AV.initialize before using the AV library.\n * @constant\n */\n NOT_INITIALIZED: 109,\n\n /**\n * Error code indicating that a field was set to an inconsistent type.\n * @constant\n */\n INCORRECT_TYPE: 111,\n\n /**\n * Error code indicating an invalid channel name. A channel name is either\n * an empty string (the broadcast channel) or contains only a-zA-Z0-9_\n * characters.\n * @constant\n */\n INVALID_CHANNEL_NAME: 112,\n\n /**\n * Error code indicating that push is misconfigured.\n * @constant\n */\n PUSH_MISCONFIGURED: 115,\n\n /**\n * Error code indicating that the object is too large.\n * @constant\n */\n OBJECT_TOO_LARGE: 116,\n\n /**\n * Error code indicating that the operation isn't allowed for clients.\n * @constant\n */\n OPERATION_FORBIDDEN: 119,\n\n /**\n * Error code indicating the result was not found in the cache.\n * @constant\n */\n CACHE_MISS: 120,\n\n /**\n * Error code indicating that an invalid key was used in a nested\n * JSONObject.\n * @constant\n */\n INVALID_NESTED_KEY: 121,\n\n /**\n * Error code indicating that an invalid filename was used for AVFile.\n * A valid file name contains only a-zA-Z0-9_. characters and is between 1\n * and 128 characters.\n * @constant\n */\n INVALID_FILE_NAME: 122,\n\n /**\n * Error code indicating an invalid ACL was provided.\n * @constant\n */\n INVALID_ACL: 123,\n\n /**\n * Error code indicating that the request timed out on the server. Typically\n * this indicates that the request is too expensive to run.\n * @constant\n */\n TIMEOUT: 124,\n\n /**\n * Error code indicating that the email address was invalid.\n * @constant\n */\n INVALID_EMAIL_ADDRESS: 125,\n\n /**\n * Error code indicating a missing content type.\n * @constant\n */\n MISSING_CONTENT_TYPE: 126,\n\n /**\n * Error code indicating a missing content length.\n * @constant\n */\n MISSING_CONTENT_LENGTH: 127,\n\n /**\n * Error code indicating an invalid content length.\n * @constant\n */\n INVALID_CONTENT_LENGTH: 128,\n\n /**\n * Error code indicating a file that was too large.\n * @constant\n */\n FILE_TOO_LARGE: 129,\n\n /**\n * Error code indicating an error saving a file.\n * @constant\n */\n FILE_SAVE_ERROR: 130,\n\n /**\n * Error code indicating an error deleting a file.\n * @constant\n */\n FILE_DELETE_ERROR: 153,\n\n /**\n * Error code indicating that a unique field was given a value that is\n * already taken.\n * @constant\n */\n DUPLICATE_VALUE: 137,\n\n /**\n * Error code indicating that a role's name is invalid.\n * @constant\n */\n INVALID_ROLE_NAME: 139,\n\n /**\n * Error code indicating that an application quota was exceeded. Upgrade to\n * resolve.\n * @constant\n */\n EXCEEDED_QUOTA: 140,\n\n /**\n * Error code indicating that a Cloud Code script failed.\n * @constant\n */\n SCRIPT_FAILED: 141,\n\n /**\n * Error code indicating that a Cloud Code validation failed.\n * @constant\n */\n VALIDATION_ERROR: 142,\n\n /**\n * Error code indicating that invalid image data was provided.\n * @constant\n */\n INVALID_IMAGE_DATA: 150,\n\n /**\n * Error code indicating an unsaved file.\n * @constant\n */\n UNSAVED_FILE_ERROR: 151,\n\n /**\n * Error code indicating an invalid push time.\n */\n INVALID_PUSH_TIME_ERROR: 152,\n\n /**\n * Error code indicating that the username is missing or empty.\n * @constant\n */\n USERNAME_MISSING: 200,\n\n /**\n * Error code indicating that the password is missing or empty.\n * @constant\n */\n PASSWORD_MISSING: 201,\n\n /**\n * Error code indicating that the username has already been taken.\n * @constant\n */\n USERNAME_TAKEN: 202,\n\n /**\n * Error code indicating that the email has already been taken.\n * @constant\n */\n EMAIL_TAKEN: 203,\n\n /**\n * Error code indicating that the email is missing, but must be specified.\n * @constant\n */\n EMAIL_MISSING: 204,\n\n /**\n * Error code indicating that a user with the specified email was not found.\n * @constant\n */\n EMAIL_NOT_FOUND: 205,\n\n /**\n * Error code indicating that a user object without a valid session could\n * not be altered.\n * @constant\n */\n SESSION_MISSING: 206,\n\n /**\n * Error code indicating that a user can only be created through signup.\n * @constant\n */\n MUST_CREATE_USER_THROUGH_SIGNUP: 207,\n\n /**\n * Error code indicating that an an account being linked is already linked\n * to another user.\n * @constant\n */\n ACCOUNT_ALREADY_LINKED: 208,\n\n /**\n * Error code indicating that a user cannot be linked to an account because\n * that account's id could not be found.\n * @constant\n */\n LINKED_ID_MISSING: 250,\n\n /**\n * Error code indicating that a user with a linked (e.g. Facebook) account\n * has an invalid session.\n * @constant\n */\n INVALID_LINKED_SESSION: 251,\n\n /**\n * Error code indicating that a service being linked (e.g. Facebook or\n * Twitter) is unsupported.\n * @constant\n */\n UNSUPPORTED_SERVICE: 252,\n /**\n * Error code indicating a real error code is unavailable because\n * we had to use an XDomainRequest object to allow CORS requests in\n * Internet Explorer, which strips the body from HTTP responses that have\n * a non-2XX status code.\n * @constant\n */\n X_DOMAIN_REQUEST: 602,\n});\n\nmodule.exports = AVError;\n\n\n\n// WEBPACK FOOTER //\n// ./src/error.js","const _ = require('underscore');\n\n// Helper function to check null or undefined.\nconst isNullOrUndefined = (x) => _.isNull(x) || _.isUndefined(x);\n\nconst ensureArray = target => {\n if (_.isArray(target)) {\n return target;\n }\n if (target === undefined || target === null) {\n return [];\n }\n return [target];\n};\n\nconst getSessionToken = (authOptions) => {\n if (authOptions.sessionToken) {\n return authOptions.sessionToken;\n }\n if (\n authOptions.user && typeof authOptions.user.getSessionToken === 'function'\n ) {\n return authOptions.user.getSessionToken();\n }\n};\n\nconst tap = interceptor => value => ((interceptor(value), value));\n\nmodule.exports = {\n isNullOrUndefined,\n ensureArray,\n getSessionToken,\n tap,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/index.js","/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n 'lightseagreen',\n 'forestgreen',\n 'goldenrod',\n 'dodgerblue',\n 'darkorchid',\n 'crimson'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/browser.js\n// module id = 5\n// module chunks = 0","const _ = require('underscore');\nconst userAgent = require('./ua');\nconst {\n isNullOrUndefined,\n} = require('./utils');\n\nconst AV = global.AV || {};\n\n// All internal configuration items\nAV._config = AV._config || {};\nconst AVConfig = AV._config;\n\n_.extend(AVConfig, {\n\n // 服务器节点地区,默认中国大陆\n region: 'cn',\n\n // 服务器的 URL,默认初始化时被设置为大陆节点地址\n APIServerURL: AVConfig.APIServerURL || '',\n\n // 禁用 currentUser,通常用于多用户环境\n disableCurrentUser: false,\n\n // Internal config can modifie the UserAgent\n userAgent,\n\n // set production environment or test environment\n // 1: production environment, 0: test environment, null: default environment\n applicationProduction: null,\n});\n\n/**\n * Contains all AV API classes and functions.\n * @namespace AV\n */\n\n// Helpers\n// -------\n\n// Shared empty constructor function to aid in prototype-chain creation.\nvar EmptyConstructor = function() {};\n\n// Helper function to correctly set up the prototype chain, for subclasses.\n// Similar to `goog.inherits`, but uses a hash of prototype properties and\n// class properties to be extended.\nvar inherits = function(parent, protoProps, staticProps) {\n var child;\n\n // The constructor function for the new subclass is either defined by you\n // (the \"constructor\" property in your `extend` definition), or defaulted\n // by us to simply call the parent's constructor.\n if (protoProps && protoProps.hasOwnProperty('constructor')) {\n child = protoProps.constructor;\n } else {\n /** @ignore */\n child = function(){ parent.apply(this, arguments); };\n }\n\n // Inherit class (static) properties from parent.\n _.extend(child, parent);\n\n // Set the prototype chain to inherit from `parent`, without calling\n // `parent`'s constructor function.\n EmptyConstructor.prototype = parent.prototype;\n child.prototype = new EmptyConstructor();\n\n // Add prototype properties (instance properties) to the subclass,\n // if supplied.\n if (protoProps) {\n _.extend(child.prototype, protoProps);\n }\n\n // Add static properties to the constructor function, if supplied.\n if (staticProps) {\n _.extend(child, staticProps);\n }\n\n // Correctly set child's `prototype.constructor`.\n child.prototype.constructor = child;\n\n // Set a convenience property in case the parent's prototype is\n // needed later.\n child.__super__ = parent.prototype;\n\n return child;\n};\n\n/**\n * Call this method to set production environment variable.\n * @function AV.setProduction\n * @param {Boolean} production True is production environment,and\n * it's true by default.\n */\nAV.setProduction = (production) => {\n if (!isNullOrUndefined(production)) {\n AVConfig.applicationProduction = production ? 1 : 0;\n } else {\n // change to default value\n AVConfig.applicationProduction = null;\n }\n};\n\n/**\n * Returns prefix for localStorage keys used by this instance of AV.\n * @param {String} path The relative suffix to append to it.\n * null or undefined is treated as the empty string.\n * @return {String} The full key name.\n * @private\n */\nAV._getAVPath = function(path) {\n if (!AV.applicationId) {\n throw new Error(\"You need to call AV.initialize before using AV.\");\n }\n if (!path) {\n path = \"\";\n }\n if (!_.isString(path)) {\n throw new Error(\"Tried to get a localStorage path that wasn't a String.\");\n }\n if (path[0] === \"/\") {\n path = path.substring(1);\n }\n return \"AV/\" + AV.applicationId + \"/\" + path;\n};\n\n/**\n * Returns the unique string for this app on this machine.\n * Gets reset when localStorage is cleared.\n * @private\n */\nAV._installationId = null;\nAV._getInstallationId = function() {\n // See if it's cached in RAM.\n if (AV._installationId) {\n return AV.Promise.resolve(AV._installationId);\n }\n\n // Try to get it from localStorage.\n var path = AV._getAVPath(\"installationId\");\n return AV.localStorage.getItemAsync(path).then(function(_installationId){\n AV._installationId = _installationId;\n if (!AV._installationId) {\n // It wasn't in localStorage, so create a new one.\n var hexOctet = function() {\n return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);\n };\n AV._installationId = (\n hexOctet() + hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + hexOctet() + hexOctet());\n return AV.localStorage.setItemAsync(path, AV._installationId);\n }\n else {\n return _installationId;\n }\n });\n};\n\nAV._parseDate = function(iso8601) {\n var regexp = new RegExp(\n \"^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})\" + \"T\" +\n \"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\" +\n \"(.([0-9]+))?\" + \"Z$\");\n var match = regexp.exec(iso8601);\n if (!match) {\n return null;\n }\n\n var year = match[1] || 0;\n var month = (match[2] || 1) - 1;\n var day = match[3] || 0;\n var hour = match[4] || 0;\n var minute = match[5] || 0;\n var second = match[6] || 0;\n var milli = match[8] || 0;\n\n return new Date(Date.UTC(year, month, day, hour, minute, second, milli));\n};\n\n// A self-propagating extend function.\nAV._extend = function(protoProps, classProps) {\n var child = inherits(this, protoProps, classProps);\n child.extend = this.extend;\n return child;\n};\n\n// Helper function to get a value from a Backbone object as a property\n// or as a function.\nAV._getValue = function(object, prop) {\n if (!(object && object[prop])) {\n return null;\n }\n return _.isFunction(object[prop]) ? object[prop]() : object[prop];\n};\n\n/**\n * Converts a value in a AV Object into the appropriate representation.\n * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object)\n * if seenObjects is falsey. Otherwise any AV.Objects not in\n * seenObjects will be fully embedded rather than encoded\n * as a pointer. This array will be used to prevent going into an infinite\n * loop because we have circular references. If \n * is set, then none of the AV Objects that are serialized can be dirty.\n * @private\n */\nAV._encode = function(value, seenObjects, disallowObjects) {\n if (value instanceof AV.Object) {\n if (disallowObjects) {\n throw new Error(\"AV.Objects not allowed here\");\n }\n if (!seenObjects || _.include(seenObjects, value) || !value._hasData) {\n return value._toPointer();\n }\n if (!value.dirty()) {\n seenObjects = seenObjects.concat(value);\n return AV._encode(value._toFullJSON(seenObjects),\n seenObjects,\n disallowObjects);\n }\n throw new Error(\"Tried to save an object with a pointer to a new, unsaved object.\");\n }\n if (value instanceof AV.ACL) {\n return value.toJSON();\n }\n if (_.isDate(value)) {\n return { \"__type\": \"Date\", \"iso\": value.toJSON() };\n }\n if (value instanceof AV.GeoPoint) {\n return value.toJSON();\n }\n if (_.isArray(value)) {\n return _.map(value, function(x) {\n return AV._encode(x, seenObjects, disallowObjects);\n });\n }\n if (_.isRegExp(value)) {\n return value.source;\n }\n if (value instanceof AV.Relation) {\n return value.toJSON();\n }\n if (value instanceof AV.Op) {\n return value.toJSON();\n }\n if (value instanceof AV.File) {\n if (!value.url() && !value.id) {\n throw new Error(\"Tried to save an object containing an unsaved file.\");\n }\n return value._toFullJSON();\n }\n if (_.isObject(value)) {\n return _.mapObject(value, (v, k) => AV._encode(v, seenObjects, disallowObjects));\n }\n return value;\n};\n\n/**\n * The inverse function of AV._encode.\n * @private\n */\nAV._decode = function(value, key) {\n if (!_.isObject(value) || _.isDate(value)) {\n return value;\n }\n if (_.isArray(value)) {\n return _.map(value, v => AV._decode(v));\n }\n if (value instanceof AV.Object) {\n return value;\n }\n if (value instanceof AV.File) {\n return value;\n }\n if (value instanceof AV.Op) {\n return value;\n }\n if (value instanceof AV.GeoPoint) {\n return value;\n }\n if (value instanceof AV.ACL) {\n return value;\n }\n if (key === 'ACL') {\n return new AV.ACL(value);\n }\n if (value.__op) {\n return AV.Op._decode(value);\n }\n var className;\n if (value.__type === \"Pointer\") {\n className = value.className;\n var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n if(Object.keys(value).length > 3) {\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n pointer._finishFetch(v, true);\n }else{\n pointer._finishFetch({ objectId: value.objectId }, false);\n }\n return pointer;\n }\n if (value.__type === \"Object\") {\n // It's an Object included in a query result.\n className = value.className;\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n object._finishFetch(v, true);\n return object;\n }\n if (value.__type === \"Date\") {\n return AV._parseDate(value.iso);\n }\n if (value.__type === \"GeoPoint\") {\n return new AV.GeoPoint({\n latitude: value.latitude,\n longitude: value.longitude\n });\n }\n if (value.__type === \"Relation\") {\n if (!key) throw new Error('key missing decoding a Relation');\n var relation = new AV.Relation(null, key);\n relation.targetClassName = value.className;\n return relation;\n }\n if (value.__type === 'File') {\n var file = new AV.File(value.name);\n const v = _.clone(value);\n delete v.__type;\n file._finishFetch(v);\n return file;\n }\n return _.mapObject(value, AV._decode);\n};\n\nAV._encodeObjectOrArray = function(value) {\n var encodeAVObject = function(object) {\n if (object && object._toFullJSON){\n object = object._toFullJSON([]);\n }\n\n return _.mapObject(object, function(value) {\n return AV._encode(value, []);\n });\n };\n\n if (_.isArray(value)) {\n return value.map(function(object) {\n return encodeAVObject(object);\n });\n } else {\n return encodeAVObject(value);\n }\n};\n\nAV._arrayEach = _.each;\n\n/**\n * Does a deep traversal of every item in object, calling func on every one.\n * @param {Object} object The object or array to traverse deeply.\n * @param {Function} func The function to call for every item. It will\n * be passed the item as an argument. If it returns a truthy value, that\n * value will replace the item in its parent container.\n * @returns {} the result of calling func on the top-level object itself.\n * @private\n */\nAV._traverse = function(object, func, seen) {\n if (object instanceof AV.Object) {\n seen = seen || [];\n if (_.indexOf(seen, object) >= 0) {\n // We've already visited this object in this call.\n return;\n }\n seen.push(object);\n AV._traverse(object.attributes, func, seen);\n return func(object);\n }\n if (object instanceof AV.Relation || object instanceof AV.File) {\n // Nothing needs to be done, but we don't want to recurse into the\n // object's parent infinitely, so we catch this case.\n return func(object);\n }\n if (_.isArray(object)) {\n _.each(object, function(child, index) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[index] = newChild;\n }\n });\n return func(object);\n }\n if (_.isObject(object)) {\n AV._each(object, function(child, key) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[key] = newChild;\n }\n });\n return func(object);\n }\n return func(object);\n};\n\n/**\n * This is like _.each, except:\n * * it doesn't work for so-called array-like objects,\n * * it does work for dictionaries with a \"length\" attribute.\n * @private\n */\nAV._objectEach = AV._each = function(obj, callback) {\n if (_.isObject(obj)) {\n _.each(_.keys(obj), function(key) {\n callback(obj[key], key);\n });\n } else {\n _.each(obj, callback);\n }\n};\n\nmodule.exports = AV;\n\n\n\n// WEBPACK FOOTER //\n// ./src/av.js","/**\n * Root reference for iframes.\n */\n\nvar root;\nif (typeof window !== 'undefined') { // Browser window\n root = window;\n} else if (typeof self !== 'undefined') { // Web Worker\n root = self;\n} else { // Other environments\n console.warn(\"Using browser-only version of superagent in non-browser environment\");\n root = this;\n}\n\nvar Emitter = require('component-emitter');\nvar RequestBase = require('./request-base');\nvar isObject = require('./is-object');\nvar isFunction = require('./is-function');\nvar ResponseBase = require('./response-base');\nvar shouldRetry = require('./should-retry');\n\n/**\n * Noop.\n */\n\nfunction noop(){};\n\n/**\n * Expose `request`.\n */\n\nvar request = exports = module.exports = function(method, url) {\n // callback\n if ('function' == typeof url) {\n return new exports.Request('GET', method).end(url);\n }\n\n // url first\n if (1 == arguments.length) {\n return new exports.Request('GET', method);\n }\n\n return new exports.Request(method, url);\n}\n\nexports.Request = Request;\n\n/**\n * Determine XHR.\n */\n\nrequest.getXHR = function () {\n if (root.XMLHttpRequest\n && (!root.location || 'file:' != root.location.protocol\n || !root.ActiveXObject)) {\n return new XMLHttpRequest;\n } else {\n try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}\n }\n throw Error(\"Browser-only verison of superagent could not find XHR\");\n};\n\n/**\n * Removes leading and trailing whitespace, added to support IE.\n *\n * @param {String} s\n * @return {String}\n * @api private\n */\n\nvar trim = ''.trim\n ? function(s) { return s.trim(); }\n : function(s) { return s.replace(/(^\\s*|\\s*$)/g, ''); };\n\n/**\n * Serialize the given `obj`.\n *\n * @param {Object} obj\n * @return {String}\n * @api private\n */\n\nfunction serialize(obj) {\n if (!isObject(obj)) return obj;\n var pairs = [];\n for (var key in obj) {\n pushEncodedKeyValuePair(pairs, key, obj[key]);\n }\n return pairs.join('&');\n}\n\n/**\n * Helps 'serialize' with serializing arrays.\n * Mutates the pairs array.\n *\n * @param {Array} pairs\n * @param {String} key\n * @param {Mixed} val\n */\n\nfunction pushEncodedKeyValuePair(pairs, key, val) {\n if (val != null) {\n if (Array.isArray(val)) {\n val.forEach(function(v) {\n pushEncodedKeyValuePair(pairs, key, v);\n });\n } else if (isObject(val)) {\n for(var subkey in val) {\n pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);\n }\n } else {\n pairs.push(encodeURIComponent(key)\n + '=' + encodeURIComponent(val));\n }\n } else if (val === null) {\n pairs.push(encodeURIComponent(key));\n }\n}\n\n/**\n * Expose serialization method.\n */\n\n request.serializeObject = serialize;\n\n /**\n * Parse the given x-www-form-urlencoded `str`.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseString(str) {\n var obj = {};\n var pairs = str.split('&');\n var pair;\n var pos;\n\n for (var i = 0, len = pairs.length; i < len; ++i) {\n pair = pairs[i];\n pos = pair.indexOf('=');\n if (pos == -1) {\n obj[decodeURIComponent(pair)] = '';\n } else {\n obj[decodeURIComponent(pair.slice(0, pos))] =\n decodeURIComponent(pair.slice(pos + 1));\n }\n }\n\n return obj;\n}\n\n/**\n * Expose parser.\n */\n\nrequest.parseString = parseString;\n\n/**\n * Default MIME type map.\n *\n * superagent.types.xml = 'application/xml';\n *\n */\n\nrequest.types = {\n html: 'text/html',\n json: 'application/json',\n xml: 'application/xml',\n urlencoded: 'application/x-www-form-urlencoded',\n 'form': 'application/x-www-form-urlencoded',\n 'form-data': 'application/x-www-form-urlencoded'\n};\n\n/**\n * Default serialization map.\n *\n * superagent.serialize['application/xml'] = function(obj){\n * return 'generated xml here';\n * };\n *\n */\n\n request.serialize = {\n 'application/x-www-form-urlencoded': serialize,\n 'application/json': JSON.stringify\n };\n\n /**\n * Default parsers.\n *\n * superagent.parse['application/xml'] = function(str){\n * return { object parsed from str };\n * };\n *\n */\n\nrequest.parse = {\n 'application/x-www-form-urlencoded': parseString,\n 'application/json': JSON.parse\n};\n\n/**\n * Parse the given header `str` into\n * an object containing the mapped fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseHeader(str) {\n var lines = str.split(/\\r?\\n/);\n var fields = {};\n var index;\n var line;\n var field;\n var val;\n\n lines.pop(); // trailing CRLF\n\n for (var i = 0, len = lines.length; i < len; ++i) {\n line = lines[i];\n index = line.indexOf(':');\n field = line.slice(0, index).toLowerCase();\n val = trim(line.slice(index + 1));\n fields[field] = val;\n }\n\n return fields;\n}\n\n/**\n * Check if `mime` is json or has +json structured syntax suffix.\n *\n * @param {String} mime\n * @return {Boolean}\n * @api private\n */\n\nfunction isJSON(mime) {\n return /[\\/+]json\\b/.test(mime);\n}\n\n/**\n * Initialize a new `Response` with the given `xhr`.\n *\n * - set flags (.ok, .error, etc)\n * - parse header\n *\n * Examples:\n *\n * Aliasing `superagent` as `request` is nice:\n *\n * request = superagent;\n *\n * We can use the promise-like API, or pass callbacks:\n *\n * request.get('/').end(function(res){});\n * request.get('/', function(res){});\n *\n * Sending data can be chained:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' })\n * .end(function(res){});\n *\n * Or passed to `.send()`:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' }, function(res){});\n *\n * Or passed to `.post()`:\n *\n * request\n * .post('/user', { name: 'tj' })\n * .end(function(res){});\n *\n * Or further reduced to a single call for simple cases:\n *\n * request\n * .post('/user', { name: 'tj' }, function(res){});\n *\n * @param {XMLHTTPRequest} xhr\n * @param {Object} options\n * @api private\n */\n\nfunction Response(req) {\n this.req = req;\n this.xhr = this.req.xhr;\n // responseText is accessible only if responseType is '' or 'text' and on older browsers\n this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')\n ? this.xhr.responseText\n : null;\n this.statusText = this.req.xhr.statusText;\n var status = this.xhr.status;\n // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request\n if (status === 1223) {\n status = 204;\n }\n this._setStatusProperties(status);\n this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());\n // getAllResponseHeaders sometimes falsely returns \"\" for CORS requests, but\n // getResponseHeader still works. so we get content-type even if getting\n // other headers fails.\n this.header['content-type'] = this.xhr.getResponseHeader('content-type');\n this._setHeaderProperties(this.header);\n\n if (null === this.text && req._responseType) {\n this.body = this.xhr.response;\n } else {\n this.body = this.req.method != 'HEAD'\n ? this._parseBody(this.text ? this.text : this.xhr.response)\n : null;\n }\n}\n\nResponseBase(Response.prototype);\n\n/**\n * Parse the given body `str`.\n *\n * Used for auto-parsing of bodies. Parsers\n * are defined on the `superagent.parse` object.\n *\n * @param {String} str\n * @return {Mixed}\n * @api private\n */\n\nResponse.prototype._parseBody = function(str){\n var parse = request.parse[this.type];\n if(this.req._parser) {\n return this.req._parser(this, str);\n }\n if (!parse && isJSON(this.type)) {\n parse = request.parse['application/json'];\n }\n return parse && str && (str.length || str instanceof Object)\n ? parse(str)\n : null;\n};\n\n/**\n * Return an `Error` representative of this response.\n *\n * @return {Error}\n * @api public\n */\n\nResponse.prototype.toError = function(){\n var req = this.req;\n var method = req.method;\n var url = req.url;\n\n var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';\n var err = new Error(msg);\n err.status = this.status;\n err.method = method;\n err.url = url;\n\n return err;\n};\n\n/**\n * Expose `Response`.\n */\n\nrequest.Response = Response;\n\n/**\n * Initialize a new `Request` with the given `method` and `url`.\n *\n * @param {String} method\n * @param {String} url\n * @api public\n */\n\nfunction Request(method, url) {\n var self = this;\n this._query = this._query || [];\n this.method = method;\n this.url = url;\n this.header = {}; // preserves header name case\n this._header = {}; // coerces header names to lowercase\n this.on('end', function(){\n var err = null;\n var res = null;\n\n try {\n res = new Response(self);\n } catch(e) {\n err = new Error('Parser is unable to parse the response');\n err.parse = true;\n err.original = e;\n // issue #675: return the raw response if the response parsing fails\n if (self.xhr) {\n // ie9 doesn't have 'response' property\n err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;\n // issue #876: return the http status code if the response parsing fails\n err.status = self.xhr.status ? self.xhr.status : null;\n err.statusCode = err.status; // backwards-compat only\n } else {\n err.rawResponse = null;\n err.status = null;\n }\n\n return self.callback(err);\n }\n\n self.emit('response', res);\n\n var new_err;\n try {\n if (!self._isResponseOK(res)) {\n new_err = new Error(res.statusText || 'Unsuccessful HTTP response');\n new_err.original = err;\n new_err.response = res;\n new_err.status = res.status;\n }\n } catch(e) {\n new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android\n }\n\n // #1000 don't catch errors from the callback to avoid double calling it\n if (new_err) {\n self.callback(new_err, res);\n } else {\n self.callback(null, res);\n }\n });\n}\n\n/**\n * Mixin `Emitter` and `RequestBase`.\n */\n\nEmitter(Request.prototype);\nRequestBase(Request.prototype);\n\n/**\n * Set Content-Type to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.xml = 'application/xml';\n *\n * request.post('/')\n * .type('xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * request.post('/')\n * .type('application/xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * @param {String} type\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.type = function(type){\n this.set('Content-Type', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Accept to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.json = 'application/json';\n *\n * request.get('/agent')\n * .accept('json')\n * .end(callback);\n *\n * request.get('/agent')\n * .accept('application/json')\n * .end(callback);\n *\n * @param {String} accept\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.accept = function(type){\n this.set('Accept', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Authorization field value with `user` and `pass`.\n *\n * @param {String} user\n * @param {String} [pass] optional in case of using 'bearer' as type\n * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.auth = function(user, pass, options){\n if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options\n options = pass;\n }\n if (!options) {\n options = {\n type: 'function' === typeof btoa ? 'basic' : 'auto',\n }\n }\n\n switch (options.type) {\n case 'basic':\n this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));\n break;\n\n case 'auto':\n this.username = user;\n this.password = pass;\n break;\n \n case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })\n this.set('Authorization', 'Bearer ' + user);\n break; \n }\n return this;\n};\n\n/**\n * Add query-string `val`.\n *\n * Examples:\n *\n * request.get('/shoes')\n * .query('size=10')\n * .query({ color: 'blue' })\n *\n * @param {Object|String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.query = function(val){\n if ('string' != typeof val) val = serialize(val);\n if (val) this._query.push(val);\n return this;\n};\n\n/**\n * Queue the given `file` as an attachment to the specified `field`,\n * with optional `options` (or filename).\n *\n * ``` js\n * request.post('/upload')\n * .attach('content', new Blob(['hey!'], { type: \"text/html\"}))\n * .end(callback);\n * ```\n *\n * @param {String} field\n * @param {Blob|File} file\n * @param {String|Object} options\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.attach = function(field, file, options){\n if (file) {\n if (this._data) {\n throw Error(\"superagent can't mix .send() and .attach()\");\n }\n\n this._getFormData().append(field, file, options || file.name);\n }\n return this;\n};\n\nRequest.prototype._getFormData = function(){\n if (!this._formData) {\n this._formData = new root.FormData();\n }\n return this._formData;\n};\n\n/**\n * Invoke the callback with `err` and `res`\n * and handle arity check.\n *\n * @param {Error} err\n * @param {Response} res\n * @api private\n */\n\nRequest.prototype.callback = function(err, res){\n // console.log(this._retries, this._maxRetries)\n if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) {\n return this._retry();\n }\n\n var fn = this._callback;\n this.clearTimeout();\n\n if (err) {\n if (this._maxRetries) err.retries = this._retries - 1;\n this.emit('error', err);\n }\n\n fn(err, res);\n};\n\n/**\n * Invoke callback with x-domain error.\n *\n * @api private\n */\n\nRequest.prototype.crossDomainError = function(){\n var err = new Error('Request has been terminated\\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');\n err.crossDomain = true;\n\n err.status = this.status;\n err.method = this.method;\n err.url = this.url;\n\n this.callback(err);\n};\n\n// This only warns, because the request is still likely to work\nRequest.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){\n console.warn(\"This is not supported in browser version of superagent\");\n return this;\n};\n\n// This throws, because it can't send/receive data as expected\nRequest.prototype.pipe = Request.prototype.write = function(){\n throw Error(\"Streaming is not supported in browser version of superagent\");\n};\n\n/**\n * Compose querystring to append to req.url\n *\n * @api private\n */\n\nRequest.prototype._appendQueryString = function(){\n var query = this._query.join('&');\n if (query) {\n this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;\n }\n\n if (this._sort) {\n var index = this.url.indexOf('?');\n if (index >= 0) {\n var queryArr = this.url.substring(index + 1).split('&');\n if (isFunction(this._sort)) {\n queryArr.sort(this._sort);\n } else {\n queryArr.sort();\n }\n this.url = this.url.substring(0, index) + '?' + queryArr.join('&');\n }\n }\n};\n\n/**\n * Check if `obj` is a host object,\n * we don't want to serialize these :)\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\nRequest.prototype._isHost = function _isHost(obj) {\n // Native objects stringify to [object File], [object Blob], [object FormData], etc.\n return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';\n}\n\n/**\n * Initiate request, invoking callback `fn(res)`\n * with an instanceof `Response`.\n *\n * @param {Function} fn\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.end = function(fn){\n if (this._endCalled) {\n console.warn(\"Warning: .end() was called twice. This is not supported in superagent\");\n }\n this._endCalled = true;\n\n // store callback\n this._callback = fn || noop;\n\n // querystring\n this._appendQueryString();\n\n return this._end();\n};\n\nRequest.prototype._end = function() {\n var self = this;\n var xhr = this.xhr = request.getXHR();\n var data = this._formData || this._data;\n\n this._setTimeouts();\n\n // state change\n xhr.onreadystatechange = function(){\n var readyState = xhr.readyState;\n if (readyState >= 2 && self._responseTimeoutTimer) {\n clearTimeout(self._responseTimeoutTimer);\n }\n if (4 != readyState) {\n return;\n }\n\n // In IE9, reads to any property (e.g. status) off of an aborted XHR will\n // result in the error \"Could not complete the operation due to error c00c023f\"\n var status;\n try { status = xhr.status } catch(e) { status = 0; }\n\n if (!status) {\n if (self.timedout || self._aborted) return;\n return self.crossDomainError();\n }\n self.emit('end');\n };\n\n // progress\n var handleProgress = function(direction, e) {\n if (e.total > 0) {\n e.percent = e.loaded / e.total * 100;\n }\n e.direction = direction;\n self.emit('progress', e);\n }\n if (this.hasListeners('progress')) {\n try {\n xhr.onprogress = handleProgress.bind(null, 'download');\n if (xhr.upload) {\n xhr.upload.onprogress = handleProgress.bind(null, 'upload');\n }\n } catch(e) {\n // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.\n // Reported here:\n // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context\n }\n }\n\n // initiate request\n try {\n if (this.username && this.password) {\n xhr.open(this.method, this.url, true, this.username, this.password);\n } else {\n xhr.open(this.method, this.url, true);\n }\n } catch (err) {\n // see #1149\n return this.callback(err);\n }\n\n // CORS\n if (this._withCredentials) xhr.withCredentials = true;\n\n // body\n if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {\n // serialize stuff\n var contentType = this._header['content-type'];\n var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];\n if (!serialize && isJSON(contentType)) {\n serialize = request.serialize['application/json'];\n }\n if (serialize) data = serialize(data);\n }\n\n // set header fields\n for (var field in this.header) {\n if (null == this.header[field]) continue;\n\n if (this.header.hasOwnProperty(field))\n xhr.setRequestHeader(field, this.header[field]);\n }\n\n if (this._responseType) {\n xhr.responseType = this._responseType;\n }\n\n // send stuff\n this.emit('request', this);\n\n // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)\n // We need null here if data is undefined\n xhr.send(typeof data !== 'undefined' ? data : null);\n return this;\n};\n\n/**\n * GET `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.get = function(url, data, fn){\n var req = request('GET', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.query(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * HEAD `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.head = function(url, data, fn){\n var req = request('HEAD', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * OPTIONS query to `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.options = function(url, data, fn){\n var req = request('OPTIONS', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * DELETE `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nfunction del(url, data, fn){\n var req = request('DELETE', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\nrequest['del'] = del;\nrequest['delete'] = del;\n\n/**\n * PATCH `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.patch = function(url, data, fn){\n var req = request('PATCH', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * POST `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.post = function(url, data, fn){\n var req = request('POST', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * PUT `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.put = function(url, data, fn){\n var req = request('PUT', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/client.js\n// module id = 7\n// module chunks = 0","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/global.js\n// module id = 8\n// module chunks = 0","class FormData {\n constructor() {\n this._entries = [];\n }\n\n append(name, value) {\n if (typeof name !== 'string') {\n throw new TypeError('FormData name must be a string');\n }\n if (typeof value !== 'string') {\n if (typeof value !== 'object' || typeof value.uri !== 'string') {\n throw new TypeError('FormData value must be a string or { uri: tempFilePath }')\n }\n }\n this._entries.push([name, value]);\n }\n\n set(name, value) {\n const entry = this.get(name);\n if (entry) {\n entry[1] = value;\n } else {\n this.append(name, value);\n }\n }\n\n delete(name) {\n this._entries = this._entries.filter(entry => entry[0] !== name);\n }\n\n entries() {\n return this._entries;\n }\n\n get(name) {\n return this._entries.find(entry => entry[0] === name);\n }\n\n getAll(name) {\n return this._entries.filter(entry => entry[0] === name);\n }\n\n has(name) {\n return this._entries.some(entry => entry[0] === name);\n }\n\n keys() {\n return this._entries.map(entry => entry[0]);\n }\n\n values() {\n return this._entries.map(entry => entry[1]);\n }\n}\n\nmodule.exports = FormData;\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/formdata.js","/**\n * @author Toru Nagashima\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n\n\"use strict\";\n\n/**\n * Creates a unique key.\n *\n * @param {string} name - A name to create.\n * @returns {symbol|string}\n * @private\n */\nvar createUniqueKey = exports.createUniqueKey = (typeof Symbol !== \"undefined\" ?\n Symbol :\n function createUniqueKey(name) {\n return \"[[\" + name + \"_\" + Math.random().toFixed(8).slice(2) + \"]]\";\n });\n\n/**\n * The key of listeners.\n *\n * @type {symbol|string}\n * @private\n */\nexports.LISTENERS = createUniqueKey(\"listeners\");\n\n/**\n * A value of kind for listeners which are registered in the capturing phase.\n *\n * @type {number}\n * @private\n */\nexports.CAPTURE = 1;\n\n/**\n * A value of kind for listeners which are registered in the bubbling phase.\n *\n * @type {number}\n * @private\n */\nexports.BUBBLE = 2;\n\n/**\n * A value of kind for listeners which are registered as an attribute.\n *\n * @type {number}\n * @private\n */\nexports.ATTRIBUTE = 3;\n\n/**\n * @typedef object ListenerNode\n * @property {function} listener - A listener function.\n * @property {number} kind - The kind of the listener.\n * @property {ListenerNode|null} next - The next node.\n * If this node is the last, this is `null`.\n */\n\n/**\n * Creates a node of singly linked list for a list of listeners.\n *\n * @param {function} listener - A listener function.\n * @param {number} kind - The kind of the listener.\n * @returns {ListenerNode} The created listener node.\n */\nexports.newNode = function newNode(listener, kind) {\n return {listener: listener, kind: kind, next: null};\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/event-target-shim/lib/commons.js\n// module id = 10\n// module chunks = 0","/**\n * Check if `obj` is an object.\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\n\nfunction isObject(obj) {\n return null !== obj && 'object' === typeof obj;\n}\n\nmodule.exports = isObject;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-object.js\n// module id = 11\n// module chunks = 0","class Storage {\n getItem(key) {\n return wx.getStorageSync(key);\n }\n\n setItem(key, value) {\n return wx.setStorageSync(key, value);\n }\n\n removeItem(key) {\n return this.setItem(key, '');\n }\n\n clear() {\n return wx.clearStorageSync();\n }\n}\n\nmodule.exports = new Storage();\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/localstorage.js","module.exports = {};\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/navigator.js","const assign = require('object-assign');\nconst EventTarget = require('event-target-shim');\n\nconst CONNECTING = 0;\nconst OPEN = 1;\nconst CLOSING = 2;\nconst CLOSED = 3;\n\nconst EVENTS = [\n 'open',\n 'error',\n 'message',\n 'close',\n];\n\nlet instance;\n\nfunction errorHandler(event) {\n // 安卓小程序会诡异地触发 onSocketError 回调\n // 通过比较 message 过滤掉\n if (event.message === \"\") return;\n if (instance) {\n instance._readyState = CLOSED;\n instance.dispatchEvent({\n type: 'error',\n message: event.errMsg,\n });\n }\n}\n\nclass WebSocket extends EventTarget(EVENTS) {\n constructor(url, protocal) {\n if (!url) {\n throw new TypeError('Failed to construct \\'WebSocket\\': url required');\n }\n if (protocal) {\n throw new Error('subprotocal not supported in weapp');\n }\n super();\n this._url = url;\n this._protocal = ''; // default value according to specs\n this._readyState = CONNECTING;\n if (instance) {\n instance.dispatchEvent({\n type: 'close'\n });\n }\n instance = this;\n \n wx.onSocketOpen(function (event) {\n if (instance) {\n instance._readyState = OPEN;\n instance.dispatchEvent({\n type: 'open'\n });\n }\n });\n wx.onSocketError(errorHandler);\n wx.onSocketMessage(function (event) {\n if (instance) {\n var {\n data,\n origin,\n ports,\n source,\n } = event;\n instance.dispatchEvent({\n data,\n origin,\n ports,\n source,\n type: 'message',\n });\n }\n });\n wx.onSocketClose(function (event) {\n if (instance) {\n instance._readyState = CLOSED;\n var {\n code,\n reason,\n wasClean,\n } = event;\n instance.dispatchEvent({\n code,\n reason,\n wasClean,\n type: 'close',\n });\n instance = null;\n }\n });\n \n wx.connectSocket({\n url,\n fail: (error) => setTimeout(() => errorHandler(error), 0),\n });\n }\n\n get url() {\n return this._url;\n }\n get protocal() {\n return this._protocal;\n }\n get readyState() {\n return this._readyState;\n }\n\n close() {\n if (this.readyState === CONNECTING) {\n console.warn('close WebSocket which is connecting might not work');\n }\n wx.closeSocket();\n }\n\n send(data) {\n if (this.readyState !== OPEN) {\n throw new Error('INVALID_STATE_ERR');\n }\n\n if (typeof data !== 'string') {\n throw new TypeError('only string typed data are supported');\n }\n\n wx.sendSocketMessage({\n data\n });\n }\n\n}\n\nassign(WebSocket, {\n CONNECTING,\n OPEN,\n CLOSING,\n CLOSED,\n});\n\nmodule.exports = WebSocket;\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/websocket.js","const assign = require('object-assign');\nconst EventTarget = require('event-target-shim');\nconst FormData = require('./formdata.js');\n\nconst UNSENT = 0;\nconst OPENED = 1;\nconst HEADERS_RECEIVED = 2;\nconst LOADING = 3;\nconst DONE = 4;\n\nconst REQUEST_EVENTS = [\n 'abort',\n 'error',\n 'load',\n 'loadstart',\n 'progress',\n 'timeout',\n 'loadend',\n 'readystatechange'\n];\n\nfunction successCallback(response) {\n this.status = response.statusCode;\n this.statusText = response.statusCode;\n let text = response.data;\n if (typeof text !== 'string') {\n text = JSON.stringify(text);\n }\n this.responseText = this.response = text;\n this.readyState = DONE;\n this.dispatchEvent({ type: 'readystatechange' });\n}\n\nclass XMLHttpRequest extends EventTarget(REQUEST_EVENTS) {\n\n constructor() {\n super();\n this.readyState = UNSENT;\n this._headers = {};\n }\n\n abort() {\n throw new Error('not supported in weapp');\n }\n getAllResponseHeaders() {\n console.warn('getAllResponseHeaders always returns \\'\\'');\n return '';\n }\n getResponseHeader(key) {\n if (key === 'content-type') {\n console.warn('get content-type always returns \\'application/json\\'');\n return 'application/json';\n }\n console.warn('getResponseHeader always returns \\'\\'');\n return '';\n }\n overrideMimeType() {\n throw new Error('not supported in weapp');\n }\n open(method, url, async = true) {\n if (this.readyState !== UNSENT) {\n throw new Error('request is already opened');\n }\n if (!async) {\n throw new Error('sync request is not supported');\n }\n this._method = method;\n this._url = url;\n this.readyState = OPENED;\n this.dispatchEvent({ type: 'readystatechange' });\n }\n setRequestHeader(header, value) {\n if (this.readyState !== OPENED) {\n throw new Error('request is not opened');\n }\n this._headers[header.toLowerCase()] = value;\n }\n send(data) {\n if (this.readyState !== OPENED) {\n throw new Error('request is not opened');\n }\n if (data instanceof FormData) {\n const entries = data.entries();\n const blobs = entries.filter(entry => typeof entry[1] !== 'string');\n if (blobs.length === 0) {\n throw new Error('Must specify a Blob field in FormData');\n }\n if (blobs.length > 1) {\n console.warn('Only the first Blob will be send in Weapp');\n }\n const restData = entries\n .filter(entry => typeof entry[1] === 'string')\n .reduce((result, entry) => assign(result, { [entry[0]]: entry[1] }), {});\n wx.uploadFile({\n url: this._url,\n name: blobs[0][0],\n filePath: blobs[0][1].uri,\n formData: restData,\n header: this._headers,\n success: successCallback.bind(this),\n fail: (error) => {\n this.status = 0;\n this.readyState = DONE;\n this.dispatchEvent({ type: 'readystatechange' });\n this.dispatchEvent({ type: 'error' });\n }\n })\n } else {\n wx.request({\n url: this._url,\n data: data || '',\n // method 的 value 居然必须为大写\n method: this._method.toUpperCase(),\n header: this._headers,\n success: successCallback.bind(this),\n fail: (error) => {\n this.status = 0;\n this.readyState = DONE;\n this.dispatchEvent({ type: 'readystatechange' });\n this.dispatchEvent({ type: 'error' });\n }\n });\n }\n }\n}\n\nassign(XMLHttpRequest, {\n UNSENT,\n OPENED,\n HEADERS_RECEIVED,\n LOADING,\n DONE,\n});\n\nmodule.exports = XMLHttpRequest;\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/xmlhttprequest.js","const storage = require('./localstorage');\nconst AV = require('./av');\n\nconst removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage);\n\nconst getCacheData = (cacheData, key) => {\n try {\n cacheData = JSON.parse(cacheData);\n } catch (e) {\n return null;\n }\n if (cacheData) {\n const expired = cacheData.expiredAt && cacheData.expiredAt < Date.now();\n if (!expired) {\n return cacheData.value;\n }\n return removeAsync(key).then(() => null);\n }\n return null;\n};\n\nexports.getAsync = (key) => {\n key = `${AV.applicationId}/${key}`;\n return storage.getItemAsync(key)\n .then(cache => getCacheData(cache, key));\n};\n\nexports.setAsync = (key, value, ttl) => {\n const cache = { value };\n if (typeof ttl === 'number') {\n cache.expiredAt = Date.now() + ttl;\n }\n return storage.setItemAsync(\n `${AV.applicationId}/${key}`,\n JSON.stringify(cache)\n );\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cache.js","var _ = require('underscore');\nvar Promise = require('./promise');\nvar localStorage = require('./utils/localstorage');\n\nvar syncApiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nif (!localStorage.async) {\n // wrap sync apis with async ones.\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] === 'function') {\n localStorage[apiName + 'Async'] = function() {\n return Promise.resolve(localStorage[apiName].apply(localStorage, arguments));\n };\n }\n });\n} else {\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] !== 'function') {\n localStorage[apiName] = function() {\n const error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.');\n error.code = 'SYNC_API_NOT_AVAILABLE';\n throw error;\n };\n }\n });\n}\n\nmodule.exports = localStorage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/localstorage.js","module.exports = '2.1.4';\n\n\n\n// WEBPACK FOOTER //\n// ./src/version.js","var charenc = {\n // UTF-8 encoding\n utf8: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n }\n },\n\n // Binary encoding\n bin: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n for (var bytes = [], i = 0; i < str.length; i++)\n bytes.push(str.charCodeAt(i) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n for (var str = [], i = 0; i < bytes.length; i++)\n str.push(String.fromCharCode(bytes[i]));\n return str.join('');\n }\n }\n};\n\nmodule.exports = charenc;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/charenc/charenc.js\n// module id = 19\n// module chunks = 0","/**\n * @author Toru Nagashima\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n\n\"use strict\";\n\n//-----------------------------------------------------------------------------\n// Requirements\n//-----------------------------------------------------------------------------\n\nvar Commons = require(\"./commons\");\nvar CustomEventTarget = require(\"./custom-event-target\");\nvar EventWrapper = require(\"./event-wrapper\");\nvar LISTENERS = Commons.LISTENERS;\nvar CAPTURE = Commons.CAPTURE;\nvar BUBBLE = Commons.BUBBLE;\nvar ATTRIBUTE = Commons.ATTRIBUTE;\nvar newNode = Commons.newNode;\nvar defineCustomEventTarget = CustomEventTarget.defineCustomEventTarget;\nvar createEventWrapper = EventWrapper.createEventWrapper;\nvar STOP_IMMEDIATE_PROPAGATION_FLAG =\n EventWrapper.STOP_IMMEDIATE_PROPAGATION_FLAG;\n\n//-----------------------------------------------------------------------------\n// Constants\n//-----------------------------------------------------------------------------\n\n/**\n * A flag which shows there is the native `EventTarget` interface object.\n *\n * @type {boolean}\n * @private\n */\nvar HAS_EVENTTARGET_INTERFACE = (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n);\n\n//-----------------------------------------------------------------------------\n// Public Interface\n//-----------------------------------------------------------------------------\n\n/**\n * An implementation for `EventTarget` interface.\n *\n * @constructor\n * @public\n */\nvar EventTarget = module.exports = function EventTarget() {\n if (this instanceof EventTarget) {\n // this[LISTENERS] is a Map.\n // Its key is event type.\n // Its value is ListenerNode object or null.\n //\n // interface ListenerNode {\n // var listener: Function\n // var kind: CAPTURE|BUBBLE|ATTRIBUTE\n // var next: ListenerNode|null\n // }\n Object.defineProperty(this, LISTENERS, {value: Object.create(null)});\n }\n else if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(EventTarget, arguments[0]);\n }\n else if (arguments.length > 0) {\n var types = Array(arguments.length);\n for (var i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i];\n }\n\n // To use to extend with attribute listener properties.\n // e.g.\n // class MyCustomObject extends EventTarget(\"message\", \"error\") {\n // //...\n // }\n return defineCustomEventTarget(EventTarget, types);\n }\n else {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n};\n\nEventTarget.prototype = Object.create(\n (HAS_EVENTTARGET_INTERFACE ? window.EventTarget : Object).prototype,\n {\n constructor: {\n value: EventTarget,\n writable: true,\n configurable: true\n },\n\n addEventListener: {\n value: function addEventListener(type, listener, capture) {\n if (listener == null) {\n return false;\n }\n if (typeof listener !== \"function\" && typeof listener !== \"object\") {\n throw new TypeError(\"\\\"listener\\\" is not an object.\");\n }\n\n var kind = (capture ? CAPTURE : BUBBLE);\n var node = this[LISTENERS][type];\n if (node == null) {\n this[LISTENERS][type] = newNode(listener, kind);\n return true;\n }\n\n var prev = null;\n while (node != null) {\n if (node.listener === listener && node.kind === kind) {\n // Should ignore a duplicated listener.\n return false;\n }\n prev = node;\n node = node.next;\n }\n\n prev.next = newNode(listener, kind);\n return true;\n },\n configurable: true,\n writable: true\n },\n\n removeEventListener: {\n value: function removeEventListener(type, listener, capture) {\n if (listener == null) {\n return false;\n }\n\n var kind = (capture ? CAPTURE : BUBBLE);\n var prev = null;\n var node = this[LISTENERS][type];\n while (node != null) {\n if (node.listener === listener && node.kind === kind) {\n if (prev == null) {\n this[LISTENERS][type] = node.next;\n }\n else {\n prev.next = node.next;\n }\n return true;\n }\n\n prev = node;\n node = node.next;\n }\n\n return false;\n },\n configurable: true,\n writable: true\n },\n\n dispatchEvent: {\n value: function dispatchEvent(event) {\n // If listeners aren't registered, terminate.\n var node = this[LISTENERS][event.type];\n if (node == null) {\n return true;\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n var wrapped = createEventWrapper(event, this);\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n while (node != null) {\n if (typeof node.listener === \"function\") {\n node.listener.call(this, wrapped);\n }\n else if (node.kind !== ATTRIBUTE && typeof node.listener.handleEvent === \"function\") {\n node.listener.handleEvent(wrapped);\n }\n\n if (wrapped[STOP_IMMEDIATE_PROPAGATION_FLAG]) {\n break;\n }\n node = node.next;\n }\n\n return !wrapped.defaultPrevented;\n },\n configurable: true,\n writable: true\n }\n }\n);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/event-target-shim/lib/event-target.js\n// module id = 20\n// module chunks = 0","/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n'use strict';\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/object-assign/index.js\n// module id = 21\n// module chunks = 0","var polyfill = require('./index.js').polyfill;\nwindow = window || {};\npolyfill();\npolyfill(window);\ntry {\n localStorage = localStorage || require('./localstorage.js');\n} catch (e) {}\ntry {\n XMLHttpRequest = XMLHttpRequest || require('./xmlhttprequest.js');\n} catch (e) {}\ntry {\n FormData = FormData || require('./formdata.js');\n} catch (e) {}\ntry {\n WebSocket = WebSocket || require('./websocket.js');\n} catch (e) {}\ntry {\n navigator = navigator || require('./navigator.js');\n} catch (e) {}\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/auto-polyfill.js","/*!\n * LeanCloud JavaScript SDK\n * https://leancloud.cn\n *\n * Copyright 2016 LeanCloud.cn, Inc.\n * The LeanCloud JavaScript SDK is freely distributable under the MIT license.\n */\n\nconst AV = require('./av');\n\nAV._ = require('underscore');\nAV.version = require('./version');\nAV.Promise = require('./promise');\nAV.localStorage = require('./localstorage');\nAV.Cache = require('./cache');\nAV.Error = require('./error');\n\nrequire('./init');\nrequire('./event')(AV);\nrequire('./geopoint')(AV);\nrequire('./acl')(AV);\nrequire('./op')(AV);\nrequire('./relation')(AV);\nrequire('./file')(AV);\nrequire('./object')(AV);\nrequire('./role')(AV);\nrequire('./user')(AV);\nrequire('./query')(AV);\nrequire('./cloudfunction')(AV);\nrequire('./push')(AV);\nrequire('./status')(AV);\nrequire('./search')(AV);\nrequire('./insight')(AV);\n\nmodule.exports = AV;\n\n/**\n * Options to controll the authentication for an operation\n * @typedef {Object} AuthOptions\n * @property {String} [sessionToken] Specify a user to excute the operation as.\n * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided.\n * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set.\n */\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","var localStorage = require('./localstorage.js');\nvar XMLHttpRequest = require('./xmlhttprequest.js');\nvar FormData = require('./formdata.js');\nvar WebSocket = require('./websocket.js');\nvar navigator = require('./navigator');\n\nmodule.exports = {\n polyfill(target = global || window) {\n if (typeof target !== 'object') {\n throw new Error('polyfill target is not an Object');\n }\n const polyfills = {\n localStorage,\n XMLHttpRequest,\n FormData,\n WebSocket,\n Object,\n navigator,\n };\n for (let k in polyfills) {\n if (!target[k]) target[k] = polyfills[k];\n }\n },\n localStorage,\n XMLHttpRequest,\n FormData,\n WebSocket,\n}\n\n\n\n// WEBPACK FOOTER //\n// ./~/weapp-polyfill/index.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var PUBLIC_KEY = \"*\";\n\n /**\n * Creates a new ACL.\n * If no argument is given, the ACL has no permissions for anyone.\n * If the argument is a AV.User, the ACL will have read and write\n * permission for only that user.\n * If the argument is any other JSON object, that object will be interpretted\n * as a serialized ACL created with toJSON().\n * @see AV.Object#setACL\n * @class\n *\n *

An ACL, or Access Control List can be added to any\n * AV.Object to restrict access to only a subset of users\n * of your application.

\n */\n AV.ACL = function(arg1) {\n var self = this;\n self.permissionsById = {};\n if (_.isObject(arg1)) {\n if (arg1 instanceof AV.User) {\n self.setReadAccess(arg1, true);\n self.setWriteAccess(arg1, true);\n } else {\n if (_.isFunction(arg1)) {\n throw new Error('AV.ACL() called with a function. Did you forget ()?');\n }\n AV._objectEach(arg1, function(accessList, userId) {\n if (!_.isString(userId)) {\n throw new Error('Tried to create an ACL with an invalid userId.');\n }\n self.permissionsById[userId] = {};\n AV._objectEach(accessList, function(allowed, permission) {\n if (permission !== \"read\" && permission !== \"write\") {\n throw new Error('Tried to create an ACL with an invalid permission type.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('Tried to create an ACL with an invalid permission value.');\n }\n self.permissionsById[userId][permission] = allowed;\n });\n });\n }\n }\n };\n\n /**\n * Returns a JSON-encoded version of the ACL.\n * @return {Object}\n */\n AV.ACL.prototype.toJSON = function() {\n return _.clone(this.permissionsById);\n };\n\n AV.ACL.prototype._setAccess = function(accessType, userId, allowed) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n if (!_.isString(userId)) {\n throw new Error('userId must be a string.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('allowed must be either true or false.');\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n if (!allowed) {\n // The user already doesn't have this permission, so no action needed.\n return;\n } else {\n permissions = {};\n this.permissionsById[userId] = permissions;\n }\n }\n\n if (allowed) {\n this.permissionsById[userId][accessType] = true;\n } else {\n delete permissions[accessType];\n if (_.isEmpty(permissions)) {\n delete this.permissionsById[userId];\n }\n }\n };\n\n AV.ACL.prototype._getAccess = function(accessType, userId) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n return false;\n }\n return permissions[accessType] ? true : false;\n };\n\n /**\n * Set whether the given user is allowed to read this object.\n * @param userId An instance of AV.User or its objectId.\n * @param {Boolean} allowed Whether that user should have read access.\n */\n AV.ACL.prototype.setReadAccess = function(userId, allowed) {\n this._setAccess(\"read\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to read this object.\n * Even if this returns false, the user may still be able to access it if\n * getPublicReadAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getReadAccess = function(userId) {\n return this._getAccess(\"read\", userId);\n };\n\n /**\n * Set whether the given user id is allowed to write this object.\n * @param userId An instance of AV.User or its objectId, or a AV.Role..\n * @param {Boolean} allowed Whether that user should have write access.\n */\n AV.ACL.prototype.setWriteAccess = function(userId, allowed) {\n this._setAccess(\"write\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to write this object.\n * Even if this returns false, the user may still be able to write it if\n * getPublicWriteAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getWriteAccess = function(userId) {\n return this._getAccess(\"write\", userId);\n };\n\n /**\n * Set whether the public is allowed to read this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicReadAccess = function(allowed) {\n this.setReadAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to read this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicReadAccess = function() {\n return this.getReadAccess(PUBLIC_KEY);\n };\n\n /**\n * Set whether the public is allowed to write this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicWriteAccess = function(allowed) {\n this.setWriteAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to write this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicWriteAccess = function() {\n return this.getWriteAccess(PUBLIC_KEY);\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to read this object. Even if this returns false, the role may\n * still be able to write it if a parent role has read access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has read access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleReadAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getReadAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to write this object. Even if this returns false, the role may\n * still be able to write it if a parent role has write access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has write access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleWriteAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getWriteAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to read this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can read this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleReadAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setReadAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to write this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can write this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleWriteAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setWriteAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/acl.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * Contains functions for calling and declaring\n *

\n * Some functions are only available from Cloud Code.\n *

\n *\n * @namespace\n */\n AV.Cloud = AV.Cloud || {};\n\n _.extend(AV.Cloud, /** @lends AV.Cloud */ {\n /**\n * Makes a call to a cloud function.\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n run: function(name, data, options) {\n var request = AVRequest('functions', name, null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response\n * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object}\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result of the function.\n */\n rpc: function(name, data, options) {\n if (_.isArray(data)) {\n return Promise.reject(new Error('Can\\'t pass Array as the param of rpc function in JavaScript SDK.'));\n }\n\n return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Make a call to request server date time.\n * @return {Promise.} A promise that will be resolved with the result\n * of the function.\n * @since 0.5.9\n */\n getServerDate: function() {\n var request = AVRequest(\"date\", null, null, 'GET');\n\n return request.then(function(resp) {\n return AV._decode(resp);\n });\n },\n\n /**\n * Makes a call to request a sms code for operation verification.\n * @param {Object} data The mobile phone number string or a JSON\n * object that contains mobilePhoneNumber,template,op,ttl,name etc.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n requestSmsCode: function(data){\n if(_.isString(data)) {\n data = { mobilePhoneNumber: data };\n }\n if(!data.mobilePhoneNumber) {\n throw new Error('Missing mobilePhoneNumber.');\n }\n var request = AVRequest(\"requestSmsCode\", null, null, 'POST',\n data);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode\n * @param {String} code The sms code sent by AV.Cloud.requestSmsCode\n * @param {phone} phone The mobile phoner number(optional).\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifySmsCode: function(code, phone){\n if(!code)\n throw new Error('Missing sms code.');\n var params = {};\n if(_.isString(phone)) {\n params['mobilePhoneNumber'] = phone;\n }\n\n var request = AVRequest(\"verifySmsCode\", code, null, 'POST',\n params);\n return request;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cloudfunction.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var eventSplitter = /\\s+/;\n var slice = Array.prototype.slice;\n\n /**\n * @class\n *\n *

AV.Events is a fork of Backbone's Events module, provided for your\n * convenience.

\n *\n *

A module that can be mixed in to any object in order to provide\n * it with custom events. You may bind callback functions to an event\n * with `on`, or remove these functions with `off`.\n * Triggering an event fires all callbacks in the order that `on` was\n * called.\n *\n * @private\n * @example\n * var object = {};\n * _.extend(object, AV.Events);\n * object.on('expand', function(){ alert('expanded'); });\n * object.trigger('expand');

\n *\n */\n AV.Events = {\n /**\n * Bind one or more space separated events, `events`, to a `callback`\n * function. Passing `\"all\"` will bind the callback to all events fired.\n */\n on: function(events, callback, context) {\n\n var calls, event, node, tail, list;\n if (!callback) {\n return this;\n }\n events = events.split(eventSplitter);\n calls = this._callbacks || (this._callbacks = {});\n\n // Create an immutable callback list, allowing traversal during\n // modification. The tail is an empty object that will always be used\n // as the next node.\n event = events.shift();\n while (event) {\n list = calls[event];\n node = list ? list.tail : {};\n node.next = tail = {};\n node.context = context;\n node.callback = callback;\n calls[event] = {tail: tail, next: list ? list.next : node};\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Remove one or many callbacks. If `context` is null, removes all callbacks\n * with that function. If `callback` is null, removes all callbacks for the\n * event. If `events` is null, removes all bound callbacks for all events.\n */\n off: function(events, callback, context) {\n var event, calls, node, tail, cb, ctx;\n\n // No events, or removing *all* events.\n if (!(calls = this._callbacks)) {\n return;\n }\n if (!(events || callback || context)) {\n delete this._callbacks;\n return this;\n }\n\n // Loop through the listed events and contexts, splicing them out of the\n // linked list of callbacks if appropriate.\n events = events ? events.split(eventSplitter) : _.keys(calls);\n event = events.shift();\n while (event) {\n node = calls[event];\n delete calls[event];\n if (!node || !(callback || context)) {\n continue;\n }\n // Create a new list, omitting the indicated callbacks.\n tail = node.tail;\n node = node.next;\n while (node !== tail) {\n cb = node.callback;\n ctx = node.context;\n if ((callback && cb !== callback) || (context && ctx !== context)) {\n this.on(event, cb, ctx);\n }\n node = node.next;\n }\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Trigger one or many events, firing all bound callbacks. Callbacks are\n * passed the same arguments as `trigger` is, apart from the event name\n * (unless you're listening on `\"all\"`, which will cause your callback to\n * receive the true name of the event as the first argument).\n */\n trigger: function(events) {\n var event, node, calls, tail, args, all, rest;\n if (!(calls = this._callbacks)) {\n return this;\n }\n all = calls.all;\n events = events.split(eventSplitter);\n rest = slice.call(arguments, 1);\n\n // For each event, walk through the linked list of callbacks twice,\n // first to trigger the event, then to trigger any `\"all\"` callbacks.\n event = events.shift();\n while (event) {\n node = calls[event];\n if (node) {\n tail = node.tail;\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, rest);\n }\n }\n node = all;\n if (node) {\n tail = node.tail;\n args = [event].concat(rest);\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, args);\n }\n }\n event = events.shift();\n }\n\n return this;\n }\n };\n\n /**\n * @function\n */\n AV.Events.bind = AV.Events.on;\n\n /**\n * @function\n */\n AV.Events.unbind = AV.Events.off;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/event.js","const _ = require('underscore');\nconst cos = require('./uploader/cos');\nconst qiniu = require('./uploader/qiniu');\nconst s3 = require('./uploader/s3');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\nconst { tap } = require('./utils');\nconst debug = require('debug')('leancloud:file');\nconst parseBase64 = require('./utils/parse-base64');\n\nmodule.exports = function(AV) {\n\n // 挂载一些配置\n let avConfig = AV._config;\n\n const hexOctet = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);\n\n // port from browserify path module\n // since react-native packager won't shim node modules.\n const extname = (path) => {\n return path.match(/^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/)[4];\n };\n\n const b64Digit = (number) => {\n if (number < 26) {\n return String.fromCharCode(65 + number);\n }\n if (number < 52) {\n return String.fromCharCode(97 + (number - 26));\n }\n if (number < 62) {\n return String.fromCharCode(48 + (number - 52));\n }\n if (number === 62) {\n return '+';\n }\n if (number === 63) {\n return '/';\n }\n throw new Error('Tried to encode large digit ' + number + ' in base64.');\n };\n\n var encodeBase64 = function(array) {\n var chunks = [];\n chunks.length = Math.ceil(array.length / 3);\n _.times(chunks.length, function(i) {\n var b1 = array[i * 3];\n var b2 = array[i * 3 + 1] || 0;\n var b3 = array[i * 3 + 2] || 0;\n\n var has2 = (i * 3 + 1) < array.length;\n var has3 = (i * 3 + 2) < array.length;\n\n chunks[i] = [\n b64Digit((b1 >> 2) & 0x3F),\n b64Digit(((b1 << 4) & 0x30) | ((b2 >> 4) & 0x0F)),\n has2 ? b64Digit(((b2 << 2) & 0x3C) | ((b3 >> 6) & 0x03)) : \"=\",\n has3 ? b64Digit(b3 & 0x3F) : \"=\"\n ].join(\"\");\n });\n return chunks.join(\"\");\n };\n\n /**\n * An AV.File is a local representation of a file that is saved to the AV\n * cloud.\n * @param name {String} The file's name. This will change to a unique value\n * once the file has finished saving.\n * @param data {Array} The data for the file, as either:\n * 1. an Array of byte value Numbers, or\n * 2. an Object like { base64: \"...\" } with a base64-encoded String.\n * 3. a File object selected with a file upload control. (3) only works\n * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.\n * 4.a Buffer object in Node.js runtime.\n *\n * For example:
\n   * var fileUploadControl = $(\"#profilePhotoFileUpload\")[0];\n   * if (fileUploadControl.files.length > 0) {\n   *   var file = fileUploadControl.files[0];\n   *   var name = \"photo.jpg\";\n   *   var file = new AV.File(name, file);\n   *   file.save().then(function() {\n   *     // The file has been saved to AV.\n   *   }, function(error) {\n   *     // The file either could not be read, or could not be saved to AV.\n   *   });\n   * }
\n *\n * @class\n * @param [mimeType] {String} Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n */\n AV.File = function(name, data, mimeType) {\n\n this.attributes = {\n name,\n url: '',\n metaData: {},\n // 用来存储转换后要上传的 base64 String\n base64: '',\n };\n\n if (_.isString(data)) {\n throw new TypeError(\"Creating an AV.File from a String is not yet supported.\");\n }\n if (_.isArray(data)) {\n this.attributes.metaData.size = data.length;\n data = { base64: encodeBase64(data) };\n }\n\n this._extName = '';\n this._data = data;\n\n let owner;\n if (data && data.owner) {\n owner = data.owner;\n } else if (!AV._config.disableCurrentUser) {\n try {\n owner = AV.User.current();\n } catch (error) {\n if ('SYNC_API_NOT_AVAILABLE' === error.code) {\n console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().');\n } else {\n throw error;\n }\n }\n }\n \n this.attributes.metaData.owner = owner ? owner.id : 'unknown';\n\n this.set('mime_type', mimeType);\n };\n\n /**\n * Creates a fresh AV.File object with exists url for saving to AVOS Cloud.\n * @param {String} name the file name\n * @param {String} url the file url.\n * @param {Object} [metaData] the file metadata object.\n * @param {String} [type] Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n * @return {AV.File} the file object\n */\n AV.File.withURL = function(name, url, metaData, type) {\n if (!name || !url){\n throw new Error(\"Please provide file name and url\");\n }\n var file = new AV.File(name, null, type);\n //copy metaData properties to file.\n if (metaData){\n for(var prop in metaData){\n if (!file.attributes.metaData[prop])\n file.attributes.metaData[prop] = metaData[prop];\n }\n }\n file.attributes.url = url;\n //Mark the file is from external source.\n file.attributes.metaData.__source = 'external';\n return file;\n };\n\n /**\n * Creates a file object with exists objectId.\n * @param {String} objectId The objectId string\n * @return {AV.File} the file object\n */\n AV.File.createWithoutData = function(objectId) {\n var file = new AV.File();\n file.id = objectId;\n return file;\n };\n\n AV.File.prototype = {\n className: '_File',\n\n _toFullJSON(seenObjects) {\n var json = _.clone(this.attributes);\n AV._objectEach(json, function(val, key) {\n json[key] = AV._encode(val, seenObjects);\n });\n AV._objectEach(this._operations, function(val, key) {\n json[key] = val;\n });\n\n if (_.has(this, \"id\")) {\n json.objectId = this.id;\n }\n _(['createdAt', 'updatedAt']).each((key) => {\n if (_.has(this, key)) {\n const val = this[key];\n json[key] = _.isDate(val) ? val.toJSON() : val;\n }\n });\n json.__type = \"File\";\n return json;\n },\n\n toJSON() {\n const json = this._toFullJSON();\n // add id and keep __type for backward compatible\n if (_.has(this, 'id')) {\n json.id = this.id;\n }\n return json;\n },\n\n /**\n * Returns the ACL for this file.\n * @returns {AV.ACL} An instance of AV.ACL.\n */\n getACL: function() {\n return this._acl;\n },\n\n /**\n * Sets the ACL to be used for this file.\n * @param {AV.ACL} acl An instance of AV.ACL.\n */\n setACL: function(acl) {\n if (!(acl instanceof AV.ACL)) {\n return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.');\n }\n this._acl = acl;\n },\n\n /**\n * Gets the name of the file. Before save is called, this is the filename\n * given by the user. After save is called, that name gets prefixed with a\n * unique identifier.\n */\n name: function() {\n return this.get('name');\n },\n\n /**\n * Gets the url of the file. It is only available after you save the file or\n * after you get the file from a AV.Object.\n * @return {String}\n */\n url: function() {\n return this.get('url');\n },\n\n /**\n * Gets the attributs of the file object.\n * @param {String} The attribute name which want to get.\n * @returns {Any}\n */\n get: function(attrName) {\n switch (attrName) {\n case 'objectId':\n return this.id;\n case 'url':\n case 'name':\n case 'mime_type':\n case 'metaData':\n case 'createdAt':\n case 'updatedAt':\n return this.attributes[attrName];\n default:\n return this.attributes.metaData[attrName];\n }\n },\n\n /**\n * Set the metaData of the file object.\n * @param {Object} Object is an key value Object for setting metaData.\n * @param {String} attr is an optional metadata key.\n * @param {Object} value is an optional metadata value.\n * @returns {String|Number|Array|Object}\n */\n set: function(...args) {\n const set = (attrName, value) => {\n switch (attrName) {\n case 'name':\n case 'url':\n case 'mime_type':\n case 'base64':\n case 'metaData':\n this.attributes[attrName] = value;\n break;\n default:\n // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面\n this.attributes.metaData[attrName] = value;\n break;\n }\n };\n\n switch (args.length) {\n case 1:\n // 传入一个 Object\n for (var k in args[0]) {\n set(k, args[0][k]);\n }\n break;\n case 2:\n set(args[0], args[1]);\n break;\n }\n },\n\n /**\n *

Returns the file's metadata JSON object if no arguments is given.Returns the\n * metadata value if a key is given.Set metadata value if key and value are both given.

\n *

\n    *  var metadata = file.metaData(); //Get metadata JSON object.\n    *  var size = file.metaData('size');  // Get the size metadata value.\n    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.\n    *

\n * @return {Object} The file's metadata JSON object.\n * @param {String} attr an optional metadata key.\n * @param {Object} value an optional metadata value.\n **/\n metaData: function(attr, value) {\n if (attr && value) {\n this.attributes.metaData[attr] = value;\n return this;\n } else if (attr && !value) {\n return this.attributes.metaData[attr];\n } else {\n return this.attributes.metaData;\n }\n },\n\n /**\n * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。\n * @return {String} 缩略图URL\n * @param {Number} width 宽度,单位:像素\n * @param {Number} heigth 高度,单位:像素\n * @param {Number} quality 质量,1-100的数字,默认100\n * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。\n * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。\n */\n\n thumbnailURL: function(width, height, quality, scaleToFit, fmt) {\n const url = this.attributes.url;\n if (!url) {\n throw new Error('Invalid url.');\n }\n if (!width || !height || width <= 0 || height <= 0 ) {\n throw new Error('Invalid width or height value.');\n }\n quality = quality || 100;\n scaleToFit = !scaleToFit ? true : scaleToFit;\n if (quality <= 0 || quality > 100) {\n throw new Error('Invalid quality value.');\n }\n fmt = fmt || 'png';\n const mode = scaleToFit ? 2: 1;\n return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt;\n },\n\n /**\n * Returns the file's size.\n * @return {Number} The file's size in bytes.\n **/\n size: function() {\n return this.metaData().size;\n },\n\n /**\n * Returns the file's owner.\n * @return {String} The file's owner id.\n */\n ownerId: function() {\n return this.metaData().owner;\n },\n\n /**\n * Destroy the file.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n if (!this.id) {\n return Promise.reject(new Error('The file id is not eixsts.'));\n }\n var request = AVRequest(\"files\", null, this.id, 'DELETE', null, options);\n return request;\n },\n\n /**\n * Request Qiniu upload token\n * @param {string} type\n * @return {Promise} Resolved with the response\n * @private\n */\n _fileToken(type, route = 'fileTokens') {\n let name = this.attributes.name;\n\n let extName = extname(name);\n if (!extName && this._extName) {\n name += this._extName;\n extName = this._extName;\n }\n // Create 16-bits uuid as qiniu key.\n const key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName;\n const data = {\n key,\n name,\n ACL: this._acl,\n mime_type: type,\n metaData: this.attributes.metaData,\n };\n this._qiniu_key = key;\n return AVRequest(route, null, null, 'POST', data);\n },\n\n /**\n * @callback UploadProgressCallback\n * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes\n */\n /**\n * Saves the file to the AV cloud.\n * @param {Object} [options]\n * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。\n * @return {Promise} Promise that is resolved when the save finishes.\n */\n save(options) {\n if (this.id) {\n throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.');\n }\n if (!this._previousSave) {\n if (this._data) {\n let mimeType = this.get('mime_type');\n this._previousSave = this._fileToken(mimeType).then(uploadInfo => {\n if (uploadInfo.mime_type) {\n mimeType = uploadInfo.mime_type;\n this.set('mime_type', mimeType);\n }\n this._token = uploadInfo.token;\n return Promise.resolve().then(() => {\n const data = this._data;\n if (data && data.base64) {\n return parseBase64(data.base64, mimeType);\n }\n if (data && data.blob) {\n if (!data.blob.type && mimeType) {\n data.blob.type = mimeType;\n }\n if (!data.blob.name) {\n data.blob.name = this.get('name');\n }\n if (process.env.CLIENT_PLATFORM === 'ReactNative' || process.env.CLIENT_PLATFORM === 'Weapp') {\n this._extName = extname(data.blob.uri);\n }\n return data.blob;\n }\n if (typeof File !== \"undefined\" && data instanceof File) {\n if (data.size) {\n this.attributes.metaData.size = data.size;\n }\n if (data.name) {\n this._extName = extname(data.name);\n }\n return data;\n }\n if (typeof Buffer !== \"undefined\" && Buffer.isBuffer(data)) {\n this.attributes.metaData.size = data.length;\n return data;\n }\n throw new TypeError('malformed file data');\n }).then(data => {\n let uploadPromise;\n switch (uploadInfo.provider) {\n case 's3':\n uploadPromise = s3(uploadInfo, data, this, options);\n break;\n case 'qcloud':\n uploadPromise = cos(uploadInfo, data, this, options);\n break;\n case 'qiniu':\n default:\n uploadPromise = qiniu(uploadInfo, data, this, options);\n break;\n }\n return uploadPromise.then(\n tap(() => this._callback(true)),\n (error) => {\n this._callback(false);\n throw error;\n }\n );\n });\n });\n } else if (this.attributes.url && this.attributes.metaData.__source === 'external') {\n // external link file.\n const data = {\n name: this.attributes.name,\n ACL: this._acl,\n metaData: this.attributes.metaData,\n mime_type: this.mimeType,\n url: this.attributes.url,\n };\n this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then((response) => {\n this.attributes.name = response.name;\n this.attributes.url = response.url;\n this.id = response.objectId;\n if (response.size) {\n this.attributes.metaData.size = response.size;\n }\n return this;\n });\n }\n }\n return this._previousSave;\n },\n\n _callback(success) {\n AVRequest('fileCallback', null, null, 'post', {\n token: this._token,\n result: success,\n }).catch(debug);\n delete this._token;\n delete this._data;\n },\n\n /**\n * fetch the file from server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option.\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(options) {\n var options = null;\n\n var request = AVRequest('files', null, this.id, 'GET', options);\n return request.then(this._finishFetch.bind(this));\n },\n _finishFetch: function(response) {\n var value = AV.Object.prototype.parse(response);\n value.attributes = {\n name: value.name,\n url: value.url,\n mime_type: value.mime_type,\n bucket: value.bucket,\n };\n value.attributes.metaData = value.metaData || {};\n value.id = value.objectId;\n // clean\n delete value.objectId;\n delete value.metaData;\n delete value.url;\n delete value.name;\n delete value.mime_type;\n delete value.bucket;\n _.extend(this, value);\n return this;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/file.js","var _ = require('underscore');\n\n/*global navigator: false */\nmodule.exports = function(AV) {\n /**\n * Creates a new GeoPoint with any of the following forms:
\n * @example\n * new GeoPoint(otherGeoPoint)\n * new GeoPoint(30, 30)\n * new GeoPoint([30, 30])\n * new GeoPoint({latitude: 30, longitude: 30})\n * new GeoPoint() // defaults to (0, 0)\n * @class\n *\n *

Represents a latitude / longitude point that may be associated\n * with a key in a AVObject or used as a reference point for geo queries.\n * This allows proximity-based queries on the key.

\n *\n *

Only one key in a class may contain a GeoPoint.

\n *\n *

Example:

\n   *   var point = new AV.GeoPoint(30.0, -20.0);\n   *   var object = new AV.Object(\"PlaceObject\");\n   *   object.set(\"location\", point);\n   *   object.save();

\n */\n AV.GeoPoint = function(arg1, arg2) {\n if (_.isArray(arg1)) {\n AV.GeoPoint._validate(arg1[0], arg1[1]);\n this.latitude = arg1[0];\n this.longitude = arg1[1];\n } else if (_.isObject(arg1)) {\n AV.GeoPoint._validate(arg1.latitude, arg1.longitude);\n this.latitude = arg1.latitude;\n this.longitude = arg1.longitude;\n } else if (_.isNumber(arg1) && _.isNumber(arg2)) {\n AV.GeoPoint._validate(arg1, arg2);\n this.latitude = arg1;\n this.longitude = arg2;\n } else {\n this.latitude = 0;\n this.longitude = 0;\n }\n\n // Add properties so that anyone using Webkit or Mozilla will get an error\n // if they try to set values that are out of bounds.\n var self = this;\n if (this.__defineGetter__ && this.__defineSetter__) {\n // Use _latitude and _longitude to actually store the values, and add\n // getters and setters for latitude and longitude.\n this._latitude = this.latitude;\n this._longitude = this.longitude;\n this.__defineGetter__(\"latitude\", function() {\n return self._latitude;\n });\n this.__defineGetter__(\"longitude\", function() {\n return self._longitude;\n });\n this.__defineSetter__(\"latitude\", function(val) {\n AV.GeoPoint._validate(val, self.longitude);\n self._latitude = val;\n });\n this.__defineSetter__(\"longitude\", function(val) {\n AV.GeoPoint._validate(self.latitude, val);\n self._longitude = val;\n });\n }\n };\n\n /**\n * @lends AV.GeoPoint.prototype\n * @property {float} latitude North-south portion of the coordinate, in range\n * [-90, 90]. Throws an exception if set out of range in a modern browser.\n * @property {float} longitude East-west portion of the coordinate, in range\n * [-180, 180]. Throws if set out of range in a modern browser.\n */\n\n /**\n * Throws an exception if the given lat-long is out of bounds.\n * @private\n */\n AV.GeoPoint._validate = function(latitude, longitude) {\n if (latitude < -90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" < -90.0.\");\n }\n if (latitude > 90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" > 90.0.\");\n }\n if (longitude < -180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" < -180.0.\");\n }\n if (longitude > 180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" > 180.0.\");\n }\n };\n\n /**\n * Creates a GeoPoint with the user's current location, if available.\n * @return {Promise.}\n */\n AV.GeoPoint.current = () => new AV.Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(function(location) {\n resolve(new AV.GeoPoint({\n latitude: location.coords.latitude,\n longitude: location.coords.longitude\n }));\n }, reject);\n });\n\n AV.GeoPoint.prototype = {\n /**\n * Returns a JSON representation of the GeoPoint, suitable for AV.\n * @return {Object}\n */\n toJSON: function() {\n AV.GeoPoint._validate(this.latitude, this.longitude);\n return {\n \"__type\": \"GeoPoint\",\n latitude: this.latitude,\n longitude: this.longitude\n };\n },\n\n /**\n * Returns the distance from this GeoPoint to another in radians.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n radiansTo: function(point) {\n var d2r = Math.PI / 180.0;\n var lat1rad = this.latitude * d2r;\n var long1rad = this.longitude * d2r;\n var lat2rad = point.latitude * d2r;\n var long2rad = point.longitude * d2r;\n var deltaLat = lat1rad - lat2rad;\n var deltaLong = long1rad - long2rad;\n var sinDeltaLatDiv2 = Math.sin(deltaLat / 2);\n var sinDeltaLongDiv2 = Math.sin(deltaLong / 2);\n // Square of half the straight line chord distance between both points.\n var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) +\n (Math.cos(lat1rad) * Math.cos(lat2rad) *\n sinDeltaLongDiv2 * sinDeltaLongDiv2));\n a = Math.min(1.0, a);\n return 2 * Math.asin(Math.sqrt(a));\n },\n\n /**\n * Returns the distance from this GeoPoint to another in kilometers.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n kilometersTo: function(point) {\n return this.radiansTo(point) * 6371.0;\n },\n\n /**\n * Returns the distance from this GeoPoint to another in miles.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n milesTo: function(point) {\n return this.radiansTo(point) * 3958.8;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/geopoint.js","require('weapp-polyfill/auto-polyfill');\n\nmodule.exports = require('./index');\n\n\n\n// WEBPACK FOOTER //\n// ./src/index-weapp.js","const AV = require('./av');\nconst request = require('./request');\n\nconst initialize = (appId, appKey, masterKey, hookKey) => {\n if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) {\n console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.');\n }\n AV.applicationId = appId;\n AV.applicationKey = appKey;\n AV.masterKey = masterKey;\n if (!process.env.CLIENT_PLATFORM) {\n AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY;\n }\n AV._useMasterKey = false;\n};\n\nconst masterKeyWarn = () => {\n console.warn('MasterKey is not supposed to be used in browser.');\n};\n\n/**\n * Call this method first to set up your authentication tokens for AV.\n * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .\n * @function AV.init\n * @param {Object} options\n * @param {String} options.appId application id\n * @param {String} options.appKey application key\n * @param {String} options.masterKey application master key\n*/\n\nAV.init = (...args) => {\n if (args.length === 1) {\n const options = args[0];\n if (typeof options === 'object') {\n if (process.env.CLIENT_PLATFORM && options.masterKey) {\n masterKeyWarn();\n }\n initialize(options.appId, options.appKey, options.masterKey, options.hookKey);\n request.setServerUrlByRegion(options.region);\n } else {\n throw new Error('AV.init(): Parameter is not correct.');\n }\n } else {\n // 兼容旧版本的初始化方法\n if (process.env.CLIENT_PLATFORM && args[3]) {\n masterKeyWarn();\n }\n initialize(...args);\n request.setServerUrlByRegion('cn');\n }\n};\n\n// If we're running in node.js, allow using the master key.\nif (!process.env.CLIENT_PLATFORM) {\n AV.Cloud = AV.Cloud || {};\n /**\n * Switches the LeanCloud SDK to using the Master key. The Master key grants\n * priveleged access to the data in LeanCloud and can be used to bypass ACLs and\n * other restrictions that are applied to the client SDKs.\n *

Available in Cloud Code and Node.js only.\n *

\n */\n AV.Cloud.useMasterKey = function() {\n AV._useMasterKey = true;\n };\n}\n\n// 兼容老版本的初始化方法\nAV.initialize = AV.init;\n\n\n\n// WEBPACK FOOTER //\n// ./src/init.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * 包含了使用了 LeanCloud\n * 离线数据分析功能的函数。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @namespace\n */\n AV.Insight = AV.Insight || {};\n\n _.extend(AV.Insight, /** @lends AV.Insight */ {\n\n /**\n * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用\n * AV.Insight.JobQuery 查询任务状态和结果。\n * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
\n     *                   { \"sql\" : \"select count(*) as c,gender from _User group by gender\",\n     *                     \"saveAs\": {\n     *                         \"className\" : \"UserGender\",\n     *                         \"limit\": 1\n     *                      }\n     *                   }\n     *                  
\n * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n startJob: function(jobConfig, options) {\n if(!jobConfig || !jobConfig.sql) {\n throw new Error('Please provide the sql to run the job.');\n }\n var data = {\n jobConfig: jobConfig,\n appId: AV.applicationId\n };\n var request = AVRequest(\"bigquery\", 'jobs', null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).id;\n });\n },\n\n /**\n * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成\n * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息,\n * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。\n *\n */\n on: function(event, cb) {\n }\n });\n\n /**\n * 创建一个对象,用于查询 Insight 任务状态和结果。\n * @class\n * @param {String} id 任务 id\n * @since 0.5.5\n */\n AV.Insight.JobQuery = function(id, className) {\n if(!id) {\n throw new Error('Please provide the job id.');\n }\n this.id = id;\n this.className = className;\n this._skip = 0;\n this._limit = 100;\n };\n\n AV.Insight.JobQuery.prototype = {\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n this._limit = n;\n return this;\n },\n\n /**\n * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数,\n * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间\n * startTime、endTime 等信息。\n *\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n *\n */\n find: function(options) {\n var params = {\n skip: this._skip,\n limit: this._limit\n };\n\n var request = AVRequest(\"bigquery\", 'jobs', this.id, \"GET\",\n params, options);\n var self = this;\n return request.then(function(response) {\n if(response.error) {\n return AV.Promise.reject(new AVError(response.code, response.error));\n }\n return AV.Promise.resolve(response);\n });\n }\n\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/insight.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst utils = require('./utils');\n\nconst RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt'];\nconst checkReservedKey = key => {\n if (RESERVED_KEYS.indexOf(key) !== -1) {\n throw new Error(`key[${key}] is reserved`);\n }\n};\n\n// AV.Object is analogous to the Java AVObject.\n// It also implements the same interface as a Backbone model.\n\nmodule.exports = function(AV) {\n /**\n * Creates a new model with defined attributes. A client id (cid) is\n * automatically generated and assigned for you.\n *\n *

You won't normally call this method directly. It is recommended that\n * you use a subclass of AV.Object instead, created by calling\n * extend.

\n *\n *

However, if you don't want to use a subclass, or aren't sure which\n * subclass is appropriate, you can use this form:

\n   *     var object = new AV.Object(\"ClassName\");\n   * 
\n * That is basically equivalent to:
\n   *     var MyClass = AV.Object.extend(\"ClassName\");\n   *     var object = new MyClass();\n   * 

\n *\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @see AV.Object.extend\n *\n * @class\n *\n *

The fundamental unit of AV data, which implements the Backbone Model\n * interface.

\n */\n AV.Object = function(attributes, options) {\n // Allow new AV.Object(\"ClassName\") as a shortcut to _create.\n if (_.isString(attributes)) {\n return AV.Object._create.apply(this, arguments);\n }\n\n attributes = attributes || {};\n if (options && options.parse) {\n attributes = this.parse(attributes);\n attributes = this._mergeMagicFields(attributes);\n }\n var defaults = AV._getValue(this, 'defaults');\n if (defaults) {\n attributes = _.extend({}, defaults, attributes);\n }\n if (options && options.collection) {\n this.collection = options.collection;\n }\n\n this._serverData = {}; // The last known data for this object from cloud.\n this._opSetQueue = [{}]; // List of sets of changes to the data.\n this._flags = {};\n this.attributes = {}; // The best estimate of this's current data.\n\n this._hashedJSON = {}; // Hash of values of containers at last save.\n this._escapedAttributes = {};\n this.cid = _.uniqueId('c');\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this.set(attributes, { silent: true });\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this._hasData = true;\n this._previousAttributes = _.clone(this.attributes);\n this.initialize.apply(this, arguments);\n };\n\n /**\n * @lends AV.Object.prototype\n * @property {String} id The objectId of the AV Object.\n */\n\n /**\n * Saves the given list of AV.Object.\n * If any error is encountered, stops and calls the error handler.\n *\n *
\n   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {\n   *     // All the objects were saved.\n   *   }, function(error) {\n   *     // An error occurred while saving one of the objects.\n   *   });\n   *\n   * @param {Array} list A list of AV.Object.\n   */\n  AV.Object.saveAll = function(list, options) {\n    return AV.Object._deepSaveAsync(list, null, options);\n  };\n\n  /**\n   * Fetch the given list of AV.Object.\n   *\n   * @param {AV.Object[]} objects A list of AV.Object\n   * @param {AuthOptions} options\n   * @return {Promise.} The given list of AV.Object, updated\n   */\n\n  AV.Object.fetchAll = (objects, options) =>\n    AV.Promise.resolve().then(() =>\n      AVRequest('batch', null, null, 'POST', {\n        requests: _.map(objects, object => {\n          if (!object.className) throw new Error('object must have className to fetch');\n          if (!object.id) throw new Error('object must have id to fetch');\n          if (object.dirty()) throw new Error('object is modified but not saved');\n          return {\n            method: 'GET',\n            path: `/1.1/classes/${object.className}/${object.id}`,\n          };\n        }),\n      }, options)\n    ).then(function(response) {\n      _.forEach(objects, function(object, i) {\n        if (response[i].success) {\n          object._finishFetch(\n            object.parse(response[i].success));\n        } else {\n          const error = new Error(response[i].error.error);\n          error.code = response[i].error.code;\n          throw error;\n        }\n      });\n      return objects;\n    });\n\n  // Attach all inheritable methods to the AV.Object prototype.\n  _.extend(AV.Object.prototype, AV.Events,\n           /** @lends AV.Object.prototype */ {\n    _fetchWhenSave: false,\n\n    /**\n     * Initialize is an empty function by default. Override it with your own\n     * initialization logic.\n     */\n    initialize: function(){},\n\n   /**\n     * Set whether to enable fetchWhenSave option when updating object.\n     * When set true, SDK would fetch the latest object after saving.\n     * Default is false.\n     *\n     * @deprecated use AV.Object#save with options.fetchWhenSave instead\n     * @param {boolean} enable  true to enable fetchWhenSave option.\n     */\n    fetchWhenSave: function(enable){\n      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');\n      if (!_.isBoolean(enable)) {\n        throw new Error('Expect boolean value for fetchWhenSave');\n      }\n      this._fetchWhenSave = enable;\n    },\n\n   /**\n    * Returns the object's objectId.\n    * @return {String} the objectId.\n    */\n    getObjectId: function() {\n      return this.id;\n    },\n\n   /**\n    * Returns the object's createdAt attribute.\n    * @return {Date}\n    */\n    getCreatedAt: function() {\n      return this.createdAt || this.get('createdAt');\n    },\n\n   /**\n    * Returns the object's updatedAt attribute.\n    * @return {Date}\n    */\n    getUpdatedAt: function() {\n      return this.updatedAt || this.get('updatedAt');\n    },\n\n    /**\n     * Returns a JSON version of the object suitable for saving to AV.\n     * @return {Object}\n     */\n    toJSON: function() {\n      var json = this._toFullJSON();\n      AV._arrayEach([\"__type\", \"className\"],\n                       function(key) { delete json[key]; });\n      return json;\n    },\n\n    _toFullJSON: function(seenObjects) {\n      var json = _.clone(this.attributes);\n      AV._objectEach(json, function(val, key) {\n        json[key] = AV._encode(val, seenObjects);\n      });\n      AV._objectEach(this._operations, function(val, key) {\n        json[key] = val;\n      });\n\n      if (_.has(this, \"id\")) {\n        json.objectId = this.id;\n      }\n      _(['createdAt', 'updatedAt']).each((key) => {\n        if (_.has(this, key)) {\n          const val = this[key];\n          json[key] = _.isDate(val) ? val.toJSON() : val;\n        }\n      });\n      json.__type = \"Object\";\n      json.className = this.className;\n      return json;\n    },\n\n    /**\n     * Updates _hashedJSON to reflect the current state of this object.\n     * Adds any changed hash values to the set of pending changes.\n     * @private\n     */\n    _refreshCache: function() {\n      var self = this;\n      if (self._refreshingCache) {\n        return;\n      }\n      self._refreshingCache = true;\n      AV._objectEach(this.attributes, function(value, key) {\n        if (value instanceof AV.Object) {\n          value._refreshCache();\n        } else if (_.isObject(value)) {\n          if (self._resetCacheForKey(key)) {\n            self.set(key, new AV.Op.Set(value), { silent: true });\n          }\n        }\n      });\n      delete self._refreshingCache;\n    },\n\n    /**\n     * Returns true if this object has been modified since its last\n     * save/refresh.  If an attribute is specified, it returns true only if that\n     * particular attribute has been modified since the last save/refresh.\n     * @param {String} attr An attribute name (optional).\n     * @return {Boolean}\n     */\n    dirty: function(attr) {\n      this._refreshCache();\n\n      var currentChanges = _.last(this._opSetQueue);\n\n      if (attr) {\n        return (currentChanges[attr] ? true : false);\n      }\n      if (!this.id) {\n        return true;\n      }\n      if (_.keys(currentChanges).length > 0) {\n        return true;\n      }\n      return false;\n    },\n\n    /**\n     * Gets a Pointer referencing this Object.\n     * @private\n     */\n    _toPointer: function() {\n      // if (!this.id) {\n      //   throw new Error(\"Can't serialize an unsaved AV.Object\");\n      // }\n      return { __type: \"Pointer\",\n               className: this.className,\n               objectId: this.id };\n    },\n\n    /**\n     * Gets the value of an attribute.\n     * @param {String} attr The string name of an attribute.\n     */\n    get: function(attr) {\n      switch (attr) {\n        case 'objectId':\n          return this.id;\n        case 'createdAt':\n        case 'updatedAt':\n          return this[attr];\n        default:\n          return this.attributes[attr];\n      }\n    },\n\n    /**\n     * Gets a relation on the given class for the attribute.\n     * @param {String} attr The attribute to get the relation for.\n     * @return {AV.Relation}\n     */\n    relation: function(attr) {\n      var value = this.get(attr);\n      if (value) {\n        if (!(value instanceof AV.Relation)) {\n          throw new Error(\"Called relation() on non-relation field \" + attr);\n        }\n        value._ensureParentAndKey(this, attr);\n        return value;\n      } else {\n        return new AV.Relation(this, attr);\n      }\n    },\n\n    /**\n     * Gets the HTML-escaped value of an attribute.\n     */\n    escape: function(attr) {\n      var html = this._escapedAttributes[attr];\n      if (html) {\n        return html;\n      }\n      var val = this.attributes[attr];\n      var escaped;\n      if (utils.isNullOrUndefined(val)) {\n        escaped = '';\n      } else {\n        escaped = _.escape(val.toString());\n      }\n      this._escapedAttributes[attr] = escaped;\n      return escaped;\n    },\n\n    /**\n     * Returns true if the attribute contains a value that is not\n     * null or undefined.\n     * @param {String} attr The string name of the attribute.\n     * @return {Boolean}\n     */\n    has: function(attr) {\n      return !utils.isNullOrUndefined(this.attributes[attr]);\n    },\n\n    /**\n     * Pulls \"special\" fields like objectId, createdAt, etc. out of attrs\n     * and puts them on \"this\" directly.  Removes them from attrs.\n     * @param attrs - A dictionary with the data for this AV.Object.\n     * @private\n     */\n    _mergeMagicFields: function(attrs) {\n      // Check for changes of magic fields.\n      var model = this;\n      var specialFields = [\"objectId\", \"createdAt\", \"updatedAt\"];\n      AV._arrayEach(specialFields, function(attr) {\n        if (attrs[attr]) {\n          if (attr === \"objectId\") {\n            model.id = attrs[attr];\n          } else if ((attr === \"createdAt\" || attr === \"updatedAt\") &&\n                     !_.isDate(attrs[attr])) {\n            model[attr] = AV._parseDate(attrs[attr]);\n          } else { \n            model[attr] = attrs[attr]; \n          }\n          delete attrs[attr];\n        }\n      });\n      return attrs;\n    },\n\n    /**\n     * Returns the json to be sent to the server.\n     * @private\n     */\n    _startSave: function() {\n      this._opSetQueue.push({});\n    },\n\n    /**\n     * Called when a save fails because of an error. Any changes that were part\n     * of the save need to be merged with changes made after the save. This\n     * might throw an exception is you do conflicting operations. For example,\n     * if you do:\n     *   object.set(\"foo\", \"bar\");\n     *   object.set(\"invalid field name\", \"baz\");\n     *   object.save();\n     *   object.increment(\"foo\");\n     * then this will throw when the save fails and the client tries to merge\n     * \"bar\" with the +1.\n     * @private\n     */\n    _cancelSave: function() {\n      var self = this;\n      var failedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      var nextChanges = _.first(this._opSetQueue);\n      AV._objectEach(failedChanges, function(op, key) {\n        var op1 = failedChanges[key];\n        var op2 = nextChanges[key];\n        if (op1 && op2) {\n          nextChanges[key] = op2._mergeWithPrevious(op1);\n        } else if (op1) {\n          nextChanges[key] = op1;\n        }\n      });\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a save completes successfully. This merges the changes that\n     * were saved into the known server data, and overrides it with any data\n     * sent directly from the server.\n     * @private\n     */\n    _finishSave: function(serverData) {\n      // Grab a copy of any object referenced by this object. These instances\n      // may have already been fetched, and we don't want to lose their data.\n      // Note that doing it like this means we will unify separate copies of the\n      // same object, but that's a risk we have to take.\n      var fetchedObjects = {};\n      AV._traverse(this.attributes, function(object) {\n        if (object instanceof AV.Object && object.id && object._hasData) {\n          fetchedObjects[object.id] = object;\n        }\n      });\n\n      var savedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      this._applyOpSet(savedChanges, this._serverData);\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n\n        // Look for any objects that might have become unfetched and fix them\n        // by replacing their values with the previously observed values.\n        var fetched = AV._traverse(self._serverData[key], function(object) {\n          if (object instanceof AV.Object && fetchedObjects[object.id]) {\n            return fetchedObjects[object.id];\n          }\n        });\n        if (fetched) {\n          self._serverData[key] = fetched;\n        }\n      });\n      this._rebuildAllEstimatedData();\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a fetch or login is complete to set the known server data to\n     * the given object.\n     * @private\n     */\n    _finishFetch: function(serverData, hasData) {\n      // Clear out any changes the user might have made previously.\n      this._opSetQueue = [{}];\n\n      // Bring in all the new server data.\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n      });\n\n      // Refresh the attributes.\n      this._rebuildAllEstimatedData();\n\n      // Clear out the cache of mutable containers.\n      this._refreshCache();\n      this._opSetQueue = [{}];\n\n      this._hasData = hasData;\n    },\n\n    /**\n     * Applies the set of AV.Op in opSet to the object target.\n     * @private\n     */\n    _applyOpSet: function(opSet, target) {\n      var self = this;\n      AV._objectEach(opSet, function(change, key) {\n        target[key] = change._estimate(target[key], self, key);\n        if (target[key] === AV.Op._UNSET) {\n          delete target[key];\n        }\n      });\n    },\n\n    /**\n     * Replaces the cached value for key with the current value.\n     * Returns true if the new value is different than the old value.\n     * @private\n     */\n    _resetCacheForKey: function(key) {\n      var value = this.attributes[key];\n      if (_.isObject(value) &&\n          !(value instanceof AV.Object) &&\n          !(value instanceof AV.File)) {\n\n        value = value.toJSON ? value.toJSON() : value;\n        var json = JSON.stringify(value);\n        if (this._hashedJSON[key] !== json) {\n          var wasSet = !! this._hashedJSON[key];\n          this._hashedJSON[key] = json;\n          return wasSet;\n        }\n      }\n      return false;\n    },\n\n    /**\n     * Populates attributes[key] by starting with the last known data from the\n     * server, and applying all of the local changes that have been made to that\n     * key since then.\n     * @private\n     */\n    _rebuildEstimatedDataForKey: function(key) {\n      var self = this;\n      delete this.attributes[key];\n      if (this._serverData[key]) {\n        this.attributes[key] = this._serverData[key];\n      }\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        var op = opSet[key];\n        if (op) {\n          self.attributes[key] = op._estimate(self.attributes[key], self, key);\n          if (self.attributes[key] === AV.Op._UNSET) {\n            delete self.attributes[key];\n          } else {\n            self._resetCacheForKey(key);\n          }\n        }\n      });\n    },\n\n    /**\n     * Populates attributes by starting with the last known data from the\n     * server, and applying all of the local changes that have been made since\n     * then.\n     * @private\n     */\n    _rebuildAllEstimatedData: function() {\n      var self = this;\n\n      var previousAttributes = _.clone(this.attributes);\n\n      this.attributes = _.clone(this._serverData);\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        self._applyOpSet(opSet, self.attributes);\n        AV._objectEach(opSet, function(op, key) {\n          self._resetCacheForKey(key);\n        });\n      });\n\n      // Trigger change events for anything that changed because of the fetch.\n      AV._objectEach(previousAttributes, function(oldValue, key) {\n        if (self.attributes[key] !== oldValue) {\n          self.trigger('change:' + key, self, self.attributes[key], {});\n        }\n      });\n      AV._objectEach(this.attributes, function(newValue, key) {\n        if (!_.has(previousAttributes, key)) {\n          self.trigger('change:' + key, self, newValue, {});\n        }\n      });\n    },\n\n    /**\n     * Sets a hash of model attributes on the object, firing\n     * \"change\" unless you choose to silence it.\n     *\n     * 

You can call it with an object containing keys and values, or with one\n * key and value. For example:

\n     *   gameTurn.set({\n     *     player: player1,\n     *     diceRoll: 2\n     *   }, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"currentPlayer\", player2, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"finished\", true);

\n *\n * @param {String} key The key to set.\n * @param {Any} value The value to give it.\n * @param {Object} [options]\n * @param {Boolean} [options.silent]\n * @return {AV.Object} self if succeeded, throws if the value is not valid.\n * @see AV.Object#validate\n */\n set: function(key, value, options) {\n var attrs;\n if (_.isObject(key) || utils.isNullOrUndefined(key)) {\n attrs = _.mapObject(key, function(v, k) {\n checkReservedKey(k);\n return AV._decode(v, k);\n });\n options = value;\n } else {\n attrs = {};\n checkReservedKey(key);\n attrs[key] = AV._decode(value, key);\n }\n\n // Extract attributes and options.\n options = options || {};\n if (!attrs) {\n return this;\n }\n if (attrs instanceof AV.Object) {\n attrs = attrs.attributes;\n }\n\n // If the unset option is used, every attribute should be a Unset.\n if (options.unset) {\n AV._objectEach(attrs, function(unused_value, key) {\n attrs[key] = new AV.Op.Unset();\n });\n }\n\n // Apply all the attributes to get the estimated values.\n var dataToValidate = _.clone(attrs);\n var self = this;\n AV._objectEach(dataToValidate, function(value, key) {\n if (value instanceof AV.Op) {\n dataToValidate[key] = value._estimate(self.attributes[key],\n self, key);\n if (dataToValidate[key] === AV.Op._UNSET) {\n delete dataToValidate[key];\n }\n }\n });\n\n // Run validation.\n this._validate(attrs, options);\n\n options.changes = {};\n var escaped = this._escapedAttributes;\n var prev = this._previousAttributes || {};\n\n // Update attributes.\n AV._arrayEach(_.keys(attrs), function(attr) {\n var val = attrs[attr];\n\n // If this is a relation object we need to set the parent correctly,\n // since the location where it was parsed does not have access to\n // this object.\n if (val instanceof AV.Relation) {\n val.parent = self;\n }\n\n if (!(val instanceof AV.Op)) {\n val = new AV.Op.Set(val);\n }\n\n // See if this change will actually have any effect.\n var isRealChange = true;\n if (val instanceof AV.Op.Set &&\n _.isEqual(self.attributes[attr], val.value)) {\n isRealChange = false;\n }\n\n if (isRealChange) {\n delete escaped[attr];\n if (options.silent) {\n self._silent[attr] = true;\n } else {\n options.changes[attr] = true;\n }\n }\n\n var currentChanges = _.last(self._opSetQueue);\n currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]);\n self._rebuildEstimatedDataForKey(attr);\n\n if (isRealChange) {\n self.changed[attr] = self.attributes[attr];\n if (!options.silent) {\n self._pending[attr] = true;\n }\n } else {\n delete self.changed[attr];\n delete self._pending[attr];\n }\n });\n\n if (!options.silent) {\n this.change(options);\n }\n return this;\n },\n\n /**\n * Remove an attribute from the model, firing \"change\" unless\n * you choose to silence it. This is a noop if the attribute doesn't\n * exist.\n */\n unset: function(attr, options) {\n options = options || {};\n options.unset = true;\n return this.set(attr, null, options);\n },\n\n /**\n * Atomically increments the value of the given attribute the next time the\n * object is saved. If no amount is specified, 1 is used by default.\n *\n * @param attr {String} The key.\n * @param amount {Number} The amount to increment by.\n */\n increment: function(attr, amount) {\n if (_.isUndefined(amount) || _.isNull(amount)) {\n amount = 1;\n }\n return this.set(attr, new AV.Op.Increment(amount));\n },\n\n /**\n * Atomically add an object to the end of the array associated with a given\n * key.\n * @param attr {String} The key.\n * @param item {} The item to add.\n */\n add: function(attr, item) {\n return this.set(attr, new AV.Op.Add(utils.ensureArray(item)));\n },\n\n /**\n * Atomically add an object to the array associated with a given key, only\n * if it is not already present in the array. The position of the insert is\n * not guaranteed.\n *\n * @param attr {String} The key.\n * @param item {} The object to add.\n */\n addUnique: function(attr, item) {\n return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item)));\n },\n\n /**\n * Atomically remove all instances of an object from the array associated\n * with a given key.\n *\n * @param attr {String} The key.\n * @param item {} The object to remove.\n */\n remove: function(attr, item) {\n return this.set(attr, new AV.Op.Remove(utils.ensureArray(item)));\n },\n\n /**\n * Returns an instance of a subclass of AV.Op describing what kind of\n * modification has been performed on this field since the last time it was\n * saved. For example, after calling object.increment(\"x\"), calling\n * object.op(\"x\") would return an instance of AV.Op.Increment.\n *\n * @param attr {String} The key.\n * @returns {AV.Op} The operation, or undefined if none.\n */\n op: function(attr) {\n return _.last(this._opSetQueue)[attr];\n },\n\n /**\n * Clear all attributes on the model, firing \"change\" unless\n * you choose to silence it.\n */\n clear: function(options) {\n options = options || {};\n options.unset = true;\n var keysToClear = _.extend(this.attributes, this._operations);\n return this.set(keysToClear, options);\n },\n\n /**\n * Returns a JSON-encoded set of operations to be sent with the next save\n * request.\n * @private\n */\n _getSaveJSON: function() {\n var json = _.clone(_.first(this._opSetQueue));\n AV._objectEach(json, function(op, key) {\n json[key] = op.toJSON();\n });\n return json;\n },\n\n /**\n * Returns true if this object can be serialized for saving.\n * @private\n */\n _canBeSerialized: function() {\n return AV.Object._canBeSerializedAsValue(this.attributes);\n },\n\n /**\n * Fetch the model from the server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * triggering a \"change\" event.\n * @param {Object} fetchOptions Optional options to set 'keys' and\n * 'include' option.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(fetchOptions = {}, options) {\n if (_.isArray(fetchOptions.keys)) {\n fetchOptions.keys = fetchOptions.keys.join(',');\n }\n if (_.isArray(fetchOptions.include)) {\n fetchOptions.include = fetchOptions.include.join(',');\n }\n\n var self = this;\n var request = AVRequest('classes', this.className, this.id, 'GET',\n fetchOptions, options);\n return request.then(function(response) {\n self._finishFetch(self.parse(response), true);\n return self;\n });\n },\n\n /**\n * Set a hash of model attributes, and save the model to the server.\n * updatedAt will be updated when the request returns.\n * You can either call it as:
\n     *   object.save();
\n * or
\n     *   object.save(null, options);
\n * or
\n     *   object.save(attrs, options);
\n * or
\n     *   object.save(key, value, options);
\n *\n * For example,
\n     *   gameTurn.save({\n     *     player: \"Jake Cutter\",\n     *     diceRoll: 2\n     *   }).then(function(gameTurnAgain) {\n     *     // The save was successful.\n     *   }, function(error) {\n     *     // The save failed.  Error is an instance of AVError.\n     *   });
\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded\n * @param {AV.Query} options.query Save object only when it matches the query\n * @return {AV.Promise} A promise that is fulfilled when the save\n * completes.\n * @see AVError\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n\n options = _.clone(options) || {};\n if (options.wait) {\n current = _.clone(this.attributes);\n }\n\n var setOptions = _.clone(options) || {};\n if (setOptions.wait) {\n setOptions.silent = true;\n }\n if (attrs) {\n this.set(attrs, setOptions);\n }\n\n var model = this;\n\n // If there is any unsaved child, save it first.\n model._refreshCache();\n\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(model.attributes,\n unsavedChildren,\n unsavedFiles);\n if (unsavedChildren.length + unsavedFiles.length > 0) {\n return AV.Object._deepSaveAsync(this.attributes, model, options).then(function() {\n return model.save(null, options);\n });\n }\n\n this._startSave();\n this._saving = (this._saving || 0) + 1;\n\n this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve();\n this._allPreviousSaves = this._allPreviousSaves.catch(e => {}).then(function() {\n var method = model.id ? 'PUT' : 'POST';\n\n var json = model._getSaveJSON();\n\n if(model._fetchWhenSave){\n //Sepcial-case fetchWhenSave when updating object.\n json._fetchWhenSave = true;\n }\n\n if (options.fetchWhenSave) {\n json._fetchWhenSave = true;\n }\n if (options.query) {\n var queryJSON;\n if (typeof options.query.toJSON === 'function') {\n queryJSON = options.query.toJSON();\n if (queryJSON) {\n json._where = queryJSON.where;\n }\n }\n if (!json._where) {\n var error = new Error('options.query is not an AV.Query');\n throw error;\n }\n }\n\n _.extend(json, model._flags);\n\n var route = \"classes\";\n var className = model.className;\n if (model.className === \"_User\" && !model.id) {\n // Special-case user sign-up.\n route = \"users\";\n className = null;\n }\n //hook makeRequest in options.\n var makeRequest = options._makeRequest || AVRequest;\n var request = makeRequest(route, className, model.id, method, json, options);\n\n request = request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n if (options.wait) {\n serverAttrs = _.extend(attrs || {}, serverAttrs);\n }\n model._finishSave(serverAttrs);\n if (options.wait) {\n model.set(current, setOptions);\n }\n return model;\n\n }, function(error) {\n model._cancelSave();\n throw error;\n });\n\n return request;\n });\n return this._allPreviousSaves;\n },\n\n /**\n * Destroy this model on the server if it was already persisted.\n * Optimistically removes the model from its collection, if it has one.\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} [options.wait] wait for the server to respond\n * before removal.\n *\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n options = options || {};\n var model = this;\n\n var triggerDestroy = function() {\n model.trigger('destroy', model, model.collection, options);\n };\n\n if (!this.id) {\n return triggerDestroy();\n }\n\n if (!options.wait) {\n triggerDestroy();\n }\n\n var request =\n AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options);\n return request.then(function() {\n if (options.wait) {\n triggerDestroy();\n }\n return model;\n });\n },\n\n /**\n * Converts a response into the hash of attributes to be set on the model.\n * @ignore\n */\n parse: function(resp) {\n var output = _.clone(resp);\n _([\"createdAt\", \"updatedAt\"]).each(function(key) {\n if (output[key]) {\n output[key] = AV._parseDate(output[key]);\n }\n });\n if (!output.updatedAt) {\n output.updatedAt = output.createdAt;\n }\n return output;\n },\n\n /**\n * Creates a new model with identical attributes to this one.\n * @return {AV.Object}\n */\n clone: function() {\n return new this.constructor(this.attributes);\n },\n\n /**\n * Returns true if this object has never been saved to AV.\n * @return {Boolean}\n */\n isNew: function() {\n return !this.id;\n },\n\n /**\n * Call this method to manually fire a `\"change\"` event for this model and\n * a `\"change:attribute\"` event for each changed attribute.\n * Calling this will cause all objects observing the model to update.\n */\n change: function(options) {\n options = options || {};\n var changing = this._changing;\n this._changing = true;\n\n // Silent changes become pending changes.\n var self = this;\n AV._objectEach(this._silent, function(attr) {\n self._pending[attr] = true;\n });\n\n // Silent changes are triggered.\n var changes = _.extend({}, options.changes, this._silent);\n this._silent = {};\n AV._objectEach(changes, function(unused_value, attr) {\n self.trigger('change:' + attr, self, self.get(attr), options);\n });\n if (changing) {\n return this;\n }\n\n // This is to get around lint not letting us make a function in a loop.\n var deleteChanged = function(value, attr) {\n if (!self._pending[attr] && !self._silent[attr]) {\n delete self.changed[attr];\n }\n };\n\n // Continue firing `\"change\"` events while there are pending changes.\n while (!_.isEmpty(this._pending)) {\n this._pending = {};\n this.trigger('change', this, options);\n // Pending and silent changes still remain.\n AV._objectEach(this.changed, deleteChanged);\n self._previousAttributes = _.clone(this.attributes);\n }\n\n this._changing = false;\n return this;\n },\n\n /**\n * Determine if the model has changed since the last \"change\"\n * event. If you specify an attribute name, determine if that attribute\n * has changed.\n * @param {String} attr Optional attribute name\n * @return {Boolean}\n */\n hasChanged: function(attr) {\n if (!arguments.length) {\n return !_.isEmpty(this.changed);\n }\n return this.changed && _.has(this.changed, attr);\n },\n\n /**\n * Returns an object containing all the attributes that have changed, or\n * false if there are no changed attributes. Useful for determining what\n * parts of a view need to be updated and/or what attributes need to be\n * persisted to the server. Unset attributes will be set to undefined.\n * You can also pass an attributes object to diff against the model,\n * determining if there *would be* a change.\n */\n changedAttributes: function(diff) {\n if (!diff) {\n return this.hasChanged() ? _.clone(this.changed) : false;\n }\n var changed = {};\n var old = this._previousAttributes;\n AV._objectEach(diff, function(diffVal, attr) {\n if (!_.isEqual(old[attr], diffVal)) {\n changed[attr] = diffVal;\n }\n });\n return changed;\n },\n\n /**\n * Gets the previous value of an attribute, recorded at the time the last\n * \"change\" event was fired.\n * @param {String} attr Name of the attribute to get.\n */\n previous: function(attr) {\n if (!arguments.length || !this._previousAttributes) {\n return null;\n }\n return this._previousAttributes[attr];\n },\n\n /**\n * Gets all of the attributes of the model at the time of the previous\n * \"change\" event.\n * @return {Object}\n */\n previousAttributes: function() {\n return _.clone(this._previousAttributes);\n },\n\n /**\n * Checks if the model is currently in a valid state. It's only possible to\n * get into an *invalid* state if you're using silent changes.\n * @return {Boolean}\n */\n isValid: function() {\n try {\n this.validate(this.attributes);\n } catch (error) {\n return false;\n }\n return true;\n },\n\n /**\n * You should not call this function directly unless you subclass\n * AV.Object, in which case you can override this method\n * to provide additional validation on set and\n * save. Your implementation should throw an Error if\n * the attrs is invalid\n *\n * @param {Object} attrs The current data to validate.\n * @see AV.Object#set\n */\n validate: function(attrs) {\n if (_.has(attrs, \"ACL\") && !(attrs.ACL instanceof AV.ACL)) {\n throw new AVError(AVError.OTHER_CAUSE,\n \"ACL must be a AV.ACL.\");\n }\n },\n\n /**\n * Run validation against a set of incoming attributes, returning `true`\n * if all is well. If a specific `error` callback has been passed,\n * call that instead of firing the general `\"error\"` event.\n * @private\n */\n _validate: function(attrs, options) {\n if (options.silent || !this.validate) {\n return;\n }\n attrs = _.extend({}, this.attributes, attrs);\n this.validate(attrs);\n },\n\n /**\n * Returns the ACL for this object.\n * @returns {AV.ACL} An instance of AV.ACL.\n * @see AV.Object#get\n */\n getACL: function() {\n return this.get(\"ACL\");\n },\n\n /**\n * Sets the ACL to be used for this object.\n * @param {AV.ACL} acl An instance of AV.ACL.\n * @param {Object} options Optional Backbone-like options object to be\n * passed in to set.\n * @return {Boolean} Whether the set passed validation.\n * @see AV.Object#set\n */\n setACL: function(acl, options) {\n return this.set(\"ACL\", acl, options);\n },\n\n disableBeforeHook: function() {\n this.ignoreHook('beforeSave');\n this.ignoreHook('beforeUpdate');\n this.ignoreHook('beforeDelete');\n },\n\n disableAfterHook: function() {\n this.ignoreHook('afterSave');\n this.ignoreHook('afterUpdate');\n this.ignoreHook('afterDelete');\n },\n\n ignoreHook: function(hookName) {\n if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) {\n console.trace('Unsupported hookName: ' + hookName);\n }\n\n if (!AV.hookKey) {\n console.trace('ignoreHook required hookKey');\n }\n\n if (!this._flags.__ignore_hooks) {\n this._flags.__ignore_hooks = [];\n }\n\n this._flags.__ignore_hooks.push(hookName);\n }\n });\n\n /**\n * Creates an instance of a subclass of AV.Object for the give classname\n * and id.\n * @param {String} className The name of the AV class backing this model.\n * @param {String} id The object id of this model.\n * @return {AV.Object} A new subclass instance of AV.Object.\n */\n AV.Object.createWithoutData = function(className, id, hasData){\n var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n result.id = id;\n result._hasData = hasData;\n return result;\n };\n /**\n * Delete objects in batch.\n * @param {AV.Object[]} objects The AV.Object array to be deleted.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n AV.Object.destroyAll = function(objects, options = {}){\n if (!objects || objects.length === 0){\n\t\t return AV.Promise.resolve();\n }\n const objectsByClassNameAndFlags = _.groupBy(objects, object => JSON.stringify({\n className: object.className,\n flags: object._flags\n }));\n const body = {\n requests: _.map(objectsByClassNameAndFlags, objects => {\n const ids = _.map(objects, 'id').join(',');\n return {\n method: 'DELETE',\n path: `/1.1/classes/${objects[0].className}/${ids}`,\n body: objects[0]._flags\n }\n })\n };\n return AVRequest('batch', null, null, 'POST', body, options);\n };\n\n /**\n * Returns the appropriate subclass for making new instances of the given\n * className string.\n * @private\n */\n AV.Object._getSubclass = function(className) {\n if (!_.isString(className)) {\n throw new Error('AV.Object._getSubclass requires a string argument.');\n }\n var ObjectClass = AV.Object._classMap[className];\n if (!ObjectClass) {\n ObjectClass = AV.Object.extend(className);\n AV.Object._classMap[className] = ObjectClass;\n }\n return ObjectClass;\n };\n\n /**\n * Creates an instance of a subclass of AV.Object for the given classname.\n * @private\n */\n AV.Object._create = function(className, attributes, options, noDefaultACL) {\n var ObjectClass = AV.Object._getSubclass(className);\n return new ObjectClass(attributes, options, noDefaultACL);\n };\n\n // Set up a map of className to class so that we can create new instances of\n // AV Objects from JSON automatically.\n AV.Object._classMap = {};\n\n AV.Object._extend = AV._extend;\n\n /**\n * Creates a new model with defined attributes,\n * It's the same with\n *
\n   *   new AV.Object(attributes, options);\n   *  
\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @return {AV.Object}\n * @since v0.4.4\n * @see AV.Object\n * @see AV.Object.extend\n */\n AV.Object['new'] = function(attributes, options){\n return new AV.Object(attributes, options);\n };\n\n /**\n * Creates a new subclass of AV.Object for the given AV class name.\n *\n *

Every extension of a AV class will inherit from the most recent\n * previous extension of that class. When a AV.Object is automatically\n * created by parsing JSON, it will use the most recent extension of that\n * class.

\n *\n *

You should call either:

\n   *     var MyClass = AV.Object.extend(\"MyClass\", {\n   *         Instance properties\n   *     }, {\n   *         Class properties\n   *     });
\n * or, for Backbone compatibility:
\n   *     var MyClass = AV.Object.extend({\n   *         className: \"MyClass\",\n   *         Other instance properties\n   *     }, {\n   *         Class properties\n   *     });

\n *\n * @param {String} className The name of the AV class backing this model.\n * @param {Object} protoProps Instance properties to add to instances of the\n * class returned from this method.\n * @param {Object} classProps Class properties to add the class returned from\n * this method.\n * @return {Class} A new subclass of AV.Object.\n */\n AV.Object.extend = function(className, protoProps, classProps) {\n // Handle the case with only two args.\n if (!_.isString(className)) {\n if (className && _.has(className, \"className\")) {\n return AV.Object.extend(className.className, className, protoProps);\n } else {\n throw new Error(\n \"AV.Object.extend's first argument should be the className.\");\n }\n }\n\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n className = \"_User\";\n }\n\n var NewClassObject = null;\n if (_.has(AV.Object._classMap, className)) {\n var OldClassObject = AV.Object._classMap[className];\n // This new subclass has been told to extend both from \"this\" and from\n // OldClassObject. This is multiple inheritance, which isn't supported.\n // For now, let's just pick one.\n if (protoProps || classProps) {\n NewClassObject = OldClassObject._extend(protoProps, classProps);\n } else {\n return OldClassObject;\n }\n } else {\n protoProps = protoProps || {};\n protoProps._className = className;\n NewClassObject = this._extend(protoProps, classProps);\n }\n // Extending a subclass should reuse the classname automatically.\n NewClassObject.extend = function(arg0) {\n if (_.isString(arg0) || (arg0 && _.has(arg0, \"className\"))) {\n return AV.Object.extend.apply(NewClassObject, arguments);\n }\n var newArguments = [className].concat(_.toArray(arguments));\n return AV.Object.extend.apply(NewClassObject, newArguments);\n };\n NewClassObject['new'] = function(attributes, options){\n return new NewClassObject(attributes, options);\n };\n AV.Object._classMap[className] = NewClassObject;\n return NewClassObject;\n };\n\n // ES6 class syntax support\n Object.defineProperty(AV.Object.prototype, 'className', {\n get: function(){\n const className = this._className || this.constructor._LCClassName || this.constructor.name;\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n return \"_User\";\n }\n return className;\n },\n });\n\n /**\n * Register a class.\n * If a subclass of AV.Object is defined with your own implement\n * rather then AV.Object.extend, the subclass must be registered.\n * @param {Function} klass A subclass of AV.Object\n * @param {String} [name] Specify the name of the class. Useful when the class might be uglified.\n * @example\n * class Person extend AV.Object {}\n * AV.Object.register(Person);\n */\n AV.Object.register = (klass, name) => {\n if (!(klass.prototype instanceof AV.Object)) {\n throw new Error('registered class is not a subclass of AV.Object');\n }\n const className = name || klass.name;\n if (!className.length) {\n throw new Error('registered class must be named');\n }\n if (name) {\n klass._LCClassName = name;\n }\n AV.Object._classMap[className] = klass;\n };\n\n AV.Object._findUnsavedChildren = function(object, children, files) {\n AV._traverse(object, function(object) {\n if (object instanceof AV.Object) {\n object._refreshCache();\n if (object.dirty()) {\n children.push(object);\n }\n return;\n }\n\n if (object instanceof AV.File) {\n if (!object.url() && !object.id) {\n files.push(object);\n }\n return;\n }\n });\n };\n\n AV.Object._canBeSerializedAsValue = function(object) {\n var canBeSerializedAsValue = true;\n\n if (object instanceof AV.Object || object instanceof AV.File) {\n canBeSerializedAsValue = !!object.id;\n\n } else if (_.isArray(object)) {\n AV._arrayEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n\n } else if (_.isObject(object)) {\n AV._objectEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n }\n\n return canBeSerializedAsValue;\n };\n\n AV.Object._deepSaveAsync = function(object, model, options) {\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles);\n if(model) {\n unsavedChildren = _.filter(unsavedChildren, function(object) {\n return object != model;\n });\n }\n\n var promise = AV.Promise.resolve();\n _.each(unsavedFiles, function(file) {\n promise = promise.then(function() {\n return file.save();\n });\n });\n\n var objects = _.uniq(unsavedChildren);\n var remaining = _.uniq(objects);\n\n return promise.then(function() {\n return AV.Promise._continueWhile(function() {\n return remaining.length > 0;\n }, function() {\n\n // Gather up all the objects that can be saved in this batch.\n var batch = [];\n var newRemaining = [];\n AV._arrayEach(remaining, function(object) {\n // Limit batches to 20 objects.\n if (batch.length > 20) {\n newRemaining.push(object);\n return;\n }\n\n if (object._canBeSerialized()) {\n batch.push(object);\n } else {\n newRemaining.push(object);\n }\n });\n remaining = newRemaining;\n\n // If we can't save any objects, there must be a circular reference.\n if (batch.length === 0) {\n return AV.Promise.reject(\n new AVError(AVError.OTHER_CAUSE,\n \"Tried to save a batch with a cycle.\"));\n }\n\n // Reserve a spot in every object's save queue.\n var readyToStart = AV.Promise.resolve(_.map(batch, function(object) {\n return object._allPreviousSaves || AV.Promise.resolve();\n }));\n\n // Save a single batch, whether previous saves succeeded or failed.\n const bathSavePromise = readyToStart.then(() =>\n AVRequest(\"batch\", null, null, \"POST\", {\n requests: _.map(batch, function(object) {\n var json = object._getSaveJSON();\n _.extend(json, object._flags);\n var method = \"POST\";\n\n var path = \"/1.1/classes/\" + object.className;\n if (object.id) {\n path = path + \"/\" + object.id;\n method = \"PUT\";\n }\n\n object._startSave();\n\n return {\n method: method,\n path: path,\n body: json\n };\n })\n\n }, options).then(function(response) {\n var error;\n AV._arrayEach(batch, function(object, i) {\n if (response[i].success) {\n object._finishSave(\n object.parse(response[i].success));\n } else {\n error = error || response[i].error;\n object._cancelSave();\n }\n });\n if (error) {\n return AV.Promise.reject(\n new AVError(error.code, error.error));\n }\n\n })\n );\n AV._arrayEach(batch, function(object) {\n object._allPreviousSaves = bathSavePromise;\n });\n return bathSavePromise;\n });\n }).then(function() {\n return object;\n });\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/object.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n\n /**\n * @private\n * @class\n * A AV.Op is an atomic operation that can be applied to a field in a\n * AV.Object. For example, calling object.set(\"foo\", \"bar\")\n * is an example of a AV.Op.Set. Calling object.unset(\"foo\")\n * is a AV.Op.Unset. These operations are stored in a AV.Object and\n * sent to the server as part of object.save() operations.\n * Instances of AV.Op should be immutable.\n *\n * You should not create subclasses of AV.Op or instantiate AV.Op\n * directly.\n */\n AV.Op = function() {\n this._initialize.apply(this, arguments);\n };\n\n AV.Op.prototype = {\n _initialize: function() {}\n };\n\n _.extend(AV.Op, {\n /**\n * To create a new Op, call AV.Op._extend();\n * @private\n */\n _extend: AV._extend,\n\n // A map of __op string to decoder function.\n _opDecoderMap: {},\n\n /**\n * Registers a function to convert a json object with an __op field into an\n * instance of a subclass of AV.Op.\n * @private\n */\n _registerDecoder: function(opName, decoder) {\n AV.Op._opDecoderMap[opName] = decoder;\n },\n\n /**\n * Converts a json object into an instance of a subclass of AV.Op.\n * @private\n */\n _decode: function(json) {\n var decoder = AV.Op._opDecoderMap[json.__op];\n if (decoder) {\n return decoder(json);\n } else {\n return undefined;\n }\n }\n });\n\n /*\n * Add a handler for Batch ops.\n */\n AV.Op._registerDecoder(\"Batch\", function(json) {\n var op = null;\n AV._arrayEach(json.ops, function(nextOp) {\n nextOp = AV.Op._decode(nextOp);\n op = nextOp._mergeWithPrevious(op);\n });\n return op;\n });\n\n /**\n * @private\n * @class\n * A Set operation indicates that either the field was changed using\n * AV.Object.set, or it is a mutable container that was detected as being\n * changed.\n */\n AV.Op.Set = AV.Op._extend(/** @lends AV.Op.Set.prototype */ {\n _initialize: function(value) {\n this._value = value;\n },\n\n /**\n * Returns the new value of this field after the set.\n */\n value: function() {\n return this._value;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return AV._encode(this.value());\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return this.value();\n }\n });\n\n /**\n * A sentinel value that is returned by AV.Op.Unset._estimate to\n * indicate the field should be deleted. Basically, if you find _UNSET as a\n * value in your object, you should remove that key.\n */\n AV.Op._UNSET = {};\n\n /**\n * @private\n * @class\n * An Unset operation indicates that this field has been deleted from the\n * object.\n */\n AV.Op.Unset = AV.Op._extend(/** @lends AV.Op.Unset.prototype */ {\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Delete\" };\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return AV.Op._UNSET;\n }\n });\n\n AV.Op._registerDecoder(\"Delete\", function(json) {\n return new AV.Op.Unset();\n });\n\n /**\n * @private\n * @class\n * An Increment is an atomic operation where the numeric value for the field\n * will be increased by a given amount.\n */\n AV.Op.Increment = AV.Op._extend(\n /** @lends AV.Op.Increment.prototype */ {\n\n _initialize: function(amount) {\n this._amount = amount;\n },\n\n /**\n * Returns the amount to increment by.\n * @return {Number} the amount to increment by.\n */\n amount: function() {\n return this._amount;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Increment\", amount: this._amount };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.amount());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(previous.value() + this.amount());\n } else if (previous instanceof AV.Op.Increment) {\n return new AV.Op.Increment(this.amount() + previous.amount());\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return this.amount();\n }\n return oldValue + this.amount();\n }\n });\n\n AV.Op._registerDecoder(\"Increment\", function(json) {\n return new AV.Op.Increment(json.amount);\n });\n\n /**\n * @private\n * @class\n * Add is an atomic operation where the given objects will be appended to the\n * array that is stored in this field.\n */\n AV.Op.Add = AV.Op._extend(/** @lends AV.Op.Add.prototype */ {\n _initialize: function(objects) {\n this._objects = objects;\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Add\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Add) {\n return new AV.Op.Add(previous.objects().concat(this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n return oldValue.concat(this.objects());\n }\n }\n });\n\n AV.Op._registerDecoder(\"Add\", function(json) {\n return new AV.Op.Add(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * AddUnique is an atomic operation where the given items will be appended to\n * the array that is stored in this field only if they were not already\n * present in the array.\n */\n AV.Op.AddUnique = AV.Op._extend(\n /** @lends AV.Op.AddUnique.prototype */ {\n\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"AddUnique\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.AddUnique) {\n return new AV.Op.AddUnique(this._estimate(previous.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n // We can't just take the _.uniq(_.union(...)) of oldValue and\n // this.objects, because the uniqueness may not apply to oldValue\n // (especially if the oldValue was set via .set())\n var newValue = _.clone(oldValue);\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n var matchingObj = _.find(newValue, function(anObj) {\n return (anObj instanceof AV.Object) && (anObj.id === obj.id);\n });\n if (!matchingObj) {\n newValue.push(obj);\n } else {\n var index = _.indexOf(newValue, matchingObj);\n newValue[index] = obj;\n }\n } else if (!_.contains(newValue, obj)) {\n newValue.push(obj);\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddUnique\", function(json) {\n return new AV.Op.AddUnique(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * Remove is an atomic operation where the given objects will be removed from\n * the array that is stored in this field.\n */\n AV.Op.Remove = AV.Op._extend(/** @lends AV.Op.Remove.prototype */ {\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be removed from the array.\n * @return {Array} The objects to be removed from the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Remove\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return previous;\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Remove) {\n return new AV.Op.Remove(_.union(previous.objects(), this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return [];\n } else {\n var newValue = _.difference(oldValue, this.objects());\n // If there are saved AV Objects being removed, also remove them.\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n newValue = _.reject(newValue, function(other) {\n return (other instanceof AV.Object) && (other.id === obj.id);\n });\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"Remove\", function(json) {\n return new AV.Op.Remove(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * A Relation operation indicates that the field is an instance of\n * AV.Relation, and objects are being added to, or removed from, that\n * relation.\n */\n AV.Op.Relation = AV.Op._extend(\n /** @lends AV.Op.Relation.prototype */ {\n\n _initialize: function(adds, removes) {\n this._targetClassName = null;\n\n var self = this;\n\n var pointerToId = function(object) {\n if (object instanceof AV.Object) {\n if (!object.id) {\n throw new Error('You can\\'t add an unsaved AV.Object to a relation.');\n }\n if (!self._targetClassName) {\n self._targetClassName = object.className;\n }\n if (self._targetClassName !== object.className) {\n throw new Error(\"Tried to create a AV.Relation with 2 different types: \" +\n self._targetClassName + \" and \" + object.className + \".\");\n }\n return object.id;\n }\n return object;\n };\n\n this.relationsToAdd = _.uniq(_.map(adds, pointerToId));\n this.relationsToRemove = _.uniq(_.map(removes, pointerToId));\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being added to the\n * relation.\n * @return {Array}\n */\n added: function() {\n var self = this;\n return _.map(this.relationsToAdd, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being removed from\n * the relation.\n * @return {Array}\n */\n removed: function() {\n var self = this;\n return _.map(this.relationsToRemove, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n var adds = null;\n var removes = null;\n var self = this;\n var idToPointer = function(id) {\n return { __type: 'Pointer',\n className: self._targetClassName,\n objectId: id };\n };\n var pointers = null;\n if (this.relationsToAdd.length > 0) {\n pointers = _.map(this.relationsToAdd, idToPointer);\n adds = { \"__op\": \"AddRelation\", \"objects\": pointers };\n }\n\n if (this.relationsToRemove.length > 0) {\n pointers = _.map(this.relationsToRemove, idToPointer);\n removes = { \"__op\": \"RemoveRelation\", \"objects\": pointers };\n }\n\n if (adds && removes) {\n return { \"__op\": \"Batch\", \"ops\": [adds, removes]};\n }\n\n return adds || removes || {};\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n throw new Error('You can\\'t modify a relation after deleting it.');\n } else if (previous instanceof AV.Op.Relation) {\n if (previous._targetClassName &&\n previous._targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be of class \" + previous._targetClassName +\n \", but \" + this._targetClassName + \" was passed in.\");\n }\n var newAdd = _.union(_.difference(previous.relationsToAdd,\n this.relationsToRemove),\n this.relationsToAdd);\n var newRemove = _.union(_.difference(previous.relationsToRemove,\n this.relationsToAdd),\n this.relationsToRemove);\n\n var newRelation = new AV.Op.Relation(newAdd, newRemove);\n newRelation._targetClassName = this._targetClassName;\n return newRelation;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue, object, key) {\n if (!oldValue) {\n var relation = new AV.Relation(object, key);\n relation.targetClassName = this._targetClassName;\n } else if (oldValue instanceof AV.Relation) {\n if (this._targetClassName) {\n if (oldValue.targetClassName) {\n if (oldValue.targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be a \" + oldValue.targetClassName +\n \", but a \" + this._targetClassName + \" was passed in.\");\n }\n } else {\n oldValue.targetClassName = this._targetClassName;\n }\n }\n return oldValue;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddRelation\", function(json) {\n return new AV.Op.Relation(AV._decode(json.objects), []);\n });\n AV.Op._registerDecoder(\"RemoveRelation\", function(json) {\n return new AV.Op.Relation([], AV._decode(json.objects));\n });\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/op.js","const AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n AV.Installation = AV.Object.extend(\"_Installation\");\n\n /**\n * @namespace\n */\n AV.Push = AV.Push || {};\n\n /**\n * Sends a push notification.\n * @param {Object} data The data of the push notification.\n * @param {String[]} [data.channels] An Array of channels to push to.\n * @param {Date} [data.push_time] A Date object for when to send the push.\n * @param {Date} [data.expiration_time] A Date object for when to expire\n * the push.\n * @param {Number} [data.expiration_interval] The seconds from now to expire the push.\n * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {Date} data.data The data to send as part of the push\n * @param {AuthOptions} [options]\n * @return {Promise}\n */\n AV.Push.send = function(data, options) {\n if (data.where) {\n data.where = data.where.toJSON().where;\n }\n\n if(data.where && data.cql){\n throw new Error(\"Both where and cql can't be set\");\n }\n\n if (data.push_time) {\n data.push_time = data.push_time.toJSON();\n }\n\n if (data.expiration_time) {\n data.expiration_time = data.expiration_time.toJSON();\n }\n\n if (data.expiration_time && data.expiration_time_interval) {\n throw new Error(\"Both expiration_time and expiration_time_interval can't be set\");\n }\n\n var request = AVRequest('push', null, null, 'POST', data, options);\n return request;\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/push.js","const _ = require('underscore');\nconst debug = require('debug')('leancloud:query');\nconst Promise = require('./promise');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst { ensureArray } = require('./utils');\n\nconst requires = (value, message) => {\n if (value === undefined) {\n throw new Error(message);\n }\n};\n\n// AV.Query is a way to create a list of AV.Objects.\nmodule.exports = function(AV) {\n /**\n * Creates a new AV.Query for the given AV.Object subclass.\n * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string.\n * @class\n *\n *

AV.Query defines a query that is used to fetch AV.Objects. The\n * most common use case is finding all objects that match a query through the\n * find method. For example, this sample code fetches all objects\n * of class MyClass. It calls a different function depending on\n * whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.find().then(function(results) {\n   *   // results is an array of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to retrieve a single object whose id is\n * known, through the get method. For example, this sample code fetches an\n * object of class MyClass and id myId. It calls a\n * different function depending on whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.get(myId).then(function(object) {\n   *   // object is an instance of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to count the number of objects that match\n * the query without retrieving all of those objects. For example, this\n * sample code counts the number of objects of the class MyClass\n *

\n   * var query = new AV.Query(MyClass);\n   * query.count().then(function(number) {\n   *   // There are number instances of MyClass.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n */\n AV.Query = function(objectClass) {\n if (_.isString(objectClass)) {\n objectClass = AV.Object._getSubclass(objectClass);\n }\n\n this.objectClass = objectClass;\n\n this.className = objectClass.prototype.className;\n\n this._where = {};\n this._include = [];\n this._select = [];\n this._limit = -1; // negative limit means, do not send a limit\n this._skip = 0;\n this._extraOptions = {};\n };\n\n /**\n * Constructs a AV.Query that is the OR of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.or(query1, query2, query3);
\n *\n * will create a compoundQuery that is an or of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to OR.\n * @return {AV.Query} The query that is the OR of the passed in queries.\n */\n AV.Query.or = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._orQuery(queries);\n return query;\n };\n\n /**\n * Constructs a AV.Query that is the AND of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.and(query1, query2, query3);
\n *\n * will create a compoundQuery that is an 'and' of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to AND.\n * @return {AV.Query} The query that is the AND of the passed in queries.\n */\n AV.Query.and = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._andQuery(queries);\n return query;\n };\n\n /**\n * Retrieves a list of AVObjects that satisfy the CQL.\n * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n *\n * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n * @param {Array} pvalues An array contains placeholder values.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n AV.Query.doCloudQuery = function(cql, pvalues, options) {\n var params = { cql: cql };\n if(_.isArray(pvalues)){\n params.pvalues = pvalues;\n } else {\n options = pvalues;\n }\n\n var request = AVRequest('cloudQuery', null, null, 'GET', params, options);\n return request.then(function(response) {\n //query to process results.\n var query = new AV.Query(response.className);\n var results = _.map(response.results, function(json) {\n var obj = query._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(query._processResult(json), true);\n }\n return obj;\n });\n return {\n results: results,\n count: response.count,\n className: response.className\n };\n });\n };\n\n AV.Query._extend = AV._extend;\n\n AV.Query.prototype = {\n //hook to iterate result. Added by dennis.\n _processResult: function(obj){\n return obj;\n },\n\n /**\n * Constructs an AV.Object whose id is already known by fetching data from\n * the server.\n *\n * @param {String} objectId The id of the object to be fetched.\n * @param {AuthOptions} options\n * @return {Promise.}\n */\n get: function(objectId, options) {\n if(!objectId) {\n var errorObject = new AVError(AVError.OBJECT_NOT_FOUND,\n \"Object not found.\");\n throw errorObject;\n }\n\n var self = this;\n\n var obj = self._newObject();\n obj.id = objectId;\n\n var queryJSON = self.toJSON();\n var fetchOptions = {};\n\n if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;\n if (queryJSON.include) fetchOptions.include = queryJSON.include;\n\n return obj.fetch(fetchOptions, options);\n },\n\n /**\n * Returns a JSON representation of this query.\n * @return {Object}\n */\n toJSON: function() {\n var params = {\n where: this._where\n };\n\n if (this._include.length > 0) {\n params.include = this._include.join(\",\");\n }\n if (this._select.length > 0) {\n params.keys = this._select.join(\",\");\n }\n if (this._limit >= 0) {\n params.limit = this._limit;\n }\n if (this._skip > 0) {\n params.skip = this._skip;\n }\n if (this._order !== undefined) {\n params.order = this._order;\n }\n\n AV._objectEach(this._extraOptions, function(v, k) {\n params[k] = v;\n });\n\n return params;\n },\n\n _newObject: function(response){\n var obj;\n if (response && response.className) {\n obj = new AV.Object(response.className);\n } else {\n obj = new this.objectClass();\n }\n return obj;\n },\n _createRequest(params = this.toJSON(), options) {\n if (JSON.stringify(params).length > 2000) {\n const body = {\n requests: [{\n method: 'GET',\n path: `/1.1/classes/${this.className}`,\n params,\n }],\n };\n return AVRequest('batch', null, null, 'POST', body, options)\n .then(response => {\n const result = response[0];\n if (result.success) {\n return result.success;\n }\n const error = new Error(result.error.error || 'Unknown batch error');\n error.code = result.error.code;\n throw error;\n });\n }\n return AVRequest('classes', this.className, null, \"GET\", params, options);\n },\n\n _parseResponse(response) {\n return _.map(response.results, (json) => {\n var obj = this._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(this._processResult(json), true);\n }\n return obj;\n });\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find(options) {\n const request = this._createRequest(undefined, options);\n return request.then(this._parseResponse.bind(this));\n },\n\n /**\n * scan a Query. masterKey required.\n *\n * @since 2.1.0\n * @param {object} [options]\n * @param {string} [options.orderedBy] specify the key to sort\n * @param {number} [options.batchSize] specify the batch size for each request\n * @param {AuthOptions} [authOptions]\n * @return {AsyncIterator.}\n * @example const scan = new AV.Query(TestClass).scan({\n * orderedBy: 'objectId',\n * batchSize: 10,\n * }, {\n * useMasterKey: true,\n * });\n * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next()));\n * getTen().then(results => {\n * // results are fisrt 10 instances of TestClass\n * return getTen();\n * }).then(results => {\n * // 11 - 20\n * });\n */\n scan({\n orderedBy,\n batchSize,\n } = {}, authOptions) {\n const condition = this.toJSON();\n debug('scan %O', condition);\n if (condition.order) {\n console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.');\n delete condition.order;\n }\n if (condition.skip) {\n console.warn('The skip option of the query is ignored for Query#scan.');\n delete condition.skip;\n }\n if (condition.limit) {\n console.warn('The limit option of the query is ignored for Query#scan.');\n delete condition.limit;\n }\n if (orderedBy) condition.scan_key = orderedBy;\n if (batchSize) condition.limit = batchSize;\n let promise = Promise.resolve([]);\n let cursor;\n let done = false;\n return {\n next: () => {\n promise = promise.then((remainResults) => {\n if (done) return [];\n if (remainResults.length > 1) return remainResults;\n // no cursor means we have reached the end\n // except for the first time\n if (!cursor && remainResults.length !== 0) {\n done = true;\n return remainResults;\n }\n // when only 1 item left in queue\n // start the next request to see if it is the last one\n return AVRequest(\n 'scan/classes',\n this.className,\n null,\n 'GET',\n cursor ? _.extend({}, condition, { cursor }) : condition,\n authOptions\n ).then(response => {\n cursor = response.cursor;\n return this._parseResponse(response);\n }).then(results => {\n if (!results.length) done = true;\n return remainResults.concat(results);\n });\n });\n return promise\n .then(remainResults => remainResults.shift())\n .then(result => ({\n value: result,\n done,\n }));\n },\n };\n },\n\n /**\n * Delete objects retrieved by this query.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n destroyAll: function(options){\n var self = this;\n return self.find(options).then(function(objects){\n return AV.Object.destroyAll(objects, options);\n });\n },\n\n /**\n * Counts the number of objects that match this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the count when\n * the query completes.\n */\n count: function(options) {\n var params = this.toJSON();\n params.limit = 0;\n params.count = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return response.count;\n });\n },\n\n /**\n * Retrieves at most one AV.Object that satisfies this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the object when\n * the query completes.\n */\n first: function(options) {\n var self = this;\n\n var params = this.toJSON();\n params.limit = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return _.map(response.results, function(json) {\n var obj = self._newObject();\n if (obj._finishFetch) {\n obj._finishFetch(self._processResult(json), true);\n }\n return obj;\n })[0];\n });\n },\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n requires(n, 'undefined is not a valid skip value');\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n requires(n, 'undefined is not a valid limit value');\n this._limit = n;\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that the AV.Object must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n equalTo: function(key, value) {\n requires(key, 'undefined is not a valid key');\n requires(value, 'undefined is not a valid value');\n this._where[key] = AV._encode(value);\n return this;\n },\n\n /**\n * Helper for condition queries\n * @private\n */\n _addCondition: function(key, condition, value) {\n requires(key, 'undefined is not a valid condition key');\n requires(condition, 'undefined is not a valid condition');\n requires(value, 'undefined is not a valid condition value');\n\n // Check if we already have a condition\n if (!this._where[key]) {\n this._where[key] = {};\n }\n this._where[key][condition] = AV._encode(value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular\n * array key's length to be equal to the provided value.\n * @param {String} key The array key to check.\n * @param value The length value.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n sizeEqualTo: function(key, value) {\n this._addCondition(key, \"$size\", value);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be not equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that must not be equalled.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notEqualTo: function(key, value) {\n this._addCondition(key, \"$ne\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThan: function(key, value) {\n this._addCondition(key, \"$lt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThan: function(key, value) {\n this._addCondition(key, \"$gt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$lte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$gte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containedIn: function(key, values) {\n this._addCondition(key, \"$in\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * not be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notContainedIn: function(key, values) {\n this._addCondition(key, \"$nin\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * contain each one of the provided list of values.\n * @param {String} key The key to check. This key's value must be an array.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containsAll: function(key, values) {\n this._addCondition(key, \"$all\", values);\n return this;\n },\n\n\n /**\n * Add a constraint for finding objects that contain the given key.\n * @param {String} key The key that should exist.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n exists: function(key) {\n this._addCondition(key, \"$exists\", true);\n return this;\n },\n\n /**\n * Add a constraint for finding objects that do not contain a given key.\n * @param {String} key The key that should not exist\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotExist: function(key) {\n this._addCondition(key, \"$exists\", false);\n return this;\n },\n\n /**\n * Add a regular expression constraint for finding string values that match\n * the provided regular expression.\n * This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {RegExp} regex The regular expression pattern to match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matches: function(key, regex, modifiers) {\n this._addCondition(key, \"$regex\", regex);\n if (!modifiers) { modifiers = \"\"; }\n // Javascript regex options support mig as inline options but store them\n // as properties of the object. We support mi & should migrate them to\n // modifiers\n if (regex.ignoreCase) { modifiers += 'i'; }\n if (regex.multiline) { modifiers += 'm'; }\n\n if (modifiers && modifiers.length) {\n this._addCondition(key, \"$options\", modifiers);\n }\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value matches a AV.Query\n * constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$inQuery\", queryJSON);\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not matches a\n * AV.Query constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$notInQuery\", queryJSON);\n return this;\n },\n\n\n /**\n * Add a constraint that requires that a key's value matches a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * matched.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$select\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not match a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * excluded.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$dontSelect\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add constraint that at least one of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _orQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$or = queryJSON;\n return this;\n },\n\n /**\n * Add constraint that both of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _andQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$and = queryJSON;\n return this;\n },\n\n\n /**\n * Converts a string into a regex that matches it.\n * Surrounding with \\Q .. \\E does this, we just need to escape \\E's in\n * the text separately.\n * @private\n */\n _quote: function(s) {\n return \"\\\\Q\" + s.replace(\"\\\\E\", \"\\\\E\\\\\\\\E\\\\Q\") + \"\\\\E\";\n },\n\n /**\n * Add a constraint for finding string values that contain a provided\n * string. This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} substring The substring that the value must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n contains: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that start with a provided\n * string. This query will use the backend index, so it will be fast even\n * for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} prefix The substring that the value must start with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n startsWith: function(key, value) {\n this._addCondition(key, \"$regex\", \"^\" + this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that end with a provided\n * string. This will be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} suffix The substring that the value must end with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n endsWith: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value) + \"$\");\n return this;\n },\n\n /**\n * Sorts the results in ascending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n ascending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = key;\n return this;\n },\n\n /**\n * Also sorts the results in ascending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addAscending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',' + key;\n else\n this._order = key;\n return this;\n },\n\n /**\n * Sorts the results in descending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n descending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = \"-\" + key;\n return this;\n },\n\n /**\n * Also sorts the results in descending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addDescending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',-' + key;\n else\n this._order = '-' + key;\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n near: function(key, point) {\n if (!(point instanceof AV.GeoPoint)) {\n // Try to cast it to a GeoPoint, so that near(\"loc\", [20,30]) works.\n point = new AV.GeoPoint(point);\n }\n this._addCondition(key, \"$nearSphere\", point);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param maxDistance Maximum distance (in radians) of results to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinRadians: function(key, point, distance) {\n this.near(key, point);\n this._addCondition(key, \"$maxDistance\", distance);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 3958.8 miles.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in miles) of results to\n * return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinMiles: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 3958.8);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 6371.0 kilometers.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in kilometers) of results\n * to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinKilometers: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 6371.0);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's\n * coordinates be contained within a given rectangular geographic bounding\n * box.\n * @param {String} key The key to be constrained.\n * @param {AV.GeoPoint} southwest\n * The lower-left inclusive corner of the box.\n * @param {AV.GeoPoint} northeast\n * The upper-right inclusive corner of the box.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinGeoBox: function(key, southwest, northeast) {\n if (!(southwest instanceof AV.GeoPoint)) {\n southwest = new AV.GeoPoint(southwest);\n }\n if (!(northeast instanceof AV.GeoPoint)) {\n northeast = new AV.GeoPoint(northeast);\n }\n this._addCondition(key, '$within', { '$box': [southwest, northeast] });\n return this;\n },\n\n /**\n * Include nested AV.Objects for the provided key. You can use dot\n * notation to specify which fields in the included object are also fetch.\n * @param {String[]} keys The name of the key to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n include: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._include = this._include.concat(ensureArray(keys))\n });\n return this;\n },\n\n /**\n * Restrict the fields of the returned AV.Objects to include only the\n * provided keys. If this is called multiple times, then all of the keys\n * specified in each of the calls will be included.\n * @param {String[]} keys The names of the keys to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n select: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._select = this._select.concat(ensureArray(keys));\n });\n return this;\n },\n\n /**\n * Iterates over each result of a query, calling a callback for each one. If\n * the callback returns a promise, the iteration will not continue until\n * that promise has been fulfilled. If the callback returns a rejected\n * promise, then iteration will stop with that error. The items are\n * processed in an unspecified order. The query may not have any sort order,\n * and may not use limit or skip.\n * @param callback {Function} Callback that will be called with each result\n * of the query.\n * @return {Promise} A promise that will be fulfilled once the\n * iteration has completed.\n */\n each: function(callback, options = {}) {\n\n if (this._order || this._skip || (this._limit >= 0)) {\n var error =\n new Error(\"Cannot iterate on a query with sort, skip, or limit.\");\n return AV.Promise.reject(error);\n }\n\n var query = new AV.Query(this.objectClass);\n // We can override the batch size from the options.\n // This is undocumented, but useful for testing.\n query._limit = options.batchSize || 100;\n query._where = _.clone(this._where);\n query._include = _.clone(this._include);\n\n query.ascending('objectId');\n\n var finished = false;\n return AV.Promise._continueWhile(function() {\n return !finished;\n\n }, function() {\n return query.find(options).then(function(results) {\n var callbacksDone = AV.Promise.resolve();\n _.each(results, function(result) {\n callbacksDone = callbacksDone.then(function() {\n return callback(result);\n });\n });\n\n return callbacksDone.then(function() {\n if (results.length >= query._limit) {\n query.greaterThan(\"objectId\", results[results.length - 1].id);\n } else {\n finished = true;\n }\n });\n });\n });\n }\n };\n\n AV.FriendShipQuery = AV.Query._extend({\n _objectClass: AV.User,\n _newObject: function(){\n return new AV.User();\n },\n _processResult: function(json){\n if(json && json[this._friendshipTag]) {\n var user = json[this._friendshipTag];\n if(user.__type === 'Pointer' && user.className === '_User'){\n delete user.__type;\n delete user.className;\n }\n return user;\n } else {\n return null;\n }\n },\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/query.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n /**\n * Creates a new Relation for the given parent object and key. This\n * constructor should rarely be used directly, but rather created by\n * {@link AV.Object#relation}.\n * @param {AV.Object} parent The parent of this relation.\n * @param {String} key The key for this relation on the parent.\n * @see AV.Object#relation\n * @class\n *\n *

\n * A class that is used to access all of the children of a many-to-many\n * relationship. Each instance of AV.Relation is associated with a\n * particular parent object and key.\n *

\n */\n AV.Relation = function(parent, key) {\n if (! _.isString(key)) {\n throw new TypeError('key must be a string');\n }\n this.parent = parent;\n this.key = key;\n this.targetClassName = null;\n };\n\n /**\n * Creates a query that can be used to query the parent objects in this relation.\n * @param {String} parentClass The parent class or name.\n * @param {String} relationKey The relation field key in parent.\n * @param {AV.Object} child The child object.\n * @return {AV.Query}\n */\n AV.Relation.reverseQuery = function(parentClass, relationKey, child){\n var query = new AV.Query(parentClass);\n query.equalTo(relationKey, child._toPointer());\n return query;\n };\n\n AV.Relation.prototype = {\n /**\n * Makes sure that this relation has the right parent and key.\n * @private\n */\n _ensureParentAndKey: function(parent, key) {\n this.parent = this.parent || parent;\n this.key = this.key || key;\n if (this.parent !== parent) {\n throw new Error(\"Internal Error. Relation retrieved from two different Objects.\");\n }\n if (this.key !== key) {\n throw new Error(\"Internal Error. Relation retrieved from two different keys.\");\n }\n },\n\n /**\n * Adds a AV.Object or an array of AV.Objects to the relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to add.\n */\n add: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation(objects, []);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Removes a AV.Object or an array of AV.Objects from this relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to remove.\n */\n remove: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation([], objects);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Returns a JSON version of the object suitable for saving to disk.\n * @return {Object}\n */\n toJSON: function() {\n return { \"__type\": \"Relation\", \"className\": this.targetClassName };\n },\n\n /**\n * Returns a AV.Query that is limited to objects in this\n * relation.\n * @return {AV.Query}\n */\n query: function() {\n var targetClass;\n var query;\n if (!this.targetClassName) {\n targetClass = AV.Object._getSubclass(this.parent.className);\n query = new AV.Query(targetClass);\n query._extraOptions.redirectClassNameForKey = this.key;\n } else {\n targetClass = AV.Object._getSubclass(this.targetClassName);\n query = new AV.Query(targetClass);\n }\n query._addCondition(\"$relatedTo\", \"object\", this.parent._toPointer());\n query._addCondition(\"$relatedTo\", \"key\", this.key);\n\n return query;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/relation.js","const _ = require('underscore');\nconst AVError = require('./error');\n\nmodule.exports = function(AV) {\n AV.Role = AV.Object.extend(\"_Role\", /** @lends AV.Role.prototype */ {\n // Instance Methods\n\n /**\n * Represents a Role on the AV server. Roles represent groupings of\n * Users for the purposes of granting permissions (e.g. specifying an ACL\n * for an Object). Roles are specified by their sets of child users and\n * child roles, all of which are granted any permissions that the parent\n * role has.\n *\n *

Roles must have a name (which cannot be changed after creation of the\n * role), and must specify an ACL.

\n * An AV.Role is a local representation of a role persisted to the AV\n * cloud.\n * @class AV.Role\n * @param {String} name The name of the Role to create.\n * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL\n * `{'*': { read: true }}` will be used.\n */\n constructor: function(name, acl, noDefaultACL) {\n if (_.isString(name)) {\n AV.Object.prototype.constructor.call(this, null, null);\n this.setName(name);\n } else {\n AV.Object.prototype.constructor.call(this, name, acl);\n }\n if (acl === undefined) {\n if (!noDefaultACL) {\n if(!this.getACL()) {\n console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.');\n var defaultAcl = new AV.ACL();\n defaultAcl.setPublicReadAccess(true); \n this.setACL(defaultAcl);\n }\n }\n } else if (!(acl instanceof AV.ACL)) {\n throw new TypeError('acl must be an instance of AV.ACL');\n } else {\n this.setACL(acl);\n }\n },\n\n /**\n * Gets the name of the role. You can alternatively call role.get(\"name\")\n *\n * @return {String} the name of the role.\n */\n getName: function() {\n return this.get(\"name\");\n },\n\n /**\n * Sets the name for a role. This value must be set before the role has\n * been saved to the server, and cannot be set once the role has been\n * saved.\n *\n *

\n * A role's name can only contain alphanumeric characters, _, -, and\n * spaces.\n *

\n *\n *

This is equivalent to calling role.set(\"name\", name)

\n *\n * @param {String} name The name of the role.\n */\n setName: function(name, options) {\n return this.set(\"name\", name, options);\n },\n\n /**\n * Gets the AV.Relation for the AV.Users that are direct\n * children of this role. These users are granted any privileges that this\n * role has been granted (e.g. read or write access through ACLs). You can\n * add or remove users from the role through this relation.\n *\n *

This is equivalent to calling role.relation(\"users\")

\n *\n * @return {AV.Relation} the relation for the users belonging to this\n * role.\n */\n getUsers: function() {\n return this.relation(\"users\");\n },\n\n /**\n * Gets the AV.Relation for the AV.Roles that are direct\n * children of this role. These roles' users are granted any privileges that\n * this role has been granted (e.g. read or write access through ACLs). You\n * can add or remove child roles from this role through this relation.\n *\n *

This is equivalent to calling role.relation(\"roles\")

\n *\n * @return {AV.Relation} the relation for the roles belonging to this\n * role.\n */\n getRoles: function() {\n return this.relation(\"roles\");\n },\n\n /**\n * @ignore\n */\n validate: function(attrs, options) {\n if (\"name\" in attrs && attrs.name !== this.getName()) {\n var newName = attrs.name;\n if (this.id && this.id !== attrs.objectId) {\n // Check to see if the objectId being set matches this.id.\n // This happens during a fetch -- the id is set before calling fetch.\n // Let the name be set in this case.\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only be set before it has been saved.\");\n }\n if (!_.isString(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name must be a String.\");\n }\n if (!(/^[0-9a-zA-Z\\-_ ]+$/).test(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only contain alphanumeric characters, _,\" +\n \" -, and spaces.\");\n }\n }\n if (AV.Object.prototype.validate) {\n return AV.Object.prototype.validate.call(this, attrs, options);\n }\n return false;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/role.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * A builder to generate sort string for app searching.For example:\n * @class\n * @since 0.5.1\n * @example\n * var builder = new AV.SearchSortBuilder();\n * builder.ascending('key1').descending('key2','max');\n * var query = new AV.SearchQuery('Player');\n * query.sortBy(builder);\n * query.find().then();\n */\n AV.SearchSortBuilder = function() {\n this._sortFields = [];\n };\n\n AV.SearchSortBuilder.prototype = {\n _addField: function(key, order, mode, missing) {\n var field = {};\n field[key] = {\n order: order || 'asc',\n mode: mode ||'avg',\n missing: '_' + (missing || 'last')\n };\n this._sortFields.push(field);\n return this;\n },\n\n\n /**\n * Sorts the results in ascending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n ascending: function(key, mode, missing) {\n return this._addField(key, 'asc', mode, missing);\n },\n\n /**\n * Sorts the results in descending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n descending: function(key, mode, missing) {\n return this._addField(key, 'desc', mode, missing);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Object} options The other options such as mode,order, unit etc.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n whereNear: function(key, point, options) {\n options = options || {};\n var field = {};\n var geo = {\n lat: point.latitude,\n lon: point.longitude\n };\n var m = {\n order: options.order || 'asc',\n mode: options.mode || 'avg',\n unit: options.unit || 'km'\n };\n m[key] = geo;\n field['_geo_distance'] = m;\n\n this._sortFields.push(field);\n return this;\n },\n\n /**\n * Build a sort string by configuration.\n * @return {String} the sort string.\n */\n build: function() {\n return JSON.stringify(AV._encode(this._sortFields));\n }\n };\n\n /**\n * App searching query.Use just like AV.Query:\n *\n * Visit App Searching Guide\n * for more details.\n * @class\n * @since 0.5.1\n * @example\n * var query = new AV.SearchQuery('Player');\n * query.queryString('*');\n * query.find().then(function(results) {\n * console.log('Found %d objects', query.hits());\n * //Process results\n * });\n */\n AV.SearchQuery = AV.Query._extend(/** @lends AV.SearchQuery.prototype */{\n _sid: null,\n _hits: 0,\n _queryString: null,\n _highlights: null,\n _sortBuilder: null,\n _createRequest: function(params, options){\n return AVRequest('search/select', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n /**\n * Sets the sid of app searching query.Default is null.\n * @param {String} sid Scroll id for searching.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n sid: function(sid) {\n this._sid = sid;\n return this;\n },\n\n /**\n * Sets the query string of app searching.\n * @param {String} q The query string.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n queryString: function(q) {\n this._queryString = q;\n return this;\n },\n\n\n /**\n * Sets the highlight fields. Such as\n *
\n     *   query.highlights('title');\n     *   //or pass an array.\n     *   query.highlights(['title', 'content'])\n     * 
\n * @param {String[]} highlights a list of fields.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n highlights: function(highlights) {\n var objects;\n if (highlights && _.isString(highlights)) {\n objects = arguments;\n } else {\n objects = highlights;\n }\n this._highlights = objects;\n return this;\n },\n\n /**\n * Sets the sort builder for this query.\n * @see AV.SearchSortBuilder\n * @param { AV.SearchSortBuilder} builder The sort builder.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n *\n */\n sortBy: function(builder) {\n this._sortBuilder = builder;\n return this;\n },\n\n /**\n * Returns the number of objects that match this query.\n * @return {Number}\n */\n hits: function() {\n if (!this._hits) {\n this._hits = 0;\n }\n return this._hits;\n },\n\n _processResult: function(json){\n delete json['className'];\n delete json['_app_url'];\n delete json['_deeplink'];\n return json;\n },\n\n /**\n * Returns true when there are more documents can be retrieved by this\n * query instance, you can call find function to get more results.\n * @see AV.SearchQuery#find\n * @return {Boolean}\n */\n hasMore: function() {\n return !this._hitEnd;\n },\n\n /**\n * Reset current query instance state(such as sid, hits etc) except params\n * for a new searching. After resetting, hasMore() will return true.\n */\n reset: function() {\n this._hitEnd = false;\n this._sid = null;\n this._hits = 0;\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n * Either options.success or options.error is called when the find\n * completes.\n *\n * @see AV.Query#find\n * @return {AV.Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find: function() {\n var self = this;\n\n var request = this._createRequest();\n\n return request.then(function(response) {\n //update sid for next querying.\n if(response.sid) {\n self._oldSid = self._sid;\n self._sid = response.sid;\n } else {\n self._sid = null;\n self._hitEnd = true;\n }\n self._hits = response.hits || 0;\n\n return _.map(response.results, function(json) {\n if(json.className) {\n response.className = json.className;\n }\n var obj = self._newObject(response);\n obj.appURL = json['_app_url'];\n obj._finishFetch(self._processResult(json), true);\n return obj;\n });\n });\n },\n\n toJSON: function(){\n var params = AV.SearchQuery.__super__.toJSON.call(this);\n delete params.where;\n if(this.className) {\n params.clazz = this.className;\n }\n if(this._sid) {\n params.sid = this._sid;\n }\n if(!this._queryString) {\n throw new Error('Please set query string.');\n } else {\n params.q = this._queryString;\n }\n if(this._highlights) {\n params.highlights = this._highlights.join(',');\n }\n if(this._sortBuilder && params.order) {\n throw new Error('sort and order can not be set at same time.');\n }\n if(this._sortBuilder) {\n params.sort = this._sortBuilder.build();\n }\n\n return params;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/search.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n const getUser = (options = {}) => AV.User.currentAsync()\n .then(currUser => currUser || AV.User._fetchUserBySessionToken(options.sessionToken));\n\n const getUserPointer = options => getUser(options)\n .then(currUser => AV.Object.createWithoutData('_User', currUser.id)._toPointer());\n\n /**\n * Contains functions to deal with Status in LeanCloud.\n * @class\n */\n AV.Status = function(imageUrl, message) {\n this.data = {};\n this.inboxType = 'default';\n this.query = null;\n if(imageUrl && typeof imageUrl === 'object') {\n this.data = imageUrl;\n } else {\n if(imageUrl){\n this.data.image = imageUrl;\n }\n if(message){\n this.data.message = message;\n }\n }\n return this;\n };\n\n AV.Status.prototype = {\n /**\n * Gets the value of an attribute in status data.\n * @param {String} attr The string name of an attribute.\n */\n get: function(attr){\n return this.data[attr];\n },\n /**\n * Sets a hash of model attributes on the status data.\n * @param {String} key The key to set.\n * @param {} value The value to give it.\n */\n set: function(key, value){\n this.data[key] = value;\n return this;\n },\n /**\n * Destroy this status,then it will not be avaiable in other user's inboxes.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options){\n if(!this.id)\n return AV.Promise.reject(new Error('The status id is not exists.'));\n var request = AVRequest('statuses', null, this.id, 'DELETE', options);\n return request;\n },\n /**\n * Cast the AV.Status object to an AV.Object pointer.\n * @return {AV.Object} A AV.Object pointer.\n */\n toObject: function(){\n if(!this.id)\n return null;\n return AV.Object.createWithoutData('_Status', this.id);\n },\n _getDataJSON: function() {\n var json = _.clone(this.data);\n return AV._encode(json);\n },\n /**\n * Send a status by a AV.Query object.\n * @since 0.3.0\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a status to male users\n * var status = new AVStatus('image url', 'a message');\n * status.query = new AV.Query('_User');\n * status.query.equalTo('gender', 'male');\n * status.send().then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n send: function(options = {}){\n if(!options.sessionToken && !AV.User.current()) {\n throw new Error('Please signin an user.');\n }\n if(!this.query){\n return AV.Status.sendStatusToFollowers(this, options);\n }\n\n return getUserPointer(options).then(currUser => {\n var query = this.query.toJSON();\n query.className = this.query.className;\n var data = {};\n data.query = query;\n this.data = this.data || {};\n this.data.source = this.data.source || currUser;\n data.data = this._getDataJSON();\n data.inboxType = this.inboxType || 'default';\n\n return AVRequest('statuses', null, null, 'POST', data, options);\n })\n .then((response) => {\n this.id = response.objectId;\n this.createdAt = AV._parseDate(response.createdAt);\n return this;\n });\n },\n\n _finishFetch: function(serverData){\n this.id = serverData.objectId;\n this.createdAt = AV._parseDate(serverData.createdAt);\n this.updatedAt = AV._parseDate(serverData.updatedAt);\n this.messageId = serverData.messageId;\n delete serverData.messageId;\n delete serverData.objectId;\n delete serverData.createdAt;\n delete serverData.updatedAt;\n this.data = AV._decode(serverData);\n }\n };\n\n /**\n * Send a status to current signined user's followers.\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendStatusToFollowers(status).then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendStatusToFollowers = function(status, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_Follower';\n query.keys = 'follower';\n query.where = {user: currUser};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = status.inboxType || 'default';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n *

Send a status from current signined user to other user's private status inbox.

\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {String} target The target user or user's objectId.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a private status to user '52e84e47e4b0f8de283b079b'\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendPrivateStatus = function(status, target, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n if(!target){\n throw new Error(\"Invalid target user.\");\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error(\"Invalid target user.\");\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_User';\n query.where = {objectId: userObjectId};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = 'private';\n status.inboxType = 'private';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n * Count unread statuses in someone's inbox.\n * @since 0.3.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the count\n * completes.\n * @example\n * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.countUnreadStatuses = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options);\n });\n };\n\n /**\n * reset unread statuses count in someone's inbox.\n * @since 2.1.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the reset\n * completes.\n * @example\n * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.resetUnreadCount = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options);\n });\n };\n\n /**\n * Create a status query to find someone's published statuses.\n * @since 0.3.0\n * @param {Object} source The status source.\n * @return {AV.Query} The query object for status.\n * @example\n * //Find current user's published statuses.\n * var query = AV.Status.statusQuery(AV.User.current());\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.statusQuery = function(source){\n var query = new AV.Query('_Status');\n if(source){\n query.equalTo('source', source);\n }\n return query;\n };\n\n /**\n *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

\n * @class\n */\n AV.InboxQuery = AV.Query._extend(/** @lends AV.InboxQuery.prototype */{\n _objectClass: AV.Status,\n _sinceId: 0,\n _maxId: 0,\n _inboxType: 'default',\n _owner: null,\n _newObject: function(){\n return new AV.Status();\n },\n _createRequest: function(params, options){\n return AVRequest('subscribe/statuses', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n\n /**\n * Sets the messageId of results to skip before returning any results.\n * This is useful for pagination.\n * Default is zero.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n sinceId: function(id){\n this._sinceId = id;\n return this;\n },\n /**\n * Sets the maximal messageId of results。\n * This is useful for pagination.\n * Default is zero that is no limition.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n maxId: function(id){\n this._maxId = id;\n return this;\n },\n /**\n * Sets the owner of the querying inbox.\n * @param {Object} owner The inbox owner.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n owner: function(owner){\n this._owner = owner;\n return this;\n },\n /**\n * Sets the querying inbox type.default is 'default'.\n * @param {Object} owner The inbox type.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n inboxType: function(type){\n this._inboxType = type;\n return this;\n },\n toJSON: function(){\n var params = AV.InboxQuery.__super__.toJSON.call(this);\n params.owner = AV._encode(this._owner);\n params.inboxType = AV._encode(this._inboxType);\n params.sinceId = AV._encode(this._sinceId);\n params.maxId = AV._encode(this._maxId);\n return params;\n }\n });\n\n /**\n * Create a inbox status query to find someone's inbox statuses.\n * @since 0.3.0\n * @param {Object} owner The inbox's owner\n * @param {String} inboxType The inbox type,'default' by default.\n * @return {AV.InboxQuery} The inbox query object.\n * @see AV.InboxQuery\n * @example\n * //Find current user's default inbox statuses.\n * var query = AV.Status.inboxQuery(AV.User.current());\n * //find the statuses after the last message id\n * query.sinceId(lastMessageId);\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.inboxQuery = function(owner, inboxType){\n var query = new AV.InboxQuery(AV.Status);\n if(owner){\n query._owner = owner;\n }\n if(inboxType){\n query._inboxType = inboxType;\n }\n return query;\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/status.js","module.exports = [];\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/comments-browser.js","const version = require('../version');\nconst comments = [process.env.CLIENT_PLATFORM || 'Node.js'].concat(require('./comments'));\n\nmodule.exports = `LeanCloud-JS-SDK/${version} (${comments.join('; ')})`;\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/index.js","const request = require('superagent');\nconst debug = require('debug')('cos');\nconst Promise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n const uploadUrl = uploadInfo.upload_url + \"?sign=\" + encodeURIComponent(uploadInfo.token);\n\n return new Promise((resolve, reject) => {\n const req = request('POST', uploadUrl)\n .field('fileContent', data)\n .field('op', 'upload');\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/cos.js","const request = require('superagent');\nconst Promise = require('../promise');\nconst debug = require('debug')('qiniu');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n // Get the uptoken to upload files to qiniu.\n const uptoken = uploadInfo.token;\n return new Promise((resolve, reject) => {\n const req = request('POST', 'https://up.qbox.me')\n .field('file', data)\n .field('name', file.attributes.name)\n .field('key', file._qiniu_key)\n .field('token', uptoken);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/qiniu-browser.js","const request = require('superagent');\nconst AVPromise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n return new Promise((resolve, reject) => {\n // 海外节点,针对 S3 才会返回 upload_url\n const req = request('PUT', uploadInfo.upload_url)\n .set('Content-Type', file.get('mime_type'))\n .send(data);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/s3.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\n\nconst getWeappLoginCode = () => {\n if (typeof wx === 'undefined' || typeof wx.login !== 'function') {\n throw new Error('Weapp Login is only available in Weapp');\n }\n return new Promise((resolve, reject) => {\n wx.login({\n success: ({ code, errMsg }) => {\n if (code) {\n resolve(code);\n } else {\n reject(new Error(errMsg));\n }\n },\n });\n });\n};\n\nmodule.exports = function(AV) {\n /**\n * @class\n *\n *

An AV.User object is a local representation of a user persisted to the\n * LeanCloud server. This class is a subclass of an AV.Object, and retains the\n * same functionality of an AV.Object, but also extends it with various\n * user specific methods, like authentication, signing up, and validation of\n * uniqueness.

\n */\n AV.User = AV.Object.extend(\"_User\", /** @lends AV.User.prototype */ {\n // Instance Variables\n _isCurrentUser: false,\n\n\n // Instance Methods\n\n /**\n * Internal method to handle special fields in a _User response.\n * @private\n */\n _mergeMagicFields: function(attrs) {\n if (attrs.sessionToken) {\n this._sessionToken = attrs.sessionToken;\n delete attrs.sessionToken;\n }\n AV.User.__super__._mergeMagicFields.call(this, attrs);\n },\n\n /**\n * Removes null values from authData (which exist temporarily for\n * unlinking)\n * @private\n */\n _cleanupAuthData: function() {\n if (!this.isCurrent()) {\n return;\n }\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n AV._objectEach(this.get('authData'), function(value, key) {\n if (!authData[key]) {\n delete authData[key];\n }\n });\n },\n\n /**\n * Synchronizes authData for all providers.\n * @private\n */\n _synchronizeAllAuthData: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._synchronizeAuthData(key);\n });\n },\n\n /**\n * Synchronizes auth data for a provider (e.g. puts the access token in the\n * right place to be used by the Facebook SDK).\n * @private\n */\n _synchronizeAuthData: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[authType];\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData');\n if (!authData || !provider) {\n return;\n }\n var success = provider.restoreAuthentication(authData[authType]);\n if (!success) {\n this._unlinkFrom(provider);\n }\n },\n\n _handleSaveResult: function(makeCurrent) {\n // Clean up and synchronize the authData object, removing any unset values\n if (makeCurrent && !AV._config.disableCurrentUser) {\n this._isCurrentUser = true;\n }\n this._cleanupAuthData();\n this._synchronizeAllAuthData();\n // Don't keep the password around.\n delete this._serverData.password;\n this._rebuildEstimatedDataForKey(\"password\");\n this._refreshCache();\n if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) {\n // Some old version of leanengine-node-sdk will overwrite\n // AV.User._saveCurrentUser which returns no Promise.\n // So we need a Promise wrapper.\n return Promise.resolve(AV.User._saveCurrentUser(this));\n } else {\n return Promise.resolve();\n }\n },\n\n /**\n * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can\n * call linkWith on the user (even if it doesn't exist yet on the server).\n * @private\n */\n _linkWith: function(provider, data) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[provider];\n } else {\n authType = provider.getAuthType();\n }\n if (data) {\n var authData = this.get('authData') || {};\n authData[authType] = data;\n return this.save({ authData })\n .then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n } else {\n return provider.authenticate().then(result => this._linkWith(provider, result));\n }\n },\n\n /**\n * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。\n * 仅在小程序中可用。\n *\n * @return {AV.User}\n */\n linkWithWeapp() {\n return getWeappLoginCode().then(code => this._linkWith('lc_weapp', { code }));\n },\n\n /**\n * Unlinks a user from a service.\n * @private\n */\n _unlinkFrom: function(provider) {\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n return this._linkWith(provider, null).then(model => {\n this._synchronizeAuthData(provider);\n return model;\n });\n },\n\n /**\n * Checks whether a user is linked to a service.\n * @private\n */\n _isLinked: function(provider) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData') || {};\n return !!authData[authType];\n },\n\n logOut: function() {\n this._logOutWithAll();\n this._isCurrentUser = false;\n },\n\n /**\n * Deauthenticates all providers.\n * @private\n */\n _logOutWithAll: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._logOutWith(key);\n });\n },\n\n /**\n * Deauthenticates a single provider (e.g. removing access tokens from the\n * Facebook SDK).\n * @private\n */\n _logOutWith: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n if (provider && provider.deauthenticate) {\n provider.deauthenticate();\n }\n },\n\n /**\n * Signs up a new user. You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUp\n */\n signUp: function(attrs, options) {\n var error;\n\n var username = (attrs && attrs.username) || this.get(\"username\");\n if (!username || (username === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty name.\");\n throw error;\n }\n\n var password = (attrs && attrs.password) || this.get(\"password\");\n if (!password || (password === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty password.\");\n throw error;\n }\n\n return this.save(attrs, options).then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Signs up a new user with mobile phone and sms code.\n * You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(attrs, options = {}) {\n var error;\n\n var mobilePhoneNumber = (attrs && attrs.mobilePhoneNumber) ||\n this.get(\"mobilePhoneNumber\");\n if (!mobilePhoneNumber || (mobilePhoneNumber === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty mobilePhoneNumber.\");\n throw error;\n }\n\n var smsCode = (attrs && attrs.smsCode) || this.get(\"smsCode\");\n if (!smsCode || (smsCode === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty smsCode.\");\n throw error;\n }\n\n options._makeRequest = function(route, className, id, method, json) {\n return AVRequest('usersByMobilePhone', null, null, \"POST\", json);\n };\n return this.save(attrs, options).then(function(model) {\n delete model.attributes.smsCode;\n delete model._serverData.smsCode;\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Logs in a AV.User. On success, this saves the session to localStorage,\n * so you can retrieve the currently logged in user using\n * current.\n *\n *

A username and password must be set before calling logIn.

\n *\n * @see AV.User.logIn\n * @return {Promise} A promise that is fulfilled with the user when\n * the login is complete.\n */\n logIn: function() {\n var model = this;\n var request = AVRequest('login', null, null, 'POST', this.toJSON());\n return request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n model._finishFetch(serverAttrs);\n return model._handleSaveResult(true).then(function() {\n if(!serverAttrs.smsCode)\n delete model.attributes['smsCode'];\n return model;\n });\n });\n },\n /**\n * @see AV.Object#save\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n options = options || {};\n\n return AV.Object.prototype.save\n .call(this, attrs, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Follow a user\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to follow.\n * @param {AuthOptions} options\n */\n follow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'POST', null, options);\n return request;\n },\n\n /**\n * Unfollow a user.\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to unfollow.\n * @param {AuthOptions} options\n */\n unfollow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'DELETE', null, options);\n return request;\n },\n\n /**\n *Create a follower query to query the user's followers.\n * @since 0.3.0\n * @see AV.User#followerQuery\n */\n followerQuery: function() {\n return AV.User.followerQuery(this.id);\n },\n\n /**\n *Create a followee query to query the user's followees.\n * @since 0.3.0\n * @see AV.User#followeeQuery\n */\n followeeQuery: function() {\n return AV.User.followeeQuery(this.id);\n },\n\n /**\n * @see AV.Object#fetch\n */\n fetch: function(fetchOptions, options) {\n return AV.Object.prototype.fetch.call(this, fetchOptions, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Update user's new password safely based on old password.\n * @param {String} oldPassword the old password.\n * @param {String} newPassword the new password.\n * @param {AuthOptions} options\n */\n updatePassword: function(oldPassword, newPassword, options) {\n var route = 'users/' + this.id + '/updatePassword';\n var params = {\n old_password: oldPassword,\n new_password: newPassword\n };\n var request = AVRequest(route, null, null, 'PUT', params, options);\n return request;\n },\n\n /**\n * Returns true if current would return this user.\n * @see AV.User#current\n */\n isCurrent: function() {\n return this._isCurrentUser;\n },\n\n /**\n * Returns get(\"username\").\n * @return {String}\n * @see AV.Object#get\n */\n getUsername: function() {\n return this.get(\"username\");\n },\n\n /**\n * Returns get(\"mobilePhoneNumber\").\n * @return {String}\n * @see AV.Object#get\n */\n getMobilePhoneNumber: function(){\n return this.get(\"mobilePhoneNumber\");\n },\n\n /**\n * Calls set(\"mobilePhoneNumber\", phoneNumber, options) and returns the result.\n * @param {String} mobilePhoneNumber\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setMobilePhoneNumber: function(phone, options) {\n return this.set(\"mobilePhoneNumber\", phone, options);\n },\n\n /**\n * Calls set(\"username\", username, options) and returns the result.\n * @param {String} username\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setUsername: function(username, options) {\n return this.set(\"username\", username, options);\n },\n\n /**\n * Calls set(\"password\", password, options) and returns the result.\n * @param {String} password\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setPassword: function(password, options) {\n return this.set(\"password\", password, options);\n },\n\n /**\n * Returns get(\"email\").\n * @return {String}\n * @see AV.Object#get\n */\n getEmail: function() {\n return this.get(\"email\");\n },\n\n /**\n * Calls set(\"email\", email, options) and returns the result.\n * @param {String} email\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setEmail: function(email, options) {\n return this.set(\"email\", email, options);\n },\n\n /**\n * Checks whether this user is the current user and has been authenticated.\n * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),\n * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id\n * @return (Boolean) whether this user is the current user and is logged in.\n */\n authenticated: function() {\n console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。')\n return !!this._sessionToken &&\n (!AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id);\n },\n\n /**\n * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。\n *\n * @since 2.0.0\n * @return Promise.\n */\n isAuthenticated() {\n return Promise.resolve().then(() =>\n !!this._sessionToken &&\n AV.User._fetchUserBySessionToken(this._sessionToken).then(\n () => true,\n (error) => {\n if (error.code === 211) {\n return false;\n }\n throw error;\n }\n )\n );\n },\n\n /**\n * Get sessionToken of current user.\n * @return {String} sessionToken\n */\n getSessionToken() {\n return this._sessionToken;\n },\n\n /**\n * Refresh sessionToken of current user.\n * @since 2.1.0\n * @param {AuthOptions} [options]\n * @return {Promise.} user with refreshed sessionToken\n */\n refreshSessionToken(options) {\n return AVRequest(`users/${this.id}/refreshSessionToken`, null, null, 'PUT', null, options)\n .then(response => {\n this._finishFetch(response);\n return this._handleSaveResult(true).then(() => this);\n });\n },\n\n /**\n * Get this user's Roles.\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that is fulfilled with the roles when\n * the query is complete.\n */\n getRoles(options) {\n return AV.Relation.reverseQuery(\"_Role\", \"users\", this).find(options);\n },\n\n }, /** @lends AV.User */ {\n // Class Variables\n\n // The currently logged-in user.\n _currentUser: null,\n\n // Whether currentUser is known to match the serialized version on disk.\n // This is useful for saving a localstorage check if you try to load\n // _currentUser frequently while there is none stored.\n _currentUserMatchesDisk: false,\n\n // The localStorage key suffix that the current user is stored under.\n _CURRENT_USER_KEY: \"currentUser\",\n\n // The mapping of auth provider names to actual providers\n _authProviders: {},\n\n // Class Methods\n\n /**\n * Signs up a new user with a username (or email) and password.\n * This will create a new AV.User on the server, and also persist the\n * session in localStorage so that you can access the user using\n * {@link #current}.\n *\n * @param {String} username The username (or email) to sign up with.\n * @param {String} password The password to sign up with.\n * @param {Object} attrs Extra fields to set on the new user.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the signup completes.\n * @see AV.User#signUp\n */\n signUp: function(username, password, attrs, options) {\n attrs = attrs || {};\n attrs.username = username;\n attrs.password = password;\n var user = AV.Object._create(\"_User\");\n return user.signUp(attrs, options);\n },\n\n /**\n * Logs in a user with a username (or email) and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} username The username (or email) to log in with.\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logIn: function(username, password, options) {\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ username: username, password: password });\n return user.logIn(options);\n },\n\n /**\n * Logs in a user with a session token. On success, this saves the session\n * to disk, so you can retrieve the currently logged in user using\n * current.\n *\n * @param {String} sessionToken The sessionToken to log in with.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n */\n become: function(sessionToken) {\n return this._fetchUserBySessionToken(sessionToken).then(user =>\n user._handleSaveResult(true).then(() => user)\n );\n },\n\n _fetchUserBySessionToken: function(sessionToken) {\n var user = AV.Object._create(\"_User\");\n return AVRequest(\n \"users\",\n \"me\",\n null,\n \"GET\", {\n session_token: sessionToken\n }\n ).then(function(resp) {\n var serverAttrs = user.parse(resp);\n user._finishFetch(serverAttrs);\n return user;\n });\n },\n\n /**\n * Logs in a user with a mobile phone number and sms code sent by\n * AV.User.requestLoginSmsCode.On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhoneSmsCode: function(mobilePhone, smsCode, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a mobilePhoneNumber and smsCode.\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {String} mobilePhoneNumber The user's mobilePhoneNumber.\n * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode\n * @param {Object} attributes The user's other attributes such as username etc.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(mobilePhoneNumber, smsCode, attrs, options) {\n attrs = attrs || {};\n attrs.mobilePhoneNumber = mobilePhoneNumber;\n attrs.smsCode = smsCode;\n var user = AV.Object._create(\"_User\");\n return user.signUpOrlogInWithMobilePhone(attrs, options);\n },\n\n\n /**\n * Logs in a user with a mobile phone number and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhone: function(mobilePhone, password, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a third party auth data(AccessToken).\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @param {string} platform Available platform for sign up.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户}\n */\n signUpOrlogInWithAuthData(authData, platform) {\n return AV.User._logInWith(platform, authData);\n },\n\n /**\n * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。\n * 仅在小程序中可用。\n *\n * @since 2.0.0\n * @return {AV.User}\n */\n loginWithWeapp() {\n return getWeappLoginCode().then(code => this.signUpOrlogInWithAuthData({ code }, 'lc_weapp'));\n },\n\n /**\n * Associate a user with a third party auth data(AccessToken).\n *\n * @param {AV.User} userObj A user which you want to associate.\n * @param {string} platform Available platform for sign up.\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @return {Promise} A promise that is fulfilled with the user when completed.\n * @example AV.User.associateWithAuthData(loginUser, 'weixin', {\n * openid: 'abc123',\n * access_token: '123abc',\n * expires_in: 1382686496\n * }).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n */\n associateWithAuthData(userObj, platform, authData) {\n return userObj._linkWith(platform, authData);\n },\n /**\n * Logs out the currently logged in user session. This will remove the\n * session from disk, log out of linked services, and future calls to\n * current will return null.\n * @return {Promise}\n */\n logOut: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser !== null) {\n AV.User._currentUser._logOutWithAll();\n AV.User._currentUser._isCurrentUser = false;\n }\n AV.User._currentUserMatchesDisk = true;\n AV.User._currentUser = null;\n return AV.localStorage.removeItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY));\n },\n\n /**\n *Create a follower query for special user to query the user's followers.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followerQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Follower');\n query._friendshipTag ='follower';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n *Create a followee query for special user to query the user's followees.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followeeQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Followee');\n query._friendshipTag ='followee';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n * Requests a password reset email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * reset their password on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * forgot their password.\n * @return {Promise}\n */\n requestPasswordReset: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestPasswordReset\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * verify their email address on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * doesn't verify their email address.\n * @return {Promise}\n */\n requestEmailVerify: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestEmailVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * verify their mobile phone number by calling AV.User.verifyMobilePhone\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestMobilePhoneVerify: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestMobilePhoneVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n\n /**\n * Requests a reset password sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * reset their account's password by calling AV.User.resetPasswordBySmsCode\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestPasswordResetBySmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestPasswordResetBySmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Makes a call to reset user's account password by sms code and new password.\n * The sms code is sent by AV.User.requestPasswordResetBySmsCode.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @param {String} password The new password.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n resetPasswordBySmsCode: function(code, password){\n var json = { password: password};\n var request = AVRequest(\"resetPasswordBySmsCode\", null, code, \"PUT\",\n json);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode\n * If verify successfully,the user mobilePhoneVerified attribute will be true.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifyMobilePhone: function(code){\n var request = AVRequest(\"verifyMobilePhone\", null, code, \"POST\",\n null);\n return request;\n },\n\n /**\n * Requests a logIn sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * login by AV.User.logInWithMobilePhoneSmsCode function.\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that want to login by AV.User.logInWithMobilePhoneSmsCode\n * @return {Promise}\n */\n requestLoginSmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestLoginSmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {Promise.} resolved with the currently logged in AV.User.\n */\n currentAsync: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser) {\n return Promise.resolve(AV.User._currentUser);\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return Promise.resolve(AV.User._currentUser);\n }\n\n\n return AV.localStorage.getItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY)\n ).then(function(userData) {\n if (!userData) {\n return null;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n });\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {AV.User} The currently logged in AV.User.\n */\n current: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return null;\n }\n\n if (AV.User._currentUser) {\n return AV.User._currentUser;\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return AV.User._currentUser;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n var userData = AV.localStorage.getItem(AV._getAVPath(\n AV.User._CURRENT_USER_KEY));\n if (!userData) {\n\n return null;\n }\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n },\n\n /**\n * Persists a user as currentUser to localStorage, and into the singleton.\n * @private\n */\n _saveCurrentUser: function(user) {\n var promise;\n if (AV.User._currentUser !== user) {\n promise = AV.User.logOut();\n }\n else {\n promise = Promise.resolve();\n }\n return promise.then(function() {\n user._isCurrentUser = true;\n AV.User._currentUser = user;\n\n var json = user.toJSON();\n json._id = user.id;\n json._sessionToken = user._sessionToken;\n return AV.localStorage.setItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY),\n JSON.stringify(json)\n ).then(function() {\n AV.User._currentUserMatchesDisk = true;\n });\n });\n },\n\n _registerAuthenticationProvider: function(provider) {\n AV.User._authProviders[provider.getAuthType()] = provider;\n // Synchronize the current user with the auth provider.\n if (!AV._config.disableCurrentUser && AV.User.current()) {\n AV.User.current()._synchronizeAuthData(provider.getAuthType());\n }\n },\n\n _logInWith: function(provider, options) {\n var user = AV.Object._create(\"_User\");\n return user._linkWith(provider, options);\n }\n\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/user.js","var _ = require('underscore');\nvar Promise = require('../promise');\n\n// interface Storage {\n// readonly attribute boolean async;\n// string getItem(string key);\n// void setItem(string key, string value);\n// void removeItem(string key);\n// void clear();\n// Promise getItemAsync(string key);\n// Promise setItemAsync(string key, string value);\n// Promise removeItemAsync(string key);\n// Promise clearAsync();\n// }\nvar Storage = {};\nvar apiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nvar localStorage = global.localStorage;\n\ntry {\n var testKey = '__storejs__';\n localStorage.setItem(testKey, testKey);\n if (localStorage.getItem(testKey) != testKey) {\n throw new Error();\n }\n localStorage.removeItem(testKey);\n} catch (e) {\n localStorage = require('localstorage-memory');\n}\n\n// in browser, `localStorage.async = false` will excute `localStorage.setItem('async', false)`\n_(apiNames).each(function(apiName) {\n Storage[apiName] = function() {\n return global.localStorage[apiName].apply(global.localStorage, arguments);\n };\n});\nStorage.async = false;\n\nmodule.exports = Storage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/localstorage-browser.js","var dataURItoBlob = function(dataURI, type) {\n var byteString;\n\n // 传入的 base64,不是 dataURL\n if (dataURI.indexOf('base64') < 0) {\n byteString = atob(dataURI);\n } else if (dataURI.split(',')[0].indexOf('base64') >= 0) {\n type = type || dataURI.split(',')[0].split(':')[1].split(';')[0];\n byteString = atob(dataURI.split(',')[1]);\n } else {\n byteString = unescape(dataURI.split(',')[1]);\n }\n var ia = new Uint8Array(byteString.length);\n for (var i = 0; i < byteString.length; i ++) {\n ia[i] = byteString.charCodeAt(i);\n }\n return new Blob([ia], {type});\n};\n\nmodule.exports = dataURItoBlob;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/parse-base64-browser.js","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/component-emitter/index.js\n// module id = 49\n// module chunks = 0","(function() {\n var base64map\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n crypt = {\n // Bit-wise rotation left\n rotl: function(n, b) {\n return (n << b) | (n >>> (32 - b));\n },\n\n // Bit-wise rotation right\n rotr: function(n, b) {\n return (n << (32 - b)) | (n >>> b);\n },\n\n // Swap big-endian to little-endian and vice versa\n endian: function(n) {\n // If number given, swap endian\n if (n.constructor == Number) {\n return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n }\n\n // Else, assume array and swap all items\n for (var i = 0; i < n.length; i++)\n n[i] = crypt.endian(n[i]);\n return n;\n },\n\n // Generate an array of any length of random bytes\n randomBytes: function(n) {\n for (var bytes = []; n > 0; n--)\n bytes.push(Math.floor(Math.random() * 256));\n return bytes;\n },\n\n // Convert a byte array to big-endian 32-bit words\n bytesToWords: function(bytes) {\n for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n words[b >>> 5] |= bytes[i] << (24 - b % 32);\n return words;\n },\n\n // Convert big-endian 32-bit words to a byte array\n wordsToBytes: function(words) {\n for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a hex string\n bytesToHex: function(bytes) {\n for (var hex = [], i = 0; i < bytes.length; i++) {\n hex.push((bytes[i] >>> 4).toString(16));\n hex.push((bytes[i] & 0xF).toString(16));\n }\n return hex.join('');\n },\n\n // Convert a hex string to a byte array\n hexToBytes: function(hex) {\n for (var bytes = [], c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return bytes;\n },\n\n // Convert a byte array to a base-64 string\n bytesToBase64: function(bytes) {\n for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n for (var j = 0; j < 4; j++)\n if (i * 8 + j * 6 <= bytes.length * 8)\n base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n else\n base64.push('=');\n }\n return base64.join('');\n },\n\n // Convert a base-64 string to a byte array\n base64ToBytes: function(base64) {\n // Remove non-base-64 characters\n base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n imod4 = ++i % 4) {\n if (imod4 == 0) continue;\n bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n }\n return bytes;\n }\n };\n\n module.exports = crypt;\n})();\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/crypt/crypt.js\n// module id = 50\n// module chunks = 0","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (namespaces || '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/debug.js\n// module id = 51\n// module chunks = 0","/*!\n * @overview es6-promise - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE\n * @version 4.1.0\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.ES6Promise = factory());\n}(this, (function () { 'use strict';\n\nfunction objectOrFunction(x) {\n return typeof x === 'function' || typeof x === 'object' && x !== null;\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\nvar _isArray = undefined;\nif (!Array.isArray) {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n} else {\n _isArray = Array.isArray;\n}\n\nvar isArray = _isArray;\n\nvar len = 0;\nvar vertxNext = undefined;\nvar customSchedulerFn = undefined;\n\nvar asap = function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 2, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n if (customSchedulerFn) {\n customSchedulerFn(flush);\n } else {\n scheduleFlush();\n }\n }\n};\n\nfunction setScheduler(scheduleFn) {\n customSchedulerFn = scheduleFn;\n}\n\nfunction setAsap(asapFn) {\n asap = asapFn;\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // see https://github.com/cujojs/when/issues/410 for details\n return function () {\n return process.nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n if (typeof vertxNext !== 'undefined') {\n return function () {\n vertxNext(flush);\n };\n }\n\n return useSetTimeout();\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n // Store setTimeout reference so es6-promise will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var globalSetTimeout = setTimeout;\n return function () {\n return globalSetTimeout(flush, 1);\n };\n}\n\nvar queue = new Array(1000);\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n\n callback(arg);\n\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertx() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush = undefined;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush = attemptVertx();\n} else {\n scheduleFlush = useSetTimeout();\n}\n\nfunction then(onFulfillment, onRejection) {\n var _arguments = arguments;\n\n var parent = this;\n\n var child = new this.constructor(noop);\n\n if (child[PROMISE_ID] === undefined) {\n makePromise(child);\n }\n\n var _state = parent._state;\n\n if (_state) {\n (function () {\n var callback = _arguments[_state - 1];\n asap(function () {\n return invokeCallback(_state, child, callback, parent._result);\n });\n })();\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\n/**\n `Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {Any} value value that the returned promise will be resolved with\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve(object) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop);\n _resolve(promise, object);\n return promise;\n}\n\nvar PROMISE_ID = Math.random().toString(36).substring(16);\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nfunction selfFulfillment() {\n return new TypeError(\"You cannot resolve a promise with itself\");\n}\n\nfunction cannotReturnOwn() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then) {\n asap(function (promise) {\n var sealed = false;\n var error = tryThen(then, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n _resolve(promise, value);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n _reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n _reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n _reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n return _resolve(promise, value);\n }, function (reason) {\n return _reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$) {\n if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$ === GET_THEN_ERROR) {\n _reject(promise, GET_THEN_ERROR.error);\n GET_THEN_ERROR.error = null;\n } else if (then$$ === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$)) {\n handleForeignThenable(promise, maybeThenable, then$$);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction _resolve(promise, value) {\n if (promise === value) {\n _reject(promise, selfFulfillment());\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onerror) {\n promise._onerror(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length !== 0) {\n asap(publish, promise);\n }\n}\n\nfunction _reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n\n asap(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var _subscribers = parent._subscribers;\n var length = _subscribers.length;\n\n parent._onerror = null;\n\n _subscribers[length] = child;\n _subscribers[length + FULFILLED] = onFulfillment;\n _subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n asap(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = undefined,\n callback = undefined,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = undefined,\n error = undefined,\n succeeded = undefined,\n failed = undefined;\n\n if (hasCallback) {\n value = tryCatch(callback, detail);\n\n if (value === TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value.error = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n _reject(promise, cannotReturnOwn());\n return;\n }\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n _resolve(promise, value);\n } else if (failed) {\n _reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n _reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n try {\n resolver(function resolvePromise(value) {\n _resolve(promise, value);\n }, function rejectPromise(reason) {\n _reject(promise, reason);\n });\n } catch (e) {\n _reject(promise, e);\n }\n}\n\nvar id = 0;\nfunction nextId() {\n return id++;\n}\n\nfunction makePromise(promise) {\n promise[PROMISE_ID] = id++;\n promise._state = undefined;\n promise._result = undefined;\n promise._subscribers = [];\n}\n\nfunction Enumerator(Constructor, input) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop);\n\n if (!this.promise[PROMISE_ID]) {\n makePromise(this.promise);\n }\n\n if (isArray(input)) {\n this._input = input;\n this.length = input.length;\n this._remaining = input.length;\n\n this._result = new Array(this.length);\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate();\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n _reject(this.promise, validationError());\n }\n}\n\nfunction validationError() {\n return new Error('Array Methods must be provided an Array');\n};\n\nEnumerator.prototype._enumerate = function () {\n var length = this.length;\n var _input = this._input;\n\n for (var i = 0; this._state === PENDING && i < length; i++) {\n this._eachEntry(_input[i], i);\n }\n};\n\nEnumerator.prototype._eachEntry = function (entry, i) {\n var c = this._instanceConstructor;\n var resolve$$ = c.resolve;\n\n if (resolve$$ === resolve) {\n var _then = getThen(entry);\n\n if (_then === then && entry._state !== PENDING) {\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof _then !== 'function') {\n this._remaining--;\n this._result[i] = entry;\n } else if (c === Promise) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, _then);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve$$) {\n return resolve$$(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve$$(entry), i);\n }\n};\n\nEnumerator.prototype._settledAt = function (state, i, value) {\n var promise = this.promise;\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (state === REJECTED) {\n _reject(promise, value);\n } else {\n this._result[i] = value;\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n};\n\nEnumerator.prototype._willSettleAt = function (promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n};\n\n/**\n `Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = resolve(2);\n let promise3 = resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = reject(new Error(\"2\"));\n let promise3 = reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries) {\n return new Enumerator(this, entries).promise;\n}\n\n/**\n `Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} promises array of promises to observe\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (!isArray(entries)) {\n return new Constructor(function (_, reject) {\n return reject(new TypeError('You must pass an array to race.'));\n });\n } else {\n return new Constructor(function (resolve, reject) {\n var length = entries.length;\n for (var i = 0; i < length; i++) {\n Constructor.resolve(entries[i]).then(resolve, reject);\n }\n });\n }\n}\n\n/**\n `Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {Any} reason value that the returned promise will be rejected with.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject(reason) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop);\n _reject(promise, reason);\n return promise;\n}\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise's eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {function} resolver\n Useful for tooling.\n @constructor\n*/\nfunction Promise(resolver) {\n this[PROMISE_ID] = nextId();\n this._result = this._state = undefined;\n this._subscribers = [];\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n}\n\nPromise.all = all;\nPromise.race = race;\nPromise.resolve = resolve;\nPromise.reject = reject;\nPromise._setScheduler = setScheduler;\nPromise._setAsap = setAsap;\nPromise._asap = asap;\n\nPromise.prototype = {\n constructor: Promise,\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n \n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n \n Chaining\n --------\n \n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n \n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n \n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n \n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n \n Assimilation\n ------------\n \n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n \n If the assimliated promise rejects, then the downstream promise will also reject.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n \n Simple Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let result;\n \n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n \n Advanced Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let author, books;\n \n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n \n function foundBooks(books) {\n \n }\n \n function failure(reason) {\n \n }\n \n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n \n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n then: then,\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function _catch(onRejection) {\n return this.then(null, onRejection);\n }\n};\n\nfunction polyfill() {\n var local = undefined;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P) {\n var promiseToString = null;\n try {\n promiseToString = Object.prototype.toString.call(P.resolve());\n } catch (e) {\n // silently ignored\n }\n\n if (promiseToString === '[object Promise]' && !P.cast) {\n return;\n }\n }\n\n local.Promise = Promise;\n}\n\n// Strange compat..\nPromise.polyfill = polyfill;\nPromise.Promise = Promise;\n\nreturn Promise;\n\n})));\n//# sourceMappingURL=es6-promise.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/es6-promise/dist/es6-promise.js\n// module id = 52\n// module chunks = 0","/**\n * @author Toru Nagashima\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n\n\"use strict\";\n\n//-----------------------------------------------------------------------------\n// Requirements\n//-----------------------------------------------------------------------------\n\nvar Commons = require(\"./commons\");\nvar LISTENERS = Commons.LISTENERS;\nvar ATTRIBUTE = Commons.ATTRIBUTE;\nvar newNode = Commons.newNode;\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/**\n * Gets a specified attribute listener from a given EventTarget object.\n *\n * @param {EventTarget} eventTarget - An EventTarget object to get.\n * @param {string} type - An event type to get.\n * @returns {function|null} The found attribute listener.\n */\nfunction getAttributeListener(eventTarget, type) {\n var node = eventTarget[LISTENERS][type];\n while (node != null) {\n if (node.kind === ATTRIBUTE) {\n return node.listener;\n }\n node = node.next;\n }\n return null;\n}\n\n/**\n * Sets a specified attribute listener to a given EventTarget object.\n *\n * @param {EventTarget} eventTarget - An EventTarget object to set.\n * @param {string} type - An event type to set.\n * @param {function|null} listener - A listener to be set.\n * @returns {void}\n */\nfunction setAttributeListener(eventTarget, type, listener) {\n if (typeof listener !== \"function\" && typeof listener !== \"object\") {\n listener = null; // eslint-disable-line no-param-reassign\n }\n\n var prev = null;\n var node = eventTarget[LISTENERS][type];\n while (node != null) {\n if (node.kind === ATTRIBUTE) {\n // Remove old value.\n if (prev == null) {\n eventTarget[LISTENERS][type] = node.next;\n }\n else {\n prev.next = node.next;\n }\n }\n else {\n prev = node;\n }\n\n node = node.next;\n }\n\n // Add new value.\n if (listener != null) {\n if (prev == null) {\n eventTarget[LISTENERS][type] = newNode(listener, ATTRIBUTE);\n }\n else {\n prev.next = newNode(listener, ATTRIBUTE);\n }\n }\n}\n\n//-----------------------------------------------------------------------------\n// Public Interface\n//-----------------------------------------------------------------------------\n\n/**\n * Defines an `EventTarget` implementation which has `onfoobar` attributes.\n *\n * @param {EventTarget} EventTargetBase - A base implementation of EventTarget.\n * @param {string[]} types - A list of event types which are defined as attribute listeners.\n * @returns {EventTarget} The defined `EventTarget` implementation which has attribute listeners.\n */\nexports.defineCustomEventTarget = function(EventTargetBase, types) {\n function EventTarget() {\n EventTargetBase.call(this);\n }\n\n var descripter = {\n constructor: {\n value: EventTarget,\n configurable: true,\n writable: true\n }\n };\n\n types.forEach(function(type) {\n descripter[\"on\" + type] = {\n get: function() { return getAttributeListener(this, type); },\n set: function(listener) { setAttributeListener(this, type, listener); },\n configurable: true,\n enumerable: true\n };\n });\n\n EventTarget.prototype = Object.create(EventTargetBase.prototype, descripter);\n\n return EventTarget;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/event-target-shim/lib/custom-event-target.js\n// module id = 53\n// module chunks = 0","/**\n * @author Toru Nagashima\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n\n\"use strict\";\n\n//-----------------------------------------------------------------------------\n// Requirements\n//-----------------------------------------------------------------------------\n\nvar createUniqueKey = require(\"./commons\").createUniqueKey;\n\n//-----------------------------------------------------------------------------\n// Constsnts\n//-----------------------------------------------------------------------------\n\n/**\n * The key of the flag which is turned on by `stopImmediatePropagation` method.\n *\n * @type {symbol|string}\n * @private\n */\nvar STOP_IMMEDIATE_PROPAGATION_FLAG =\n createUniqueKey(\"stop_immediate_propagation_flag\");\n\n/**\n * The key of the flag which is turned on by `preventDefault` method.\n *\n * @type {symbol|string}\n * @private\n */\nvar CANCELED_FLAG = createUniqueKey(\"canceled_flag\");\n\n/**\n * The key of the original event object.\n *\n * @type {symbol|string}\n * @private\n */\nvar ORIGINAL_EVENT = createUniqueKey(\"original_event\");\n\n/**\n * Method definitions for the event wrapper.\n *\n * @type {object}\n * @private\n */\nvar wrapperPrototypeDefinition = Object.freeze({\n stopPropagation: Object.freeze({\n value: function stopPropagation() {\n var e = this[ORIGINAL_EVENT];\n if (typeof e.stopPropagation === \"function\") {\n e.stopPropagation();\n }\n },\n writable: true,\n configurable: true\n }),\n\n stopImmediatePropagation: Object.freeze({\n value: function stopImmediatePropagation() {\n this[STOP_IMMEDIATE_PROPAGATION_FLAG] = true;\n\n var e = this[ORIGINAL_EVENT];\n if (typeof e.stopImmediatePropagation === \"function\") {\n e.stopImmediatePropagation();\n }\n },\n writable: true,\n configurable: true\n }),\n\n preventDefault: Object.freeze({\n value: function preventDefault() {\n if (this.cancelable === true) {\n this[CANCELED_FLAG] = true;\n }\n\n var e = this[ORIGINAL_EVENT];\n if (typeof e.preventDefault === \"function\") {\n e.preventDefault();\n }\n },\n writable: true,\n configurable: true\n }),\n\n defaultPrevented: Object.freeze({\n get: function defaultPrevented() { return this[CANCELED_FLAG]; },\n enumerable: true,\n configurable: true\n })\n});\n\n//-----------------------------------------------------------------------------\n// Public Interface\n//-----------------------------------------------------------------------------\n\nexports.STOP_IMMEDIATE_PROPAGATION_FLAG = STOP_IMMEDIATE_PROPAGATION_FLAG;\n\n/**\n * Creates an event wrapper.\n *\n * We cannot modify several properties of `Event` object, so we need to create the wrapper.\n * Plus, this wrapper supports non `Event` objects.\n *\n * @param {Event|{type: string}} event - An original event to create the wrapper.\n * @param {EventTarget} eventTarget - The event target of the event.\n * @returns {Event} The created wrapper. This object is implemented `Event` interface.\n * @private\n */\nexports.createEventWrapper = function createEventWrapper(event, eventTarget) {\n var timeStamp = (\n typeof event.timeStamp === \"number\" ? event.timeStamp : Date.now()\n );\n var propertyDefinition = {\n type: {value: event.type, enumerable: true},\n target: {value: eventTarget, enumerable: true},\n currentTarget: {value: eventTarget, enumerable: true},\n eventPhase: {value: 2, enumerable: true},\n bubbles: {value: Boolean(event.bubbles), enumerable: true},\n cancelable: {value: Boolean(event.cancelable), enumerable: true},\n timeStamp: {value: timeStamp, enumerable: true},\n isTrusted: {value: false, enumerable: true}\n };\n propertyDefinition[STOP_IMMEDIATE_PROPAGATION_FLAG] = {value: false, writable: true};\n propertyDefinition[CANCELED_FLAG] = {value: false, writable: true};\n propertyDefinition[ORIGINAL_EVENT] = {value: event};\n\n // For CustomEvent.\n if (typeof event.detail !== \"undefined\") {\n propertyDefinition.detail = {value: event.detail, enumerable: true};\n }\n\n return Object.create(\n Object.create(event, wrapperPrototypeDefinition),\n propertyDefinition\n );\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/event-target-shim/lib/event-wrapper.js\n// module id = 54\n// module chunks = 0","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/is-buffer/index.js\n// module id = 55\n// module chunks = 0","(function(root) {\n var localStorageMemory = {};\n var cache = {};\n\n /**\n * number of stored items.\n */\n localStorageMemory.length = 0;\n\n /**\n * returns item for passed key, or null\n *\n * @para {String} key\n * name of item to be returned\n * @returns {String|null}\n */\n localStorageMemory.getItem = function(key) {\n return cache[key] || null;\n };\n\n /**\n * sets item for key to passed value, as String\n *\n * @para {String} key\n * name of item to be set\n * @para {String} value\n * value, will always be turned into a String\n * @returns {undefined}\n */\n localStorageMemory.setItem = function(key, value) {\n if (typeof value === 'undefined') {\n localStorageMemory.removeItem(key);\n } else {\n if (!(cache.hasOwnProperty(key))) {\n localStorageMemory.length++;\n }\n\n cache[key] = '' + value;\n }\n };\n\n /**\n * removes item for passed key\n *\n * @para {String} key\n * name of item to be removed\n * @returns {undefined}\n */\n localStorageMemory.removeItem = function(key) {\n if (cache.hasOwnProperty(key)) {\n delete cache[key];\n localStorageMemory.length--;\n }\n };\n\n /**\n * returns name of key at passed index\n *\n * @para {Number} index\n * Position for key to be returned (starts at 0)\n * @returns {String|null}\n */\n localStorageMemory.key = function(index) {\n return Object.keys(cache)[index] || null;\n };\n\n /**\n * removes all stored items and sets length to 0\n *\n * @returns {undefined}\n */\n localStorageMemory.clear = function() {\n cache = {};\n localStorageMemory.length = 0;\n };\n\n if (typeof exports === 'object') {\n module.exports = localStorageMemory;\n } else {\n root.localStorageMemory = localStorageMemory;\n }\n})(this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/localstorage-memory/lib/localstorage-memory.js\n// module id = 56\n// module chunks = 0","(function(){\r\n var crypt = require('crypt'),\r\n utf8 = require('charenc').utf8,\r\n isBuffer = require('is-buffer'),\r\n bin = require('charenc').bin,\r\n\r\n // The core\r\n md5 = function (message, options) {\r\n // Convert to byte array\r\n if (message.constructor == String)\r\n if (options && options.encoding === 'binary')\r\n message = bin.stringToBytes(message);\r\n else\r\n message = utf8.stringToBytes(message);\r\n else if (isBuffer(message))\r\n message = Array.prototype.slice.call(message, 0);\r\n else if (!Array.isArray(message))\r\n message = message.toString();\r\n // else, assume byte array already\r\n\r\n var m = crypt.bytesToWords(message),\r\n l = message.length * 8,\r\n a = 1732584193,\r\n b = -271733879,\r\n c = -1732584194,\r\n d = 271733878;\r\n\r\n // Swap endian\r\n for (var i = 0; i < m.length; i++) {\r\n m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;\r\n }\r\n\r\n // Padding\r\n m[l >>> 5] |= 0x80 << (l % 32);\r\n m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n // Method shortcuts\r\n var FF = md5._ff,\r\n GG = md5._gg,\r\n HH = md5._hh,\r\n II = md5._ii;\r\n\r\n for (var i = 0; i < m.length; i += 16) {\r\n\r\n var aa = a,\r\n bb = b,\r\n cc = c,\r\n dd = d;\r\n\r\n a = FF(a, b, c, d, m[i+ 0], 7, -680876936);\r\n d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n c = FF(c, d, a, b, m[i+ 2], 17, 606105819);\r\n b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n a = FF(a, b, c, d, m[i+ 4], 7, -176418897);\r\n d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);\r\n c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);\r\n d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n a = FF(a, b, c, d, m[i+12], 7, 1804603682);\r\n d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n b = FF(b, c, d, a, m[i+15], 22, 1236535329);\r\n\r\n a = GG(a, b, c, d, m[i+ 1], 5, -165796510);\r\n d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);\r\n c = GG(c, d, a, b, m[i+11], 14, 643717713);\r\n b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n a = GG(a, b, c, d, m[i+ 5], 5, -701558691);\r\n d = GG(d, a, b, c, m[i+10], 9, 38016083);\r\n c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n a = GG(a, b, c, d, m[i+ 9], 5, 568446438);\r\n d = GG(d, a, b, c, m[i+14], 9, -1019803690);\r\n c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);\r\n a = GG(a, b, c, d, m[i+13], 5, -1444681467);\r\n d = GG(d, a, b, c, m[i+ 2], 9, -51403784);\r\n c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);\r\n b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n a = HH(a, b, c, d, m[i+ 5], 4, -378558);\r\n d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n c = HH(c, d, a, b, m[i+11], 16, 1839030562);\r\n b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);\r\n d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);\r\n c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n a = HH(a, b, c, d, m[i+13], 4, 681279174);\r\n d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n b = HH(b, c, d, a, m[i+ 6], 23, 76029189);\r\n a = HH(a, b, c, d, m[i+ 9], 4, -640364487);\r\n d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n c = HH(c, d, a, b, m[i+15], 16, 530742520);\r\n b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n a = II(a, b, c, d, m[i+ 0], 6, -198630844);\r\n d = II(d, a, b, c, m[i+ 7], 10, 1126891415);\r\n c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n a = II(a, b, c, d, m[i+12], 6, 1700485571);\r\n d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n a = II(a, b, c, d, m[i+ 8], 6, 1873313359);\r\n d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n b = II(b, c, d, a, m[i+13], 21, 1309151649);\r\n a = II(a, b, c, d, m[i+ 4], 6, -145523070);\r\n d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n c = II(c, d, a, b, m[i+ 2], 15, 718787259);\r\n b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n a = (a + aa) >>> 0;\r\n b = (b + bb) >>> 0;\r\n c = (c + cc) >>> 0;\r\n d = (d + dd) >>> 0;\r\n }\r\n\r\n return crypt.endian([a, b, c, d]);\r\n };\r\n\r\n // Auxiliary functions\r\n md5._ff = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._gg = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._hh = function (a, b, c, d, x, s, t) {\r\n var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._ii = function (a, b, c, d, x, s, t) {\r\n var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n\r\n // Package private blocksize\r\n md5._blocksize = 16;\r\n md5._digestsize = 16;\r\n\r\n module.exports = function (message, options) {\r\n if (message === undefined || message === null)\r\n throw new Error('Illegal argument ' + message);\r\n\r\n var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n return options && options.asBytes ? digestbytes :\r\n options && options.asString ? bin.bytesToString(digestbytes) :\r\n crypt.bytesToHex(digestbytes);\r\n };\r\n\r\n})();\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/md5/md5.js\n// module id = 57\n// module chunks = 0","/**\n * Helpers.\n */\n\nvar s = 1000\nvar m = s * 60\nvar h = m * 60\nvar d = h * 24\nvar y = d * 365.25\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} options\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {}\n var type = typeof val\n if (type === 'string' && val.length > 0) {\n return parse(val)\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ?\n\t\t\tfmtLong(val) :\n\t\t\tfmtShort(val)\n }\n throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))\n}\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str)\n if (str.length > 10000) {\n return\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)\n if (!match) {\n return\n }\n var n = parseFloat(match[1])\n var type = (match[2] || 'ms').toLowerCase()\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y\n case 'days':\n case 'day':\n case 'd':\n return n * d\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n\n default:\n return undefined\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd'\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h'\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm'\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's'\n }\n return ms + 'ms'\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms'\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name\n }\n return Math.ceil(ms / n) + ' ' + name + 's'\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ms/index.js\n// module id = 58\n// module chunks = 0","/**\n * Check if `fn` is a function.\n *\n * @param {Function} fn\n * @return {Boolean}\n * @api private\n */\nvar isObject = require('./is-object');\n\nfunction isFunction(fn) {\n var tag = isObject(fn) ? Object.prototype.toString.call(fn) : '';\n return tag === '[object Function]';\n}\n\nmodule.exports = isFunction;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-function.js\n// module id = 59\n// module chunks = 0","/**\n * Module of mixed-in functions shared between node and client code\n */\nvar isObject = require('./is-object');\n\n/**\n * Expose `RequestBase`.\n */\n\nmodule.exports = RequestBase;\n\n/**\n * Initialize a new `RequestBase`.\n *\n * @api public\n */\n\nfunction RequestBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in RequestBase.prototype) {\n obj[key] = RequestBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Clear previous timeout.\n *\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.clearTimeout = function _clearTimeout(){\n clearTimeout(this._timer);\n clearTimeout(this._responseTimeoutTimer);\n delete this._timer;\n delete this._responseTimeoutTimer;\n return this;\n};\n\n/**\n * Override default response body parser\n *\n * This function will be called to convert incoming data into request.body\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.parse = function parse(fn){\n this._parser = fn;\n return this;\n};\n\n/**\n * Set format of binary response body.\n * In browser valid formats are 'blob' and 'arraybuffer',\n * which return Blob and ArrayBuffer, respectively.\n *\n * In Node all values result in Buffer.\n *\n * Examples:\n *\n * req.get('/')\n * .responseType('blob')\n * .end(callback);\n *\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.responseType = function(val){\n this._responseType = val;\n return this;\n};\n\n/**\n * Override default request body serializer\n *\n * This function will be called to convert data set via .send or .attach into payload to send\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.serialize = function serialize(fn){\n this._serializer = fn;\n return this;\n};\n\n/**\n * Set timeouts.\n *\n * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.\n * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.\n *\n * Value of 0 or false means no timeout.\n *\n * @param {Number|Object} ms or {response, read, deadline}\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.timeout = function timeout(options){\n if (!options || 'object' !== typeof options) {\n this._timeout = options;\n this._responseTimeout = 0;\n return this;\n }\n\n for(var option in options) {\n switch(option) {\n case 'deadline':\n this._timeout = options.deadline;\n break;\n case 'response':\n this._responseTimeout = options.response;\n break;\n default:\n console.warn(\"Unknown timeout option\", option);\n }\n }\n return this;\n};\n\n/**\n * Set number of retry attempts on error.\n *\n * Failed requests will be retried 'count' times if timeout or err.code >= 500.\n *\n * @param {Number} count\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.retry = function retry(count){\n // Default to 1 if no count passed or true\n if (arguments.length === 0 || count === true) count = 1;\n if (count <= 0) count = 0;\n this._maxRetries = count;\n this._retries = 0;\n return this;\n};\n\n/**\n * Retry request\n *\n * @return {Request} for chaining\n * @api private\n */\n\nRequestBase.prototype._retry = function() {\n this.clearTimeout();\n\n // node\n if (this.req) {\n this.req = null;\n this.req = this.request();\n }\n\n this._aborted = false;\n this.timedout = false;\n\n return this._end();\n};\n\n/**\n * Promise support\n *\n * @param {Function} resolve\n * @param {Function} [reject]\n * @return {Request}\n */\n\nRequestBase.prototype.then = function then(resolve, reject) {\n if (!this._fullfilledPromise) {\n var self = this;\n if (this._endCalled) {\n console.warn(\"Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises\");\n }\n this._fullfilledPromise = new Promise(function(innerResolve, innerReject){\n self.end(function(err, res){\n if (err) innerReject(err); else innerResolve(res);\n });\n });\n }\n return this._fullfilledPromise.then(resolve, reject);\n}\n\nRequestBase.prototype.catch = function(cb) {\n return this.then(undefined, cb);\n};\n\n/**\n * Allow for extension\n */\n\nRequestBase.prototype.use = function use(fn) {\n fn(this);\n return this;\n}\n\nRequestBase.prototype.ok = function(cb) {\n if ('function' !== typeof cb) throw Error(\"Callback required\");\n this._okCallback = cb;\n return this;\n};\n\nRequestBase.prototype._isResponseOK = function(res) {\n if (!res) {\n return false;\n }\n\n if (this._okCallback) {\n return this._okCallback(res);\n }\n\n return res.status >= 200 && res.status < 300;\n};\n\n\n/**\n * Get request header `field`.\n * Case-insensitive.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nRequestBase.prototype.get = function(field){\n return this._header[field.toLowerCase()];\n};\n\n/**\n * Get case-insensitive header `field` value.\n * This is a deprecated internal API. Use `.get(field)` instead.\n *\n * (getHeader is no longer used internally by the superagent code base)\n *\n * @param {String} field\n * @return {String}\n * @api private\n * @deprecated\n */\n\nRequestBase.prototype.getHeader = RequestBase.prototype.get;\n\n/**\n * Set header `field` to `val`, or multiple fields with one object.\n * Case-insensitive.\n *\n * Examples:\n *\n * req.get('/')\n * .set('Accept', 'application/json')\n * .set('X-API-Key', 'foobar')\n * .end(callback);\n *\n * req.get('/')\n * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })\n * .end(callback);\n *\n * @param {String|Object} field\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.set = function(field, val){\n if (isObject(field)) {\n for (var key in field) {\n this.set(key, field[key]);\n }\n return this;\n }\n this._header[field.toLowerCase()] = val;\n this.header[field] = val;\n return this;\n};\n\n/**\n * Remove header `field`.\n * Case-insensitive.\n *\n * Example:\n *\n * req.get('/')\n * .unset('User-Agent')\n * .end(callback);\n *\n * @param {String} field\n */\nRequestBase.prototype.unset = function(field){\n delete this._header[field.toLowerCase()];\n delete this.header[field];\n return this;\n};\n\n/**\n * Write the field `name` and `val`, or multiple fields with one object\n * for \"multipart/form-data\" request bodies.\n *\n * ``` js\n * request.post('/upload')\n * .field('foo', 'bar')\n * .end(callback);\n *\n * request.post('/upload')\n * .field({ foo: 'bar', baz: 'qux' })\n * .end(callback);\n * ```\n *\n * @param {String|Object} name\n * @param {String|Blob|File|Buffer|fs.ReadStream} val\n * @return {Request} for chaining\n * @api public\n */\nRequestBase.prototype.field = function(name, val) {\n\n // name should be either a string or an object.\n if (null === name || undefined === name) {\n throw new Error('.field(name, val) name can not be empty');\n }\n\n if (this._data) {\n console.error(\".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObject(name)) {\n for (var key in name) {\n this.field(key, name[key]);\n }\n return this;\n }\n\n if (Array.isArray(val)) {\n for (var i in val) {\n this.field(name, val[i]);\n }\n return this;\n }\n\n // val should be defined now\n if (null === val || undefined === val) {\n throw new Error('.field(name, val) val can not be empty');\n }\n if ('boolean' === typeof val) {\n val = '' + val;\n }\n this._getFormData().append(name, val);\n return this;\n};\n\n/**\n * Abort the request, and clear potential timeout.\n *\n * @return {Request}\n * @api public\n */\nRequestBase.prototype.abort = function(){\n if (this._aborted) {\n return this;\n }\n this._aborted = true;\n this.xhr && this.xhr.abort(); // browser\n this.req && this.req.abort(); // node\n this.clearTimeout();\n this.emit('abort');\n return this;\n};\n\n/**\n * Enable transmission of cookies with x-domain requests.\n *\n * Note that for this to work the origin must not be\n * using \"Access-Control-Allow-Origin\" with a wildcard,\n * and also must set \"Access-Control-Allow-Credentials\"\n * to \"true\".\n *\n * @api public\n */\n\nRequestBase.prototype.withCredentials = function(on){\n // This is browser-only functionality. Node side is no-op.\n if(on==undefined) on = true;\n this._withCredentials = on;\n return this;\n};\n\n/**\n * Set the max redirects to `n`. Does noting in browser XHR implementation.\n *\n * @param {Number} n\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.redirects = function(n){\n this._maxRedirects = n;\n return this;\n};\n\n/**\n * Convert to a plain javascript object (not JSON string) of scalar properties.\n * Note as this method is designed to return a useful non-this value,\n * it cannot be chained.\n *\n * @return {Object} describing method, url, and data of this request\n * @api public\n */\n\nRequestBase.prototype.toJSON = function(){\n return {\n method: this.method,\n url: this.url,\n data: this._data,\n headers: this._header\n };\n};\n\n\n/**\n * Send `data` as the request body, defaulting the `.type()` to \"json\" when\n * an object is given.\n *\n * Examples:\n *\n * // manual json\n * request.post('/user')\n * .type('json')\n * .send('{\"name\":\"tj\"}')\n * .end(callback)\n *\n * // auto json\n * request.post('/user')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // manual x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send('name=tj')\n * .end(callback)\n *\n * // auto x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // defaults to x-www-form-urlencoded\n * request.post('/user')\n * .send('name=tobi')\n * .send('species=ferret')\n * .end(callback)\n *\n * @param {String|Object} data\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.send = function(data){\n var isObj = isObject(data);\n var type = this._header['content-type'];\n\n if (this._formData) {\n console.error(\".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObj && !this._data) {\n if (Array.isArray(data)) {\n this._data = [];\n } else if (!this._isHost(data)) {\n this._data = {};\n }\n } else if (data && this._data && this._isHost(this._data)) {\n throw Error(\"Can't merge these send calls\");\n }\n\n // merge\n if (isObj && isObject(this._data)) {\n for (var key in data) {\n this._data[key] = data[key];\n }\n } else if ('string' == typeof data) {\n // default to x-www-form-urlencoded\n if (!type) this.type('form');\n type = this._header['content-type'];\n if ('application/x-www-form-urlencoded' == type) {\n this._data = this._data\n ? this._data + '&' + data\n : data;\n } else {\n this._data = (this._data || '') + data;\n }\n } else {\n this._data = data;\n }\n\n if (!isObj || this._isHost(data)) {\n return this;\n }\n\n // default to json\n if (!type) this.type('json');\n return this;\n};\n\n\n/**\n * Sort `querystring` by the sort function\n *\n *\n * Examples:\n *\n * // default order\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery()\n * .end(callback)\n *\n * // customized sort function\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery(function(a, b){\n * return a.length - b.length;\n * })\n * .end(callback)\n *\n *\n * @param {Function} sort\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.sortQuery = function(sort) {\n // _sort default to true but otherwise can be a function or boolean\n this._sort = typeof sort === 'undefined' ? true : sort;\n return this;\n};\n\n/**\n * Invoke callback with timeout error.\n *\n * @api private\n */\n\nRequestBase.prototype._timeoutError = function(reason, timeout, errno){\n if (this._aborted) {\n return;\n }\n var err = new Error(reason + timeout + 'ms exceeded');\n err.timeout = timeout;\n err.code = 'ECONNABORTED';\n err.errno = errno;\n this.timedout = true;\n this.abort();\n this.callback(err);\n};\n\nRequestBase.prototype._setTimeouts = function() {\n var self = this;\n\n // deadline\n if (this._timeout && !this._timer) {\n this._timer = setTimeout(function(){\n self._timeoutError('Timeout of ', self._timeout, 'ETIME');\n }, this._timeout);\n }\n // response timeout\n if (this._responseTimeout && !this._responseTimeoutTimer) {\n this._responseTimeoutTimer = setTimeout(function(){\n self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');\n }, this._responseTimeout);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/request-base.js\n// module id = 60\n// module chunks = 0","\n/**\n * Module dependencies.\n */\n\nvar utils = require('./utils');\n\n/**\n * Expose `ResponseBase`.\n */\n\nmodule.exports = ResponseBase;\n\n/**\n * Initialize a new `ResponseBase`.\n *\n * @api public\n */\n\nfunction ResponseBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in ResponseBase.prototype) {\n obj[key] = ResponseBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Get case-insensitive `field` value.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nResponseBase.prototype.get = function(field){\n return this.header[field.toLowerCase()];\n};\n\n/**\n * Set header related properties:\n *\n * - `.type` the content type without params\n *\n * A response of \"Content-Type: text/plain; charset=utf-8\"\n * will provide you with a `.type` of \"text/plain\".\n *\n * @param {Object} header\n * @api private\n */\n\nResponseBase.prototype._setHeaderProperties = function(header){\n // TODO: moar!\n // TODO: make this a util\n\n // content-type\n var ct = header['content-type'] || '';\n this.type = utils.type(ct);\n\n // params\n var params = utils.params(ct);\n for (var key in params) this[key] = params[key];\n\n this.links = {};\n\n // links\n try {\n if (header.link) {\n this.links = utils.parseLinks(header.link);\n }\n } catch (err) {\n // ignore\n }\n};\n\n/**\n * Set flags such as `.ok` based on `status`.\n *\n * For example a 2xx response will give you a `.ok` of __true__\n * whereas 5xx will be __false__ and `.error` will be __true__. The\n * `.clientError` and `.serverError` are also available to be more\n * specific, and `.statusType` is the class of error ranging from 1..5\n * sometimes useful for mapping respond colors etc.\n *\n * \"sugar\" properties are also defined for common cases. Currently providing:\n *\n * - .noContent\n * - .badRequest\n * - .unauthorized\n * - .notAcceptable\n * - .notFound\n *\n * @param {Number} status\n * @api private\n */\n\nResponseBase.prototype._setStatusProperties = function(status){\n var type = status / 100 | 0;\n\n // status / class\n this.status = this.statusCode = status;\n this.statusType = type;\n\n // basics\n this.info = 1 == type;\n this.ok = 2 == type;\n this.redirect = 3 == type;\n this.clientError = 4 == type;\n this.serverError = 5 == type;\n this.error = (4 == type || 5 == type)\n ? this.toError()\n : false;\n\n // sugar\n this.accepted = 202 == status;\n this.noContent = 204 == status;\n this.badRequest = 400 == status;\n this.unauthorized = 401 == status;\n this.notAcceptable = 406 == status;\n this.forbidden = 403 == status;\n this.notFound = 404 == status;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/response-base.js\n// module id = 61\n// module chunks = 0","var ERROR_CODES = [\n 'ECONNRESET',\n 'ETIMEDOUT',\n 'EADDRINFO',\n 'ESOCKETTIMEDOUT'\n];\n\n/**\n * Determine if a request should be retried.\n * (Borrowed from segmentio/superagent-retry)\n *\n * @param {Error} err\n * @param {Response} [res]\n * @returns {Boolean}\n */\nmodule.exports = function shouldRetry(err, res) {\n if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true;\n if (res && res.status && res.status >= 500) return true;\n // Superagent timeout\n if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true;\n if (err && 'crossDomain' in err) return true;\n return false;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/should-retry.js\n// module id = 62\n// module chunks = 0","\n/**\n * Return the mime type for the given `str`.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nexports.type = function(str){\n return str.split(/ *; */).shift();\n};\n\n/**\n * Return header field parameters.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.params = function(str){\n return str.split(/ *; */).reduce(function(obj, str){\n var parts = str.split(/ *= */);\n var key = parts.shift();\n var val = parts.shift();\n\n if (key && val) obj[key] = val;\n return obj;\n }, {});\n};\n\n/**\n * Parse Link header fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.parseLinks = function(str){\n return str.split(/ *, */).reduce(function(obj, str){\n var parts = str.split(/ *; */);\n var url = parts[0].slice(1, -1);\n var rel = parts[1].split(/ *= */)[1].slice(1, -1);\n obj[rel] = url;\n return obj;\n }, {});\n};\n\n/**\n * Strip content related fields from `header`.\n *\n * @param {Object} header\n * @return {Object} header\n * @api private\n */\n\nexports.cleanHeader = function(header, shouldStripCookie){\n delete header['content-type'];\n delete header['content-length'];\n delete header['transfer-encoding'];\n delete header['host'];\n if (shouldStripCookie) {\n delete header['cookie'];\n }\n return header;\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/utils.js\n// module id = 63\n// module chunks = 0","/* (ignored) */\n\n\n//////////////////\n// WEBPACK FOOTER\n// vertx (ignored)\n// module id = 64\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/av.js b/dist/av.js new file mode 100644 index 000000000..8d88b9da4 --- /dev/null +++ b/dist/av.js @@ -0,0 +1,14093 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["AV"] = factory(); + else + root["AV"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; +/******/ +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 30); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Underscore.js 1.8.3 +// http://underscorejs.org +// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `exports` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var + push = ArrayProto.push, + slice = ArrayProto.slice, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind, + nativeCreate = Object.create; + + // Naked function reference for surrogate-prototype-swapping. + var Ctor = function(){}; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object. + if (true) { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.8.3'; + + // Internal function that returns an efficient (for current engines) version + // of the passed-in callback, to be repeatedly applied in other Underscore + // functions. + var optimizeCb = function(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 2: return function(value, other) { + return func.call(context, value, other); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; + } + return function() { + return func.apply(context, arguments); + }; + }; + + // A mostly-internal function to generate callbacks that can be applied + // to each element in a collection, returning the desired result — either + // identity, an arbitrary callback, a property matcher, or a property accessor. + var cb = function(value, context, argCount) { + if (value == null) return _.identity; + if (_.isFunction(value)) return optimizeCb(value, context, argCount); + if (_.isObject(value)) return _.matcher(value); + return _.property(value); + }; + _.iteratee = function(value, context) { + return cb(value, context, Infinity); + }; + + // An internal function for creating assigner functions. + var createAssigner = function(keysFunc, undefinedOnly) { + return function(obj) { + var length = arguments.length; + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + } + } + return obj; + }; + }; + + // An internal function for creating a new object that inherits from another. + var baseCreate = function(prototype) { + if (!_.isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + Ctor.prototype = prototype; + var result = new Ctor; + Ctor.prototype = null; + return result; + }; + + var property = function(key) { + return function(obj) { + return obj == null ? void 0 : obj[key]; + }; + }; + + // Helper for collection methods to determine whether a collection + // should be iterated as an array or as an object + // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength + // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; + var getLength = property('length'); + var isArrayLike = function(collection) { + var length = getLength(collection); + return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; + }; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles raw objects in addition to array-likes. Treats all + // sparse array-likes as if they were dense. + _.each = _.forEach = function(obj, iteratee, context) { + iteratee = optimizeCb(iteratee, context); + var i, length; + if (isArrayLike(obj)) { + for (i = 0, length = obj.length; i < length; i++) { + iteratee(obj[i], i, obj); + } + } else { + var keys = _.keys(obj); + for (i = 0, length = keys.length; i < length; i++) { + iteratee(obj[keys[i]], keys[i], obj); + } + } + return obj; + }; + + // Return the results of applying the iteratee to each element. + _.map = _.collect = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + results = Array(length); + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + results[index] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Create a reducing function iterating left or right. + function createReduce(dir) { + // Optimized iterator function as using arguments.length + // in the main function will deoptimize the, see #1991. + function iterator(obj, iteratee, memo, keys, index, length) { + for (; index >= 0 && index < length; index += dir) { + var currentKey = keys ? keys[index] : index; + memo = iteratee(memo, obj[currentKey], currentKey, obj); + } + return memo; + } + + return function(obj, iteratee, memo, context) { + iteratee = optimizeCb(iteratee, context, 4); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length, + index = dir > 0 ? 0 : length - 1; + // Determine the initial value if none is provided. + if (arguments.length < 3) { + memo = obj[keys ? keys[index] : index]; + index += dir; + } + return iterator(obj, iteratee, memo, keys, index, length); + }; + } + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. + _.reduce = _.foldl = _.inject = createReduce(1); + + // The right-associative version of reduce, also known as `foldr`. + _.reduceRight = _.foldr = createReduce(-1); + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, predicate, context) { + var key; + if (isArrayLike(obj)) { + key = _.findIndex(obj, predicate, context); + } else { + key = _.findKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) return obj[key]; + }; + + // Return all the elements that pass a truth test. + // Aliased as `select`. + _.filter = _.select = function(obj, predicate, context) { + var results = []; + predicate = cb(predicate, context); + _.each(obj, function(value, index, list) { + if (predicate(value, index, list)) results.push(value); + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, predicate, context) { + return _.filter(obj, _.negate(cb(predicate)), context); + }; + + // Determine whether all of the elements match a truth test. + // Aliased as `all`. + _.every = _.all = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (!predicate(obj[currentKey], currentKey, obj)) return false; + } + return true; + }; + + // Determine if at least one element in the object matches a truth test. + // Aliased as `any`. + _.some = _.any = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = !isArrayLike(obj) && _.keys(obj), + length = (keys || obj).length; + for (var index = 0; index < length; index++) { + var currentKey = keys ? keys[index] : index; + if (predicate(obj[currentKey], currentKey, obj)) return true; + } + return false; + }; + + // Determine if the array or object contains a given item (using `===`). + // Aliased as `includes` and `include`. + _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + if (typeof fromIndex != 'number' || guard) fromIndex = 0; + return _.indexOf(obj, item, fromIndex) >= 0; + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + var func = isFunc ? method : value[method]; + return func == null ? func : func.apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, _.property(key)); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // containing specific `key:value` pairs. + _.where = function(obj, attrs) { + return _.filter(obj, _.matcher(attrs)); + }; + + // Convenience version of a common use case of `find`: getting the first object + // containing specific `key:value` pairs. + _.findWhere = function(obj, attrs) { + return _.find(obj, _.matcher(attrs)); + }; + + // Return the maximum element (or element-based computation). + _.max = function(obj, iteratee, context) { + var result = -Infinity, lastComputed = -Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value > result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed > lastComputed || computed === -Infinity && result === -Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iteratee, context) { + var result = Infinity, lastComputed = Infinity, + value, computed; + if (iteratee == null && obj != null) { + obj = isArrayLike(obj) ? obj : _.values(obj); + for (var i = 0, length = obj.length; i < length; i++) { + value = obj[i]; + if (value < result) { + result = value; + } + } + } else { + iteratee = cb(iteratee, context); + _.each(obj, function(value, index, list) { + computed = iteratee(value, index, list); + if (computed < lastComputed || computed === Infinity && result === Infinity) { + result = value; + lastComputed = computed; + } + }); + } + return result; + }; + + // Shuffle a collection, using the modern version of the + // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). + _.shuffle = function(obj) { + var set = isArrayLike(obj) ? obj : _.values(obj); + var length = set.length; + var shuffled = Array(length); + for (var index = 0, rand; index < length; index++) { + rand = _.random(0, index); + if (rand !== index) shuffled[index] = shuffled[rand]; + shuffled[rand] = set[index]; + } + return shuffled; + }; + + // Sample **n** random values from a collection. + // If **n** is not specified, returns a single random element. + // The internal `guard` argument allows it to work with `map`. + _.sample = function(obj, n, guard) { + if (n == null || guard) { + if (!isArrayLike(obj)) obj = _.values(obj); + return obj[_.random(obj.length - 1)]; + } + return _.shuffle(obj).slice(0, Math.max(0, n)); + }; + + // Sort the object's values by a criterion produced by an iteratee. + _.sortBy = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value: value, + index: index, + criteria: iteratee(value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index - right.index; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(behavior) { + return function(obj, iteratee, context) { + var result = {}; + iteratee = cb(iteratee, context); + _.each(obj, function(value, index) { + var key = iteratee(value, index, obj); + behavior(result, value, key); + }); + return result; + }; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = group(function(result, value, key) { + if (_.has(result, key)) result[key].push(value); else result[key] = [value]; + }); + + // Indexes the object's values by a criterion, similar to `groupBy`, but for + // when you know that your index values will be unique. + _.indexBy = group(function(result, value, key) { + result[key] = value; + }); + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = group(function(result, value, key) { + if (_.has(result, key)) result[key]++; else result[key] = 1; + }); + + // Safely create a real, live array from anything iterable. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); + if (isArrayLike(obj)) return _.map(obj, _.identity); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return isArrayLike(obj) ? obj.length : _.keys(obj).length; + }; + + // Split a collection into two arrays: one whose elements all satisfy the given + // predicate, and one whose elements all do not satisfy the predicate. + _.partition = function(obj, predicate, context) { + predicate = cb(predicate, context); + var pass = [], fail = []; + _.each(obj, function(value, key, obj) { + (predicate(value, key, obj) ? pass : fail).push(value); + }); + return [pass, fail]; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head` and `take`. The **guard** check + // allows it to work with `_.map`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[0]; + return _.initial(array, array.length - n); + }; + + // Returns everything but the last entry of the array. Especially useful on + // the arguments object. Passing **n** will return all the values in + // the array, excluding the last N. + _.initial = function(array, n, guard) { + return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); + }; + + // Get the last element of an array. Passing **n** will return the last N + // values in the array. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if (n == null || guard) return array[array.length - 1]; + return _.rest(array, Math.max(0, array.length - n)); + }; + + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. + // Especially useful on the arguments object. Passing an **n** will return + // the rest N values in the array. + _.rest = _.tail = _.drop = function(array, n, guard) { + return slice.call(array, n == null || guard ? 1 : n); + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, _.identity); + }; + + // Internal implementation of a recursive `flatten` function. + var flatten = function(input, shallow, strict, startIndex) { + var output = [], idx = 0; + for (var i = startIndex || 0, length = getLength(input); i < length; i++) { + var value = input[i]; + if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { + //flatten current level of array or arguments object + if (!shallow) value = flatten(value, shallow, strict); + var j = 0, len = value.length; + output.length += len; + while (j < len) { + output[idx++] = value[j++]; + } + } else if (!strict) { + output[idx++] = value; + } + } + return output; + }; + + // Flatten out an array, either recursively (by default), or just one level. + _.flatten = function(array, shallow) { + return flatten(array, shallow, false); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted, iteratee, context) { + if (!_.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + if (iteratee != null) iteratee = cb(iteratee, context); + var result = []; + var seen = []; + for (var i = 0, length = getLength(array); i < length; i++) { + var value = array[i], + computed = iteratee ? iteratee(value, i, array) : value; + if (isSorted) { + if (!i || seen !== computed) result.push(value); + seen = computed; + } else if (iteratee) { + if (!_.contains(seen, computed)) { + seen.push(computed); + result.push(value); + } + } else if (!_.contains(result, value)) { + result.push(value); + } + } + return result; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(flatten(arguments, true, true)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var result = []; + var argsLength = arguments.length; + for (var i = 0, length = getLength(array); i < length; i++) { + var item = array[i]; + if (_.contains(result, item)) continue; + for (var j = 1; j < argsLength; j++) { + if (!_.contains(arguments[j], item)) break; + } + if (j === argsLength) result.push(item); + } + return result; + }; + + // Take the difference between one array and a number of other arrays. + // Only the elements present in just the first array will remain. + _.difference = function(array) { + var rest = flatten(arguments, true, true, 1); + return _.filter(array, function(value){ + return !_.contains(rest, value); + }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + return _.unzip(arguments); + }; + + // Complement of _.zip. Unzip accepts an array of arrays and groups + // each array's elements on shared indices + _.unzip = function(array) { + var length = array && _.max(array, getLength).length || 0; + var result = Array(length); + + for (var index = 0; index < length; index++) { + result[index] = _.pluck(array, index); + } + return result; + }; + + // Converts lists into objects. Pass either a single array of `[key, value]` + // pairs, or two parallel arrays of the same length -- one of keys, and one of + // the corresponding values. + _.object = function(list, values) { + var result = {}; + for (var i = 0, length = getLength(list); i < length; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // Generator function to create the findIndex and findLastIndex functions + function createPredicateIndexFinder(dir) { + return function(array, predicate, context) { + predicate = cb(predicate, context); + var length = getLength(array); + var index = dir > 0 ? 0 : length - 1; + for (; index >= 0 && index < length; index += dir) { + if (predicate(array[index], index, array)) return index; + } + return -1; + }; + } + + // Returns the first index on an array-like that passes a predicate test + _.findIndex = createPredicateIndexFinder(1); + _.findLastIndex = createPredicateIndexFinder(-1); + + // Use a comparator function to figure out the smallest index at which + // an object should be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iteratee, context) { + iteratee = cb(iteratee, context, 1); + var value = iteratee(obj); + var low = 0, high = getLength(array); + while (low < high) { + var mid = Math.floor((low + high) / 2); + if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; + } + return low; + }; + + // Generator function to create the indexOf and lastIndexOf functions + function createIndexFinder(dir, predicateFind, sortedIndex) { + return function(array, item, idx) { + var i = 0, length = getLength(array); + if (typeof idx == 'number') { + if (dir > 0) { + i = idx >= 0 ? idx : Math.max(idx + length, i); + } else { + length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; + } + } else if (sortedIndex && idx && length) { + idx = sortedIndex(array, item); + return array[idx] === item ? idx : -1; + } + if (item !== item) { + idx = predicateFind(slice.call(array, i, length), _.isNaN); + return idx >= 0 ? idx + i : -1; + } + for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { + if (array[idx] === item) return idx; + } + return -1; + }; + } + + // Return the position of the first occurrence of an item in an array, + // or -1 if the item is not included in the array. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); + _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (stop == null) { + stop = start || 0; + start = 0; + } + step = step || 1; + + var length = Math.max(Math.ceil((stop - start) / step), 0); + var range = Array(length); + + for (var idx = 0; idx < length; idx++, start += step) { + range[idx] = start; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Determines whether to execute a function as a constructor + // or a normal function with the provided arguments + var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { + if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); + var self = baseCreate(sourceFunc.prototype); + var result = sourceFunc.apply(self, args); + if (_.isObject(result)) return result; + return self; + }; + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if + // available. + _.bind = function(func, context) { + if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); + var args = slice.call(arguments, 2); + var bound = function() { + return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); + }; + return bound; + }; + + // Partially apply a function by creating a version that has had some of its + // arguments pre-filled, without changing its dynamic `this` context. _ acts + // as a placeholder, allowing any combination of arguments to be pre-filled. + _.partial = function(func) { + var boundArgs = slice.call(arguments, 1); + var bound = function() { + var position = 0, length = boundArgs.length; + var args = Array(length); + for (var i = 0; i < length; i++) { + args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; + } + while (position < arguments.length) args.push(arguments[position++]); + return executeBound(func, bound, this, this, args); + }; + return bound; + }; + + // Bind a number of an object's methods to that object. Remaining arguments + // are the method names to be bound. Useful for ensuring that all callbacks + // defined on an object belong to it. + _.bindAll = function(obj) { + var i, length = arguments.length, key; + if (length <= 1) throw new Error('bindAll must be passed function names'); + for (i = 1; i < length; i++) { + key = arguments[i]; + obj[key] = _.bind(obj[key], obj); + } + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memoize = function(key) { + var cache = memoize.cache; + var address = '' + (hasher ? hasher.apply(this, arguments) : key); + if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); + return cache[address]; + }; + memoize.cache = {}; + return memoize; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ + return func.apply(null, args); + }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = _.partial(_.delay, _, 1); + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. Normally, the throttled function will run + // as much as it can, without ever going more than once per `wait` duration; + // but if you'd like to disable the execution on the leading edge, pass + // `{leading: false}`. To disable execution on the trailing edge, ditto. + _.throttle = function(func, wait, options) { + var context, args, result; + var timeout = null; + var previous = 0; + if (!options) options = {}; + var later = function() { + previous = options.leading === false ? 0 : _.now(); + timeout = null; + result = func.apply(context, args); + if (!timeout) context = args = null; + }; + return function() { + var now = _.now(); + if (!previous && options.leading === false) previous = now; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0 || remaining > wait) { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + previous = now; + result = func.apply(context, args); + if (!timeout) context = args = null; + } else if (!timeout && options.trailing !== false) { + timeout = setTimeout(later, remaining); + } + return result; + }; + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. If `immediate` is passed, trigger the function on the + // leading edge, instead of the trailing. + _.debounce = function(func, wait, immediate) { + var timeout, args, context, timestamp, result; + + var later = function() { + var last = _.now() - timestamp; + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + if (!timeout) context = args = null; + } + } + }; + + return function() { + context = this; + args = arguments; + timestamp = _.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + + return result; + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return _.partial(wrapper, func); + }; + + // Returns a negated version of the passed-in predicate. + _.negate = function(predicate) { + return function() { + return !predicate.apply(this, arguments); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var args = arguments; + var start = args.length - 1; + return function() { + var i = start; + var result = args[start].apply(this, arguments); + while (i--) result = args[i].call(this, result); + return result; + }; + }; + + // Returns a function that will only be executed on and after the Nth call. + _.after = function(times, func) { + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Returns a function that will only be executed up to (but not including) the Nth call. + _.before = function(times, func) { + var memo; + return function() { + if (--times > 0) { + memo = func.apply(this, arguments); + } + if (times <= 1) func = null; + return memo; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = _.partial(_.before, 2); + + // Object Functions + // ---------------- + + // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. + var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); + var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', + 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; + + function collectNonEnumProps(obj, keys) { + var nonEnumIdx = nonEnumerableProps.length; + var constructor = obj.constructor; + var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; + + // Constructor is a special case. + var prop = 'constructor'; + if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); + + while (nonEnumIdx--) { + prop = nonEnumerableProps[nonEnumIdx]; + if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { + keys.push(prop); + } + } + } + + // Retrieve the names of an object's own properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = function(obj) { + if (!_.isObject(obj)) return []; + if (nativeKeys) return nativeKeys(obj); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve all the property names of an object. + _.allKeys = function(obj) { + if (!_.isObject(obj)) return []; + var keys = []; + for (var key in obj) keys.push(key); + // Ahem, IE < 9. + if (hasEnumBug) collectNonEnumProps(obj, keys); + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var values = Array(length); + for (var i = 0; i < length; i++) { + values[i] = obj[keys[i]]; + } + return values; + }; + + // Returns the results of applying the iteratee to each element of the object + // In contrast to _.map it returns an object + _.mapObject = function(obj, iteratee, context) { + iteratee = cb(iteratee, context); + var keys = _.keys(obj), + length = keys.length, + results = {}, + currentKey; + for (var index = 0; index < length; index++) { + currentKey = keys[index]; + results[currentKey] = iteratee(obj[currentKey], currentKey, obj); + } + return results; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var keys = _.keys(obj); + var length = keys.length; + var pairs = Array(length); + for (var i = 0; i < length; i++) { + pairs[i] = [keys[i], obj[keys[i]]]; + } + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.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; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = createAssigner(_.allKeys); + + // Assigns a given object with all the own properties in the passed-in object(s) + // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + _.extendOwn = _.assign = createAssigner(_.keys); + + // Returns the first key on an object that passes a predicate test + _.findKey = function(obj, predicate, context) { + predicate = cb(predicate, context); + var keys = _.keys(obj), key; + for (var i = 0, length = keys.length; i < length; i++) { + key = keys[i]; + if (predicate(obj[key], key, obj)) return key; + } + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(object, oiteratee, context) { + var result = {}, obj = object, iteratee, keys; + if (obj == null) return result; + if (_.isFunction(oiteratee)) { + keys = _.allKeys(obj); + iteratee = optimizeCb(oiteratee, context); + } else { + keys = flatten(arguments, false, false, 1); + iteratee = function(value, key, obj) { return key in obj; }; + obj = Object(obj); + } + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i]; + var value = obj[key]; + if (iteratee(value, key, obj)) result[key] = value; + } + return result; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj, iteratee, context) { + if (_.isFunction(iteratee)) { + iteratee = _.negate(iteratee); + } else { + var keys = _.map(flatten(arguments, false, false, 1), String); + iteratee = function(value, key) { + return !_.contains(keys, key); + }; + } + return _.pick(obj, iteratee, context); + }; + + // Fill in a given object with default properties. + _.defaults = createAssigner(_.allKeys, true); + + // Creates an object that inherits from the given prototype object. + // If additional properties are provided then they will be added to the + // created object. + _.create = function(prototype, props) { + var result = baseCreate(prototype); + if (props) _.extendOwn(result, props); + return result; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + if (!_.isObject(obj)) return obj; + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Returns whether an object has a given set of `key:value` pairs. + _.isMatch = function(object, attrs) { + var keys = _.keys(attrs), length = keys.length; + if (object == null) return !length; + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (attrs[key] !== obj[key] || !(key in obj)) return false; + } + return true; + }; + + + // Internal recursive comparison function for `isEqual`. + var eq = function(a, b, aStack, bStack) { + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) return a !== 0 || 1 / a === 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className !== toString.call(b)) return false; + switch (className) { + // Strings, numbers, regular expressions, dates, and booleans are compared by value. + case '[object RegExp]': + // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return '' + a === '' + b; + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. + // Object(NaN) is equivalent to NaN + if (+a !== +a) return +b !== +b; + // An `egal` comparison is performed for other numeric values. + return +a === 0 ? 1 / +a === 1 / b : +a === +b; + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a === +b; + } + + var areArrays = className === '[object Array]'; + if (!areArrays) { + if (typeof a != 'object' || typeof b != 'object') return false; + + // Objects with different constructors are not equivalent, but `Object`s or `Array`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && + _.isFunction(bCtor) && bCtor instanceof bCtor) + && ('constructor' in a && 'constructor' in b)) { + return false; + } + } + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + + // Initializing stack of traversed objects. + // It's done here since we only need them for objects and arrays comparison. + aStack = aStack || []; + bStack = bStack || []; + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] === a) return bStack[length] === b; + } + + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + + // Recursively compare objects and arrays. + if (areArrays) { + // Compare array lengths to determine if a deep comparison is necessary. + length = a.length; + if (length !== b.length) return false; + // Deep compare the contents, ignoring non-numeric properties. + while (length--) { + if (!eq(a[length], b[length], aStack, bStack)) return false; + } + } else { + // Deep compare objects. + var keys = _.keys(a), key; + length = keys.length; + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (_.keys(b).length !== length) return false; + while (length--) { + // Deep compare each member + key = keys[length]; + if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return true; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + return eq(a, b); + }; + + // Is a given array, string, or object empty? + // An "empty" object has no enumerable own-properties. + _.isEmpty = function(obj) { + if (obj == null) return true; + if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; + return _.keys(obj).length === 0; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) === '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. + _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) === '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE < 9), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return _.has(obj, 'callee'); + }; + } + + // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, + // IE 11 (#1621), and in Safari 8 (#1929). + if (typeof /./ != 'function' && typeof Int8Array != 'object') { + _.isFunction = function(obj) { + return typeof obj == 'function' || false; + }; + } + + // Is a given object a finite number? + _.isFinite = function(obj) { + return isFinite(obj) && !isNaN(parseFloat(obj)); + }; + + // Is the given value `NaN`? (NaN is the only number which does not equal itself). + _.isNaN = function(obj) { + return _.isNumber(obj) && obj !== +obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Shortcut function for checking if an object has a given property directly + // on itself (in other words, not on a prototype). + _.has = function(obj, key) { + return obj != null && hasOwnProperty.call(obj, key); + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iteratees. + _.identity = function(value) { + return value; + }; + + // Predicate-generating functions. Often useful outside of Underscore. + _.constant = function(value) { + return function() { + return value; + }; + }; + + _.noop = function(){}; + + _.property = property; + + // Generates a function for a given object that returns a given property. + _.propertyOf = function(obj) { + return obj == null ? function(){} : function(key) { + return obj[key]; + }; + }; + + // Returns a predicate for checking whether an object has a given set of + // `key:value` pairs. + _.matcher = _.matches = function(attrs) { + attrs = _.extendOwn({}, attrs); + return function(obj) { + return _.isMatch(obj, attrs); + }; + }; + + // Run a function **n** times. + _.times = function(n, iteratee, context) { + var accum = Array(Math.max(0, n)); + iteratee = optimizeCb(iteratee, context, 1); + for (var i = 0; i < n; i++) accum[i] = iteratee(i); + return accum; + }; + + // Return a random integer between min and max (inclusive). + _.random = function(min, max) { + if (max == null) { + max = min; + min = 0; + } + return min + Math.floor(Math.random() * (max - min + 1)); + }; + + // A (possibly faster) way to get the current timestamp as an integer. + _.now = Date.now || function() { + return new Date().getTime(); + }; + + // List of HTML entities for escaping. + var escapeMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + var unescapeMap = _.invert(escapeMap); + + // Functions for escaping and unescaping strings to/from HTML interpolation. + var createEscaper = function(map) { + var escaper = function(match) { + return map[match]; + }; + // Regexes for identifying a key that needs to be escaped + var source = '(?:' + _.keys(map).join('|') + ')'; + var testRegexp = RegExp(source); + var replaceRegexp = RegExp(source, 'g'); + return function(string) { + string = string == null ? '' : '' + string; + return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; + }; + }; + _.escape = createEscaper(escapeMap); + _.unescape = createEscaper(unescapeMap); + + // If the value of the named `property` is a function then invoke it with the + // `object` as context; otherwise, return it. + _.result = function(object, property, fallback) { + var value = object == null ? void 0 : object[property]; + if (value === void 0) { + value = fallback; + } + return _.isFunction(value) ? value.call(object) : value; + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = ++idCounter + ''; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\u2028|\u2029/g; + + var escapeChar = function(match) { + return '\\' + escapes[match]; + }; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + // NB: `oldSettings` only exists for backwards compatibility. + _.template = function(text, settings, oldSettings) { + if (!settings && oldSettings) settings = oldSettings; + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset).replace(escaper, escapeChar); + index = offset + match.length; + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } else if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } else if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + + // Adobe VMs need the match returned to produce the correct offest. + return match; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + 'return __p;\n'; + + try { + var render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled source as a convenience for precompilation. + var argument = settings.variable || 'obj'; + template.source = 'function(' + argument + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function. Start chaining a wrapped Underscore object. + _.chain = function(obj) { + var instance = _(obj); + instance._chain = true; + return instance; + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(instance, obj) { + return instance._chain ? _(obj).chain() : obj; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + _.each(_.functions(obj), function(name) { + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result(this, func.apply(_, args)); + }; + }); + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; + return result(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + _.each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result(this, method.apply(this._wrapped, arguments)); + }; + }); + + // Extracts the result from a wrapped and chained object. + _.prototype.value = function() { + return this._wrapped; + }; + + // Provide unwrapping proxy for some methods used in engine operations + // such as arithmetic and JSON stringification. + _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; + + _.prototype.toString = function() { + return '' + this._wrapped; + }; + + // AMD registration happens at the end for compatibility with AMD loaders + // that may not enforce next-turn semantics on modules. Even though general + // practice for AMD registration is to be anonymous, underscore registers + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { + return _; + }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } +}.call(this)); + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(41).Promise; + +Promise._continueWhile = function (predicate, asyncFunction) { + if (predicate()) { + return asyncFunction().then(function () { + return Promise._continueWhile(predicate, asyncFunction); + }); + } + return Promise.resolve(); +}; + +module.exports = Promise; + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var request = __webpack_require__(7); +var debug = __webpack_require__(5)('leancloud:request'); +var md5 = __webpack_require__(44); +var Promise = __webpack_require__(1); +var Cache = __webpack_require__(10); +var AVError = __webpack_require__(3); +var AV = __webpack_require__(6); +var _ = __webpack_require__(0); + +var _require = __webpack_require__(4), + getSessionToken = _require.getSessionToken; + +var getServerURLPromise = void 0; + +// 服务器请求的节点 host +var API_HOST = { + cn: 'https://api.leancloud.cn', + us: 'https://us-api.leancloud.cn' +}; + +// 计算 X-LC-Sign 的签名方法 +var sign = function sign(key, isMasterKey) { + var now = new Date().getTime(); + var signature = md5(now + key); + if (isMasterKey) { + return signature + ',' + now + ',master'; + } + return signature + ',' + now; +}; + +var requestsCount = 0; + +var ajax = function ajax(method, resourceUrl, data) { + var headers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var onprogress = arguments[4]; + + var count = requestsCount++; + + debug('request(' + count + ')', method, resourceUrl, data, headers); + + return new Promise(function (resolve, reject) { + var req = request(method, resourceUrl).set(headers).send(data); + if (onprogress) { + req.on('progress', onprogress); + } + req.end(function (err, res) { + if (res) { + debug('response(' + count + ')', res.status, res.body || res.text, res.header); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + return resolve(res.body); + }); + }); +}; + +var setAppKey = function setAppKey(headers, signKey) { + if (signKey) { + headers['X-LC-Sign'] = sign(AV.applicationKey); + } else { + headers['X-LC-Key'] = AV.applicationKey; + } +}; + +var setHeaders = function setHeaders() { + var authOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var signKey = arguments[1]; + + var headers = { + 'X-LC-Id': AV.applicationId, + 'Content-Type': 'application/json;charset=UTF-8' + }; + var useMasterKey = false; + if (typeof authOptions.useMasterKey === 'boolean') { + useMasterKey = authOptions.useMasterKey; + } else if (typeof AV._useMasterKey === 'boolean') { + useMasterKey = AV._useMasterKey; + } + if (useMasterKey) { + if (AV.masterKey) { + if (signKey) { + headers['X-LC-Sign'] = sign(AV.masterKey, true); + } else { + headers['X-LC-Key'] = AV.masterKey + ',master'; + } + } else { + console.warn('masterKey is not set, fall back to use appKey'); + setAppKey(headers, signKey); + } + } else { + setAppKey(headers, signKey); + } + if (AV.hookKey) { + headers['X-LC-Hook-Key'] = AV.hookKey; + } + if (AV._config.applicationProduction !== null) { + headers['X-LC-Prod'] = String(AV._config.applicationProduction); + } + headers[ false ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent; + + return Promise.resolve().then(function () { + // Pass the session token + var sessionToken = getSessionToken(authOptions); + if (sessionToken) { + headers['X-LC-Session'] = sessionToken; + } else if (!AV._config.disableCurrentUser) { + return AV.User.currentAsync().then(function (currentUser) { + if (currentUser && currentUser._sessionToken) { + headers['X-LC-Session'] = currentUser._sessionToken; + } + return headers; + }); + } + return headers; + }); +}; + +var createApiUrl = function createApiUrl(route, className, objectId, method, dataObject) { + // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉 + if (AV.serverURL) { + AV._config.APIServerURL = AV.serverURL; + console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.'); + } + + var apiURL = AV._config.APIServerURL || API_HOST.cn; + + if (apiURL.charAt(apiURL.length - 1) !== '/') { + apiURL += '/'; + } + apiURL += '1.1/' + route; + if (className) { + apiURL += '/' + className; + } + if (objectId) { + apiURL += '/' + objectId; + } + if ((route === 'users' || route === 'classes') && dataObject) { + apiURL += '?'; + if (dataObject._fetchWhenSave) { + delete dataObject._fetchWhenSave; + apiURL += '&new=true'; + } + if (dataObject._where) { + apiURL += '&where=' + encodeURIComponent(JSON.stringify(dataObject._where)); + delete dataObject._where; + } + } + + if (method.toLowerCase() === 'get') { + if (apiURL.indexOf('?') === -1) { + apiURL += '?'; + } + for (var k in dataObject) { + if (_typeof(dataObject[k]) === 'object') { + dataObject[k] = JSON.stringify(dataObject[k]); + } + apiURL += '&' + k + '=' + encodeURIComponent(dataObject[k]); + } + } + + return apiURL; +}; + +var cacheServerURL = function cacheServerURL(serverURL, ttl) { + if (typeof ttl !== 'number') { + ttl = 3600; + } + return Cache.setAsync('APIServerURL', serverURL, ttl * 1000); +}; + +// handle AV._request Error +var handleError = function handleError(error) { + return new Promise(function (resolve, reject) { + /** + When API request need to redirect to the right location, + can't use browser redirect by http status 307, as the reason of CORS, + so API server response http status 410 and the param "location" for this case. + */ + if (error.statusCode === 410) { + cacheServerURL(error.response.api_server, error.response.ttl).then(function () { + resolve(error.response.location); + }).catch(reject); + } else { + var errorJSON = { + code: error.code || -1, + error: error.message || error.responseText + }; + if (error.response && error.response.code) { + errorJSON = error.response; + } else if (error.responseText) { + try { + errorJSON = JSON.parse(error.responseText); + } catch (e) { + // If we fail to parse the error text, that's okay. + } + } + + // Transform the error into an instance of AVError by trying to parse + // the error string as JSON. + reject(new AVError(errorJSON.code, errorJSON.error)); + } + }); +}; + +var setServerUrl = function setServerUrl(serverURL) { + AV._config.APIServerURL = 'https://' + serverURL; + + // 根据新 URL 重新设置区域 + var newRegion = _.findKey(API_HOST, function (item) { + return item === AV._config.APIServerURL; + }); + if (newRegion) { + AV._config.region = newRegion; + } +}; + +var refreshServerUrlByRouter = function refreshServerUrlByRouter() { + var url = 'https://app-router.leancloud.cn/1/route?appId=' + AV.applicationId; + return ajax('get', url).then(function (servers) { + if (servers.api_server) { + setServerUrl(servers.api_server); + return cacheServerURL(servers.api_server, servers.ttl); + } + }, function (error) { + // bypass all non-4XX errors + if (error.statusCode >= 400 && error.statusCode < 500) { + throw error; + } + }); +}; + +var setServerUrlByRegion = function setServerUrlByRegion() { + var region = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'cn'; + + getServerURLPromise = new Promise(function (resolve, reject) { + // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router + if (AV._config.APIServerURL) { + resolve(); + return; + } + // if not china server region, do not use router + if (region === 'cn') { + return Cache.getAsync('APIServerURL').then(function (serverURL) { + if (serverURL) { + setServerUrl(serverURL); + } else { + return refreshServerUrlByRouter(); + } + }).then(function () { + resolve(); + }).catch(function (error) { + reject(error); + }); + } else { + AV._config.region = region; + AV._config.APIServerURL = API_HOST[region]; + resolve(); + } + }); +}; + +/** + * route is classes, users, login, etc. + * objectId is null if there is no associated objectId. + * method is the http method for the REST API. + * dataObject is the payload as an object, or null if there is none. + * @ignore + */ +var AVRequest = function AVRequest(route, className, objectId, method) { + var dataObject = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + var authOptions = arguments[5]; + + if (!AV.applicationId) { + throw new Error('You must specify your applicationId using AV.init()'); + } + + if (!AV.applicationKey && !AV.masterKey) { + throw new Error('You must specify a AppKey using AV.init()'); + } + + if (!getServerURLPromise) { + return Promise.reject(new Error('Not initialized')); + } + return getServerURLPromise.then(function () { + var apiURL = createApiUrl(route, className, objectId, method, dataObject); + return setHeaders(authOptions, route !== 'bigquery').then(function (headers) { + return ajax(method, apiURL, dataObject, headers).then(null, function (res) { + return handleError(res).then(function (location) { + return ajax(method, location, dataObject, headers); + }); + }); + }); + }); +}; + +module.exports = { + ajax: ajax, + request: AVRequest, + setServerUrlByRegion: setServerUrlByRegion +}; + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +/** + * @class AV.Error + */ + +function AVError(code, message) { + var error = new Error(message); + error.code = code; + return error; +} + +_.extend(AVError, /** @lends AV.Error */{ + /** + * Error code indicating some error other than those enumerated here. + * @constant + */ + OTHER_CAUSE: -1, + + /** + * Error code indicating that something has gone wrong with the server. + * If you get this error code, it is AV's fault. Contact us at + * https://avoscloud.com/help + * @constant + */ + INTERNAL_SERVER_ERROR: 1, + + /** + * Error code indicating the connection to the AV servers failed. + * @constant + */ + CONNECTION_FAILED: 100, + + /** + * Error code indicating the specified object doesn't exist. + * @constant + */ + OBJECT_NOT_FOUND: 101, + + /** + * Error code indicating you tried to query with a datatype that doesn't + * support it, like exact matching an array or object. + * @constant + */ + INVALID_QUERY: 102, + + /** + * Error code indicating a missing or invalid classname. Classnames are + * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the + * only valid characters. + * @constant + */ + INVALID_CLASS_NAME: 103, + + /** + * Error code indicating an unspecified object id. + * @constant + */ + MISSING_OBJECT_ID: 104, + + /** + * Error code indicating an invalid key name. Keys are case-sensitive. They + * must start with a letter, and a-zA-Z0-9_ are the only valid characters. + * @constant + */ + INVALID_KEY_NAME: 105, + + /** + * Error code indicating a malformed pointer. You should not see this unless + * you have been mucking about changing internal AV code. + * @constant + */ + INVALID_POINTER: 106, + + /** + * Error code indicating that badly formed JSON was received upstream. This + * either indicates you have done something unusual with modifying how + * things encode to JSON, or the network is failing badly. + * @constant + */ + INVALID_JSON: 107, + + /** + * Error code indicating that the feature you tried to access is only + * available internally for testing purposes. + * @constant + */ + COMMAND_UNAVAILABLE: 108, + + /** + * You must call AV.initialize before using the AV library. + * @constant + */ + NOT_INITIALIZED: 109, + + /** + * Error code indicating that a field was set to an inconsistent type. + * @constant + */ + INCORRECT_TYPE: 111, + + /** + * Error code indicating an invalid channel name. A channel name is either + * an empty string (the broadcast channel) or contains only a-zA-Z0-9_ + * characters. + * @constant + */ + INVALID_CHANNEL_NAME: 112, + + /** + * Error code indicating that push is misconfigured. + * @constant + */ + PUSH_MISCONFIGURED: 115, + + /** + * Error code indicating that the object is too large. + * @constant + */ + OBJECT_TOO_LARGE: 116, + + /** + * Error code indicating that the operation isn't allowed for clients. + * @constant + */ + OPERATION_FORBIDDEN: 119, + + /** + * Error code indicating the result was not found in the cache. + * @constant + */ + CACHE_MISS: 120, + + /** + * Error code indicating that an invalid key was used in a nested + * JSONObject. + * @constant + */ + INVALID_NESTED_KEY: 121, + + /** + * Error code indicating that an invalid filename was used for AVFile. + * A valid file name contains only a-zA-Z0-9_. characters and is between 1 + * and 128 characters. + * @constant + */ + INVALID_FILE_NAME: 122, + + /** + * Error code indicating an invalid ACL was provided. + * @constant + */ + INVALID_ACL: 123, + + /** + * Error code indicating that the request timed out on the server. Typically + * this indicates that the request is too expensive to run. + * @constant + */ + TIMEOUT: 124, + + /** + * Error code indicating that the email address was invalid. + * @constant + */ + INVALID_EMAIL_ADDRESS: 125, + + /** + * Error code indicating a missing content type. + * @constant + */ + MISSING_CONTENT_TYPE: 126, + + /** + * Error code indicating a missing content length. + * @constant + */ + MISSING_CONTENT_LENGTH: 127, + + /** + * Error code indicating an invalid content length. + * @constant + */ + INVALID_CONTENT_LENGTH: 128, + + /** + * Error code indicating a file that was too large. + * @constant + */ + FILE_TOO_LARGE: 129, + + /** + * Error code indicating an error saving a file. + * @constant + */ + FILE_SAVE_ERROR: 130, + + /** + * Error code indicating an error deleting a file. + * @constant + */ + FILE_DELETE_ERROR: 153, + + /** + * Error code indicating that a unique field was given a value that is + * already taken. + * @constant + */ + DUPLICATE_VALUE: 137, + + /** + * Error code indicating that a role's name is invalid. + * @constant + */ + INVALID_ROLE_NAME: 139, + + /** + * Error code indicating that an application quota was exceeded. Upgrade to + * resolve. + * @constant + */ + EXCEEDED_QUOTA: 140, + + /** + * Error code indicating that a Cloud Code script failed. + * @constant + */ + SCRIPT_FAILED: 141, + + /** + * Error code indicating that a Cloud Code validation failed. + * @constant + */ + VALIDATION_ERROR: 142, + + /** + * Error code indicating that invalid image data was provided. + * @constant + */ + INVALID_IMAGE_DATA: 150, + + /** + * Error code indicating an unsaved file. + * @constant + */ + UNSAVED_FILE_ERROR: 151, + + /** + * Error code indicating an invalid push time. + */ + INVALID_PUSH_TIME_ERROR: 152, + + /** + * Error code indicating that the username is missing or empty. + * @constant + */ + USERNAME_MISSING: 200, + + /** + * Error code indicating that the password is missing or empty. + * @constant + */ + PASSWORD_MISSING: 201, + + /** + * Error code indicating that the username has already been taken. + * @constant + */ + USERNAME_TAKEN: 202, + + /** + * Error code indicating that the email has already been taken. + * @constant + */ + EMAIL_TAKEN: 203, + + /** + * Error code indicating that the email is missing, but must be specified. + * @constant + */ + EMAIL_MISSING: 204, + + /** + * Error code indicating that a user with the specified email was not found. + * @constant + */ + EMAIL_NOT_FOUND: 205, + + /** + * Error code indicating that a user object without a valid session could + * not be altered. + * @constant + */ + SESSION_MISSING: 206, + + /** + * Error code indicating that a user can only be created through signup. + * @constant + */ + MUST_CREATE_USER_THROUGH_SIGNUP: 207, + + /** + * Error code indicating that an an account being linked is already linked + * to another user. + * @constant + */ + ACCOUNT_ALREADY_LINKED: 208, + + /** + * Error code indicating that a user cannot be linked to an account because + * that account's id could not be found. + * @constant + */ + LINKED_ID_MISSING: 250, + + /** + * Error code indicating that a user with a linked (e.g. Facebook) account + * has an invalid session. + * @constant + */ + INVALID_LINKED_SESSION: 251, + + /** + * Error code indicating that a service being linked (e.g. Facebook or + * Twitter) is unsupported. + * @constant + */ + UNSUPPORTED_SERVICE: 252, + /** + * Error code indicating a real error code is unavailable because + * we had to use an XDomainRequest object to allow CORS requests in + * Internet Explorer, which strips the body from HTTP responses that have + * a non-2XX status code. + * @constant + */ + X_DOMAIN_REQUEST: 602 +}); + +module.exports = AVError; + +/***/ }), +/* 4 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +// Helper function to check null or undefined. +var isNullOrUndefined = function isNullOrUndefined(x) { + return _.isNull(x) || _.isUndefined(x); +}; + +var ensureArray = function ensureArray(target) { + if (_.isArray(target)) { + return target; + } + if (target === undefined || target === null) { + return []; + } + return [target]; +}; + +var getSessionToken = function getSessionToken(authOptions) { + if (authOptions.sessionToken) { + return authOptions.sessionToken; + } + if (authOptions.user && typeof authOptions.user.getSessionToken === 'function') { + return authOptions.user.getSessionToken(); + } +}; + +var tap = function tap(interceptor) { + return function (value) { + return interceptor(value), value; + }; +}; + +module.exports = { + isNullOrUndefined: isNullOrUndefined, + ensureArray: ensureArray, + getSessionToken: getSessionToken, + tap: tap +}; + +/***/ }), +/* 5 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = __webpack_require__(40); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var _ = __webpack_require__(0); +var userAgent = __webpack_require__(32); + +var _require = __webpack_require__(4), + isNullOrUndefined = _require.isNullOrUndefined; + +var AV = global.AV || {}; + +// All internal configuration items +AV._config = AV._config || {}; +var AVConfig = AV._config; + +_.extend(AVConfig, { + + // 服务器节点地区,默认中国大陆 + region: 'cn', + + // 服务器的 URL,默认初始化时被设置为大陆节点地址 + APIServerURL: AVConfig.APIServerURL || '', + + // 禁用 currentUser,通常用于多用户环境 + disableCurrentUser: false, + + // Internal config can modifie the UserAgent + userAgent: userAgent, + + // set production environment or test environment + // 1: production environment, 0: test environment, null: default environment + applicationProduction: null +}); + +/** + * Contains all AV API classes and functions. + * @namespace AV + */ + +// Helpers +// ------- + +// Shared empty constructor function to aid in prototype-chain creation. +var EmptyConstructor = function EmptyConstructor() {}; + +// Helper function to correctly set up the prototype chain, for subclasses. +// Similar to `goog.inherits`, but uses a hash of prototype properties and +// class properties to be extended. +var inherits = function inherits(parent, protoProps, staticProps) { + var child; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent's constructor. + if (protoProps && protoProps.hasOwnProperty('constructor')) { + child = protoProps.constructor; + } else { + /** @ignore */ + child = function child() { + parent.apply(this, arguments); + }; + } + + // Inherit class (static) properties from parent. + _.extend(child, parent); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + EmptyConstructor.prototype = parent.prototype; + child.prototype = new EmptyConstructor(); + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) { + _.extend(child.prototype, protoProps); + } + + // Add static properties to the constructor function, if supplied. + if (staticProps) { + _.extend(child, staticProps); + } + + // Correctly set child's `prototype.constructor`. + child.prototype.constructor = child; + + // Set a convenience property in case the parent's prototype is + // needed later. + child.__super__ = parent.prototype; + + return child; +}; + +/** + * Call this method to set production environment variable. + * @function AV.setProduction + * @param {Boolean} production True is production environment,and + * it's true by default. + */ +AV.setProduction = function (production) { + if (!isNullOrUndefined(production)) { + AVConfig.applicationProduction = production ? 1 : 0; + } else { + // change to default value + AVConfig.applicationProduction = null; + } +}; + +/** + * Returns prefix for localStorage keys used by this instance of AV. + * @param {String} path The relative suffix to append to it. + * null or undefined is treated as the empty string. + * @return {String} The full key name. + * @private + */ +AV._getAVPath = function (path) { + if (!AV.applicationId) { + throw new Error("You need to call AV.initialize before using AV."); + } + if (!path) { + path = ""; + } + if (!_.isString(path)) { + throw new Error("Tried to get a localStorage path that wasn't a String."); + } + if (path[0] === "/") { + path = path.substring(1); + } + return "AV/" + AV.applicationId + "/" + path; +}; + +/** + * Returns the unique string for this app on this machine. + * Gets reset when localStorage is cleared. + * @private + */ +AV._installationId = null; +AV._getInstallationId = function () { + // See if it's cached in RAM. + if (AV._installationId) { + return AV.Promise.resolve(AV._installationId); + } + + // Try to get it from localStorage. + var path = AV._getAVPath("installationId"); + return AV.localStorage.getItemAsync(path).then(function (_installationId) { + AV._installationId = _installationId; + if (!AV._installationId) { + // It wasn't in localStorage, so create a new one. + var hexOctet = function hexOctet() { + return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + }; + AV._installationId = hexOctet() + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + hexOctet() + hexOctet(); + return AV.localStorage.setItemAsync(path, AV._installationId); + } else { + return _installationId; + } + }); +}; + +AV._parseDate = function (iso8601) { + var regexp = new RegExp("^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})" + "T" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})" + "(.([0-9]+))?" + "Z$"); + var match = regexp.exec(iso8601); + if (!match) { + return null; + } + + var year = match[1] || 0; + var month = (match[2] || 1) - 1; + var day = match[3] || 0; + var hour = match[4] || 0; + var minute = match[5] || 0; + var second = match[6] || 0; + var milli = match[8] || 0; + + return new Date(Date.UTC(year, month, day, hour, minute, second, milli)); +}; + +// A self-propagating extend function. +AV._extend = function (protoProps, classProps) { + var child = inherits(this, protoProps, classProps); + child.extend = this.extend; + return child; +}; + +// Helper function to get a value from a Backbone object as a property +// or as a function. +AV._getValue = function (object, prop) { + if (!(object && object[prop])) { + return null; + } + return _.isFunction(object[prop]) ? object[prop]() : object[prop]; +}; + +/** + * Converts a value in a AV Object into the appropriate representation. + * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object) + * if seenObjects is falsey. Otherwise any AV.Objects not in + * seenObjects will be fully embedded rather than encoded + * as a pointer. This array will be used to prevent going into an infinite + * loop because we have circular references. If + * is set, then none of the AV Objects that are serialized can be dirty. + * @private + */ +AV._encode = function (value, seenObjects, disallowObjects) { + if (value instanceof AV.Object) { + if (disallowObjects) { + throw new Error("AV.Objects not allowed here"); + } + if (!seenObjects || _.include(seenObjects, value) || !value._hasData) { + return value._toPointer(); + } + if (!value.dirty()) { + seenObjects = seenObjects.concat(value); + return AV._encode(value._toFullJSON(seenObjects), seenObjects, disallowObjects); + } + throw new Error("Tried to save an object with a pointer to a new, unsaved object."); + } + if (value instanceof AV.ACL) { + return value.toJSON(); + } + if (_.isDate(value)) { + return { "__type": "Date", "iso": value.toJSON() }; + } + if (value instanceof AV.GeoPoint) { + return value.toJSON(); + } + if (_.isArray(value)) { + return _.map(value, function (x) { + return AV._encode(x, seenObjects, disallowObjects); + }); + } + if (_.isRegExp(value)) { + return value.source; + } + if (value instanceof AV.Relation) { + return value.toJSON(); + } + if (value instanceof AV.Op) { + return value.toJSON(); + } + if (value instanceof AV.File) { + if (!value.url() && !value.id) { + throw new Error("Tried to save an object containing an unsaved file."); + } + return value._toFullJSON(); + } + if (_.isObject(value)) { + return _.mapObject(value, function (v, k) { + return AV._encode(v, seenObjects, disallowObjects); + }); + } + return value; +}; + +/** + * The inverse function of AV._encode. + * @private + */ +AV._decode = function (value, key) { + if (!_.isObject(value) || _.isDate(value)) { + return value; + } + if (_.isArray(value)) { + return _.map(value, function (v) { + return AV._decode(v); + }); + } + if (value instanceof AV.Object) { + return value; + } + if (value instanceof AV.File) { + return value; + } + if (value instanceof AV.Op) { + return value; + } + if (value instanceof AV.GeoPoint) { + return value; + } + if (value instanceof AV.ACL) { + return value; + } + if (key === 'ACL') { + return new AV.ACL(value); + } + if (value.__op) { + return AV.Op._decode(value); + } + var className; + if (value.__type === "Pointer") { + className = value.className; + var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + if (Object.keys(value).length > 3) { + var v = _.clone(value); + delete v.__type; + delete v.className; + pointer._finishFetch(v, true); + } else { + pointer._finishFetch({ objectId: value.objectId }, false); + } + return pointer; + } + if (value.__type === "Object") { + // It's an Object included in a query result. + className = value.className; + var _v = _.clone(value); + delete _v.__type; + delete _v.className; + var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + object._finishFetch(_v, true); + return object; + } + if (value.__type === "Date") { + return AV._parseDate(value.iso); + } + if (value.__type === "GeoPoint") { + return new AV.GeoPoint({ + latitude: value.latitude, + longitude: value.longitude + }); + } + if (value.__type === "Relation") { + if (!key) throw new Error('key missing decoding a Relation'); + var relation = new AV.Relation(null, key); + relation.targetClassName = value.className; + return relation; + } + if (value.__type === 'File') { + var file = new AV.File(value.name); + var _v2 = _.clone(value); + delete _v2.__type; + file._finishFetch(_v2); + return file; + } + return _.mapObject(value, AV._decode); +}; + +AV._encodeObjectOrArray = function (value) { + var encodeAVObject = function encodeAVObject(object) { + if (object && object._toFullJSON) { + object = object._toFullJSON([]); + } + + return _.mapObject(object, function (value) { + return AV._encode(value, []); + }); + }; + + if (_.isArray(value)) { + return value.map(function (object) { + return encodeAVObject(object); + }); + } else { + return encodeAVObject(value); + } +}; + +AV._arrayEach = _.each; + +/** + * Does a deep traversal of every item in object, calling func on every one. + * @param {Object} object The object or array to traverse deeply. + * @param {Function} func The function to call for every item. It will + * be passed the item as an argument. If it returns a truthy value, that + * value will replace the item in its parent container. + * @returns {} the result of calling func on the top-level object itself. + * @private + */ +AV._traverse = function (object, func, seen) { + if (object instanceof AV.Object) { + seen = seen || []; + if (_.indexOf(seen, object) >= 0) { + // We've already visited this object in this call. + return; + } + seen.push(object); + AV._traverse(object.attributes, func, seen); + return func(object); + } + if (object instanceof AV.Relation || object instanceof AV.File) { + // Nothing needs to be done, but we don't want to recurse into the + // object's parent infinitely, so we catch this case. + return func(object); + } + if (_.isArray(object)) { + _.each(object, function (child, index) { + var newChild = AV._traverse(child, func, seen); + if (newChild) { + object[index] = newChild; + } + }); + return func(object); + } + if (_.isObject(object)) { + AV._each(object, function (child, key) { + var newChild = AV._traverse(child, func, seen); + if (newChild) { + object[key] = newChild; + } + }); + return func(object); + } + return func(object); +}; + +/** + * This is like _.each, except: + * * it doesn't work for so-called array-like objects, + * * it does work for dictionaries with a "length" attribute. + * @private + */ +AV._objectEach = AV._each = function (obj, callback) { + if (_.isObject(obj)) { + _.each(_.keys(obj), function (key) { + callback(obj[key], key); + }); + } else { + _.each(obj, callback); + } +}; + +module.exports = AV; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) + +/***/ }), +/* 7 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Root reference for iframes. + */ + +var root; +if (typeof window !== 'undefined') { // Browser window + root = window; +} else if (typeof self !== 'undefined') { // Web Worker + root = self; +} else { // Other environments + console.warn("Using browser-only version of superagent in non-browser environment"); + root = this; +} + +var Emitter = __webpack_require__(38); +var RequestBase = __webpack_require__(47); +var isObject = __webpack_require__(8); +var isFunction = __webpack_require__(46); +var ResponseBase = __webpack_require__(48); +var shouldRetry = __webpack_require__(49); + +/** + * Noop. + */ + +function noop(){}; + +/** + * Expose `request`. + */ + +var request = exports = module.exports = function(method, url) { + // callback + if ('function' == typeof url) { + return new exports.Request('GET', method).end(url); + } + + // url first + if (1 == arguments.length) { + return new exports.Request('GET', method); + } + + return new exports.Request(method, url); +} + +exports.Request = Request; + +/** + * Determine XHR. + */ + +request.getXHR = function () { + if (root.XMLHttpRequest + && (!root.location || 'file:' != root.location.protocol + || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} + } + throw Error("Browser-only verison of superagent could not find XHR"); +}; + +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + +var trim = ''.trim + ? function(s) { return s.trim(); } + : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; + +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + for (var key in obj) { + pushEncodedKeyValuePair(pairs, key, obj[key]); + } + return pairs.join('&'); +} + +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + +function pushEncodedKeyValuePair(pairs, key, val) { + if (val != null) { + if (Array.isArray(val)) { + val.forEach(function(v) { + pushEncodedKeyValuePair(pairs, key, v); + }); + } else if (isObject(val)) { + for(var subkey in val) { + pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); + } + } else { + pairs.push(encodeURIComponent(key) + + '=' + encodeURIComponent(val)); + } + } else if (val === null) { + pairs.push(encodeURIComponent(key)); + } +} + +/** + * Expose serialization method. + */ + + request.serializeObject = serialize; + + /** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var pair; + var pos; + + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos == -1) { + obj[decodeURIComponent(pair)] = ''; + } else { + obj[decodeURIComponent(pair.slice(0, pos))] = + decodeURIComponent(pair.slice(pos + 1)); + } + } + + return obj; +} + +/** + * Expose parser. + */ + +request.parseString = parseString; + +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'application/xml', + urlencoded: 'application/x-www-form-urlencoded', + 'form': 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + + request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': JSON.stringify + }; + + /** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; + +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + + lines.pop(); // trailing CRLF + + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + + return fields; +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + return /[\/+]json\b/.test(mime); +} + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + +function Response(req) { + this.req = req; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') + ? this.xhr.responseText + : null; + this.statusText = this.req.xhr.statusText; + var status = this.xhr.status; + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + this._setStatusProperties(status); + this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + + if (null === this.text && req._responseType) { + this.body = this.xhr.response; + } else { + this.body = this.req.method != 'HEAD' + ? this._parseBody(this.text ? this.text : this.xhr.response) + : null; + } +} + +ResponseBase(Response.prototype); + +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function(str){ + var parse = request.parse[this.type]; + if(this.req._parser) { + return this.req._parser(this, str); + } + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && str && (str.length || str instanceof Object) + ? parse(str) + : null; +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function(){ + var req = this.req; + var method = req.method; + var url = req.url; + + var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + + return err; +}; + +/** + * Expose `Response`. + */ + +request.Response = Response; + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + var self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', function(){ + var err = null; + var res = null; + + try { + res = new Response(self); + } catch(e) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = e; + // issue #675: return the raw response if the response parsing fails + if (self.xhr) { + // ie9 doesn't have 'response' property + err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response; + // issue #876: return the http status code if the response parsing fails + err.status = self.xhr.status ? self.xhr.status : null; + err.statusCode = err.status; // backwards-compat only + } else { + err.rawResponse = null; + err.status = null; + } + + return self.callback(err); + } + + self.emit('response', res); + + var new_err; + try { + if (!self._isResponseOK(res)) { + new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + } + } catch(e) { + new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android + } + + // #1000 don't catch errors from the callback to avoid double calling it + if (new_err) { + self.callback(new_err, res); + } else { + self.callback(null, res); + } + }); +} + +/** + * Mixin `Emitter` and `RequestBase`. + */ + +Emitter(Request.prototype); +RequestBase(Request.prototype); + +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function(type){ + this.set('Content-Type', request.types[type] || type); + return this; +}; + +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function(type){ + this.set('Accept', request.types[type] || type); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} [pass] optional in case of using 'bearer' as type + * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function(user, pass, options){ + if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options + options = pass; + } + if (!options) { + options = { + type: 'function' === typeof btoa ? 'basic' : 'auto', + } + } + + switch (options.type) { + case 'basic': + this.set('Authorization', 'Basic ' + btoa(user + ':' + pass)); + break; + + case 'auto': + this.username = user; + this.password = pass; + break; + + case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' }) + this.set('Authorization', 'Bearer ' + user); + break; + } + return this; +}; + +/** + * Add query-string `val`. + * + * Examples: + * + * request.get('/shoes') + * .query('size=10') + * .query({ color: 'blue' }) + * + * @param {Object|String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.query = function(val){ + if ('string' != typeof val) val = serialize(val); + if (val) this._query.push(val); + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `options` (or filename). + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String|Object} options + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function(field, file, options){ + if (file) { + if (this._data) { + throw Error("superagent can't mix .send() and .attach()"); + } + + this._getFormData().append(field, file, options || file.name); + } + return this; +}; + +Request.prototype._getFormData = function(){ + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function(err, res){ + // console.log(this._retries, this._maxRetries) + if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) { + return this._retry(); + } + + var fn = this._callback; + this.clearTimeout(); + + if (err) { + if (this._maxRetries) err.retries = this._retries - 1; + this.emit('error', err); + } + + fn(err, res); +}; + +/** + * Invoke callback with x-domain error. + * + * @api private + */ + +Request.prototype.crossDomainError = function(){ + var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + err.crossDomain = true; + + err.status = this.status; + err.method = this.method; + err.url = this.url; + + this.callback(err); +}; + +// This only warns, because the request is still likely to work +Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){ + console.warn("This is not supported in browser version of superagent"); + return this; +}; + +// This throws, because it can't send/receive data as expected +Request.prototype.pipe = Request.prototype.write = function(){ + throw Error("Streaming is not supported in browser version of superagent"); +}; + +/** + * Compose querystring to append to req.url + * + * @api private + */ + +Request.prototype._appendQueryString = function(){ + var query = this._query.join('&'); + if (query) { + this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query; + } + + if (this._sort) { + var index = this.url.indexOf('?'); + if (index >= 0) { + var queryArr = this.url.substring(index + 1).split('&'); + if (isFunction(this._sort)) { + queryArr.sort(this._sort); + } else { + queryArr.sort(); + } + this.url = this.url.substring(0, index) + '?' + queryArr.join('&'); + } + } +}; + +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ +Request.prototype._isHost = function _isHost(obj) { + // Native objects stringify to [object File], [object Blob], [object FormData], etc. + return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; +} + +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype.end = function(fn){ + if (this._endCalled) { + console.warn("Warning: .end() was called twice. This is not supported in superagent"); + } + this._endCalled = true; + + // store callback + this._callback = fn || noop; + + // querystring + this._appendQueryString(); + + return this._end(); +}; + +Request.prototype._end = function() { + var self = this; + var xhr = this.xhr = request.getXHR(); + var data = this._formData || this._data; + + this._setTimeouts(); + + // state change + xhr.onreadystatechange = function(){ + var readyState = xhr.readyState; + if (readyState >= 2 && self._responseTimeoutTimer) { + clearTimeout(self._responseTimeoutTimer); + } + if (4 != readyState) { + return; + } + + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + var status; + try { status = xhr.status } catch(e) { status = 0; } + + if (!status) { + if (self.timedout || self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }; + + // progress + var handleProgress = function(direction, e) { + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + } + e.direction = direction; + self.emit('progress', e); + } + if (this.hasListeners('progress')) { + try { + xhr.onprogress = handleProgress.bind(null, 'download'); + if (xhr.upload) { + xhr.upload.onprogress = handleProgress.bind(null, 'upload'); + } + } catch(e) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + } + + // initiate request + try { + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + } catch (err) { + // see #1149 + return this.callback(err); + } + + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { + // serialize stuff + var contentType = this._header['content-type']; + var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) { + serialize = request.serialize['application/json']; + } + if (serialize) data = serialize(data); + } + + // set header fields + for (var field in this.header) { + if (null == this.header[field]) continue; + + if (this.header.hasOwnProperty(field)) + xhr.setRequestHeader(field, this.header[field]); + } + + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data !== 'undefined' ? data : null); + return this; +}; + +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; + +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.options = function(url, data, fn){ + var req = request('OPTIONS', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * DELETE `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +function del(url, data, fn){ + var req = request('DELETE', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +request['del'] = del; +request['delete'] = del; + +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} [data] + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} [data] or fn + * @param {Function} [fn] + * @return {Request} + * @api public + */ + +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports) { + +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isObject(obj) { + return null !== obj && 'object' === typeof obj; +} + +module.exports = isObject; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var storage = __webpack_require__(11); +var AV = __webpack_require__(6); + +var removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage); + +var getCacheData = function getCacheData(cacheData, key) { + try { + cacheData = JSON.parse(cacheData); + } catch (e) { + return null; + } + if (cacheData) { + var expired = cacheData.expiredAt && cacheData.expiredAt < Date.now(); + if (!expired) { + return cacheData.value; + } + return removeAsync(key).then(function () { + return null; + }); + } + return null; +}; + +exports.getAsync = function (key) { + key = AV.applicationId + '/' + key; + return storage.getItemAsync(key).then(function (cache) { + return getCacheData(cache, key); + }); +}; + +exports.setAsync = function (key, value, ttl) { + var cache = { value: value }; + if (typeof ttl === 'number') { + cache.expiredAt = Date.now() + ttl; + } + return storage.setItemAsync(AV.applicationId + '/' + key, JSON.stringify(cache)); +}; + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(1); +var localStorage = __webpack_require__(36); + +var syncApiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +if (!localStorage.async) { + // wrap sync apis with async ones. + _(syncApiNames).each(function (apiName) { + if (typeof localStorage[apiName] === 'function') { + localStorage[apiName + 'Async'] = function () { + return Promise.resolve(localStorage[apiName].apply(localStorage, arguments)); + }; + } + }); +} else { + _(syncApiNames).each(function (apiName) { + if (typeof localStorage[apiName] !== 'function') { + localStorage[apiName] = function () { + var error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.'); + error.code = 'SYNC_API_NOT_AVAILABLE'; + throw error; + }; + } + }); +} + +module.exports = localStorage; + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = '2.1.4'; + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + +var charenc = { + // UTF-8 encoding + utf8: { + // Convert a string to a byte array + stringToBytes: function(str) { + return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))); + }, + + // Convert a byte array to a string + bytesToString: function(bytes) { + return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))); + } + }, + + // Binary encoding + bin: { + // Convert a string to a byte array + stringToBytes: function(str) { + for (var bytes = [], i = 0; i < str.length; i++) + bytes.push(str.charCodeAt(i) & 0xFF); + return bytes; + }, + + // Convert a byte array to a string + bytesToString: function(bytes) { + for (var str = [], i = 0; i < bytes.length; i++) + str.push(String.fromCharCode(bytes[i])); + return str.join(''); + } + } +}; + +module.exports = charenc; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + var PUBLIC_KEY = "*"; + + /** + * Creates a new ACL. + * If no argument is given, the ACL has no permissions for anyone. + * If the argument is a AV.User, the ACL will have read and write + * permission for only that user. + * If the argument is any other JSON object, that object will be interpretted + * as a serialized ACL created with toJSON(). + * @see AV.Object#setACL + * @class + * + *

An ACL, or Access Control List can be added to any + * AV.Object to restrict access to only a subset of users + * of your application.

+ */ + AV.ACL = function (arg1) { + var self = this; + self.permissionsById = {}; + if (_.isObject(arg1)) { + if (arg1 instanceof AV.User) { + self.setReadAccess(arg1, true); + self.setWriteAccess(arg1, true); + } else { + if (_.isFunction(arg1)) { + throw new Error('AV.ACL() called with a function. Did you forget ()?'); + } + AV._objectEach(arg1, function (accessList, userId) { + if (!_.isString(userId)) { + throw new Error('Tried to create an ACL with an invalid userId.'); + } + self.permissionsById[userId] = {}; + AV._objectEach(accessList, function (allowed, permission) { + if (permission !== "read" && permission !== "write") { + throw new Error('Tried to create an ACL with an invalid permission type.'); + } + if (!_.isBoolean(allowed)) { + throw new Error('Tried to create an ACL with an invalid permission value.'); + } + self.permissionsById[userId][permission] = allowed; + }); + }); + } + } + }; + + /** + * Returns a JSON-encoded version of the ACL. + * @return {Object} + */ + AV.ACL.prototype.toJSON = function () { + return _.clone(this.permissionsById); + }; + + AV.ACL.prototype._setAccess = function (accessType, userId, allowed) { + if (userId instanceof AV.User) { + userId = userId.id; + } else if (userId instanceof AV.Role) { + userId = "role:" + userId.getName(); + } + if (!_.isString(userId)) { + throw new Error('userId must be a string.'); + } + if (!_.isBoolean(allowed)) { + throw new Error('allowed must be either true or false.'); + } + var permissions = this.permissionsById[userId]; + if (!permissions) { + if (!allowed) { + // The user already doesn't have this permission, so no action needed. + return; + } else { + permissions = {}; + this.permissionsById[userId] = permissions; + } + } + + if (allowed) { + this.permissionsById[userId][accessType] = true; + } else { + delete permissions[accessType]; + if (_.isEmpty(permissions)) { + delete this.permissionsById[userId]; + } + } + }; + + AV.ACL.prototype._getAccess = function (accessType, userId) { + if (userId instanceof AV.User) { + userId = userId.id; + } else if (userId instanceof AV.Role) { + userId = "role:" + userId.getName(); + } + var permissions = this.permissionsById[userId]; + if (!permissions) { + return false; + } + return permissions[accessType] ? true : false; + }; + + /** + * Set whether the given user is allowed to read this object. + * @param userId An instance of AV.User or its objectId. + * @param {Boolean} allowed Whether that user should have read access. + */ + AV.ACL.prototype.setReadAccess = function (userId, allowed) { + this._setAccess("read", userId, allowed); + }; + + /** + * Get whether the given user id is *explicitly* allowed to read this object. + * Even if this returns false, the user may still be able to access it if + * getPublicReadAccess returns true or a role that the user belongs to has + * write access. + * @param userId An instance of AV.User or its objectId, or a AV.Role. + * @return {Boolean} + */ + AV.ACL.prototype.getReadAccess = function (userId) { + return this._getAccess("read", userId); + }; + + /** + * Set whether the given user id is allowed to write this object. + * @param userId An instance of AV.User or its objectId, or a AV.Role.. + * @param {Boolean} allowed Whether that user should have write access. + */ + AV.ACL.prototype.setWriteAccess = function (userId, allowed) { + this._setAccess("write", userId, allowed); + }; + + /** + * Get whether the given user id is *explicitly* allowed to write this object. + * Even if this returns false, the user may still be able to write it if + * getPublicWriteAccess returns true or a role that the user belongs to has + * write access. + * @param userId An instance of AV.User or its objectId, or a AV.Role. + * @return {Boolean} + */ + AV.ACL.prototype.getWriteAccess = function (userId) { + return this._getAccess("write", userId); + }; + + /** + * Set whether the public is allowed to read this object. + * @param {Boolean} allowed + */ + AV.ACL.prototype.setPublicReadAccess = function (allowed) { + this.setReadAccess(PUBLIC_KEY, allowed); + }; + + /** + * Get whether the public is allowed to read this object. + * @return {Boolean} + */ + AV.ACL.prototype.getPublicReadAccess = function () { + return this.getReadAccess(PUBLIC_KEY); + }; + + /** + * Set whether the public is allowed to write this object. + * @param {Boolean} allowed + */ + AV.ACL.prototype.setPublicWriteAccess = function (allowed) { + this.setWriteAccess(PUBLIC_KEY, allowed); + }; + + /** + * Get whether the public is allowed to write this object. + * @return {Boolean} + */ + AV.ACL.prototype.getPublicWriteAccess = function () { + return this.getWriteAccess(PUBLIC_KEY); + }; + + /** + * Get whether users belonging to the given role are allowed + * to read this object. Even if this returns false, the role may + * still be able to write it if a parent role has read access. + * + * @param role The name of the role, or a AV.Role object. + * @return {Boolean} true if the role has read access. false otherwise. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.getRoleReadAccess = function (role) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + return this.getReadAccess("role:" + role); + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Get whether users belonging to the given role are allowed + * to write this object. Even if this returns false, the role may + * still be able to write it if a parent role has write access. + * + * @param role The name of the role, or a AV.Role object. + * @return {Boolean} true if the role has write access. false otherwise. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.getRoleWriteAccess = function (role) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + return this.getWriteAccess("role:" + role); + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Set whether users belonging to the given role are allowed + * to read this object. + * + * @param role The name of the role, or a AV.Role object. + * @param {Boolean} allowed Whether the given role can read this object. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.setRoleReadAccess = function (role, allowed) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + this.setReadAccess("role:" + role, allowed); + return; + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Set whether users belonging to the given role are allowed + * to write this object. + * + * @param role The name of the role, or a AV.Role object. + * @param {Boolean} allowed Whether the given role can write this object. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.setRoleWriteAccess = function (role, allowed) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + this.setWriteAccess("role:" + role, allowed); + return; + } + throw new Error('role must be a AV.Role or a String'); + }; +}; + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * Contains functions for calling and declaring + *

+ * Some functions are only available from Cloud Code. + *

+ * + * @namespace + */ + AV.Cloud = AV.Cloud || {}; + + _.extend(AV.Cloud, /** @lends AV.Cloud */{ + /** + * Makes a call to a cloud function. + * @param {String} name The function name. + * @param {Object} data The parameters to send to the cloud function. + * @param {AuthOptions} options + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + run: function run(name, data, options) { + var request = AVRequest('functions', name, null, 'POST', AV._encode(data, null, true), options); + + return request.then(function (resp) { + return AV._decode(resp).result; + }); + }, + + /** + * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response + * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object} + * @param {String} name The function name. + * @param {Object} data The parameters to send to the cloud function. + * @param {AuthOptions} options + * @return {Promise} A promise that will be resolved with the result of the function. + */ + rpc: function rpc(name, data, options) { + if (_.isArray(data)) { + return Promise.reject(new Error('Can\'t pass Array as the param of rpc function in JavaScript SDK.')); + } + + return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function (resp) { + return AV._decode(resp).result; + }); + }, + + /** + * Make a call to request server date time. + * @return {Promise.} A promise that will be resolved with the result + * of the function. + * @since 0.5.9 + */ + getServerDate: function getServerDate() { + var request = AVRequest("date", null, null, 'GET'); + + return request.then(function (resp) { + return AV._decode(resp); + }); + }, + + /** + * Makes a call to request a sms code for operation verification. + * @param {Object} data The mobile phone number string or a JSON + * object that contains mobilePhoneNumber,template,op,ttl,name etc. + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + requestSmsCode: function requestSmsCode(data) { + if (_.isString(data)) { + data = { mobilePhoneNumber: data }; + } + if (!data.mobilePhoneNumber) { + throw new Error('Missing mobilePhoneNumber.'); + } + var request = AVRequest("requestSmsCode", null, null, 'POST', data); + return request; + }, + + /** + * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode + * @param {String} code The sms code sent by AV.Cloud.requestSmsCode + * @param {phone} phone The mobile phoner number(optional). + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + verifySmsCode: function verifySmsCode(code, phone) { + if (!code) throw new Error('Missing sms code.'); + var params = {}; + if (_.isString(phone)) { + params['mobilePhoneNumber'] = phone; + } + + var request = AVRequest("verifySmsCode", code, null, 'POST', params); + return request; + } + }); +}; + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + var eventSplitter = /\s+/; + var slice = Array.prototype.slice; + + /** + * @class + * + *

AV.Events is a fork of Backbone's Events module, provided for your + * convenience.

+ * + *

A module that can be mixed in to any object in order to provide + * it with custom events. You may bind callback functions to an event + * with `on`, or remove these functions with `off`. + * Triggering an event fires all callbacks in the order that `on` was + * called. + * + * @private + * @example + * var object = {}; + * _.extend(object, AV.Events); + * object.on('expand', function(){ alert('expanded'); }); + * object.trigger('expand');

+ * + */ + AV.Events = { + /** + * Bind one or more space separated events, `events`, to a `callback` + * function. Passing `"all"` will bind the callback to all events fired. + */ + on: function on(events, callback, context) { + + var calls, event, node, tail, list; + if (!callback) { + return this; + } + events = events.split(eventSplitter); + calls = this._callbacks || (this._callbacks = {}); + + // Create an immutable callback list, allowing traversal during + // modification. The tail is an empty object that will always be used + // as the next node. + event = events.shift(); + while (event) { + list = calls[event]; + node = list ? list.tail : {}; + node.next = tail = {}; + node.context = context; + node.callback = callback; + calls[event] = { tail: tail, next: list ? list.next : node }; + event = events.shift(); + } + + return this; + }, + + /** + * Remove one or many callbacks. If `context` is null, removes all callbacks + * with that function. If `callback` is null, removes all callbacks for the + * event. If `events` is null, removes all bound callbacks for all events. + */ + off: function off(events, callback, context) { + var event, calls, node, tail, cb, ctx; + + // No events, or removing *all* events. + if (!(calls = this._callbacks)) { + return; + } + if (!(events || callback || context)) { + delete this._callbacks; + return this; + } + + // Loop through the listed events and contexts, splicing them out of the + // linked list of callbacks if appropriate. + events = events ? events.split(eventSplitter) : _.keys(calls); + event = events.shift(); + while (event) { + node = calls[event]; + delete calls[event]; + if (!node || !(callback || context)) { + continue; + } + // Create a new list, omitting the indicated callbacks. + tail = node.tail; + node = node.next; + while (node !== tail) { + cb = node.callback; + ctx = node.context; + if (callback && cb !== callback || context && ctx !== context) { + this.on(event, cb, ctx); + } + node = node.next; + } + event = events.shift(); + } + + return this; + }, + + /** + * Trigger one or many events, firing all bound callbacks. Callbacks are + * passed the same arguments as `trigger` is, apart from the event name + * (unless you're listening on `"all"`, which will cause your callback to + * receive the true name of the event as the first argument). + */ + trigger: function trigger(events) { + var event, node, calls, tail, args, all, rest; + if (!(calls = this._callbacks)) { + return this; + } + all = calls.all; + events = events.split(eventSplitter); + rest = slice.call(arguments, 1); + + // For each event, walk through the linked list of callbacks twice, + // first to trigger the event, then to trigger any `"all"` callbacks. + event = events.shift(); + while (event) { + node = calls[event]; + if (node) { + tail = node.tail; + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, rest); + } + } + node = all; + if (node) { + tail = node.tail; + args = [event].concat(rest); + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, args); + } + } + event = events.shift(); + } + + return this; + } + }; + + /** + * @function + */ + AV.Events.bind = AV.Events.on; + + /** + * @function + */ + AV.Events.unbind = AV.Events.off; +}; + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var cos = __webpack_require__(33); +var qiniu = __webpack_require__(34); +var s3 = __webpack_require__(35); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var Promise = __webpack_require__(1); + +var _require = __webpack_require__(4), + tap = _require.tap; + +var debug = __webpack_require__(5)('leancloud:file'); +var parseBase64 = __webpack_require__(37); + +module.exports = function (AV) { + + // 挂载一些配置 + var avConfig = AV._config; + + var hexOctet = function hexOctet() { + return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + }; + + // port from browserify path module + // since react-native packager won't shim node modules. + var extname = function extname(path) { + return path.match(/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/)[4]; + }; + + var b64Digit = function b64Digit(number) { + if (number < 26) { + return String.fromCharCode(65 + number); + } + if (number < 52) { + return String.fromCharCode(97 + (number - 26)); + } + if (number < 62) { + return String.fromCharCode(48 + (number - 52)); + } + if (number === 62) { + return '+'; + } + if (number === 63) { + return '/'; + } + throw new Error('Tried to encode large digit ' + number + ' in base64.'); + }; + + var encodeBase64 = function encodeBase64(array) { + var chunks = []; + chunks.length = Math.ceil(array.length / 3); + _.times(chunks.length, function (i) { + var b1 = array[i * 3]; + var b2 = array[i * 3 + 1] || 0; + var b3 = array[i * 3 + 2] || 0; + + var has2 = i * 3 + 1 < array.length; + var has3 = i * 3 + 2 < array.length; + + chunks[i] = [b64Digit(b1 >> 2 & 0x3F), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0F), has2 ? b64Digit(b2 << 2 & 0x3C | b3 >> 6 & 0x03) : "=", has3 ? b64Digit(b3 & 0x3F) : "="].join(""); + }); + return chunks.join(""); + }; + + /** + * An AV.File is a local representation of a file that is saved to the AV + * cloud. + * @param name {String} The file's name. This will change to a unique value + * once the file has finished saving. + * @param data {Array} The data for the file, as either: + * 1. an Array of byte value Numbers, or + * 2. an Object like { base64: "..." } with a base64-encoded String. + * 3. a File object selected with a file upload control. (3) only works + * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+. + * 4.a Buffer object in Node.js runtime. + * + * For example:
+   * var fileUploadControl = $("#profilePhotoFileUpload")[0];
+   * if (fileUploadControl.files.length > 0) {
+   *   var file = fileUploadControl.files[0];
+   *   var name = "photo.jpg";
+   *   var file = new AV.File(name, file);
+   *   file.save().then(function() {
+   *     // The file has been saved to AV.
+   *   }, function(error) {
+   *     // The file either could not be read, or could not be saved to AV.
+   *   });
+   * }
+ * + * @class + * @param [mimeType] {String} Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + */ + AV.File = function (name, data, mimeType) { + + this.attributes = { + name: name, + url: '', + metaData: {}, + // 用来存储转换后要上传的 base64 String + base64: '' + }; + + if (_.isString(data)) { + throw new TypeError("Creating an AV.File from a String is not yet supported."); + } + if (_.isArray(data)) { + this.attributes.metaData.size = data.length; + data = { base64: encodeBase64(data) }; + } + + this._extName = ''; + this._data = data; + + var owner = void 0; + if (data && data.owner) { + owner = data.owner; + } else if (!AV._config.disableCurrentUser) { + try { + owner = AV.User.current(); + } catch (error) { + if ('SYNC_API_NOT_AVAILABLE' === error.code) { + console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().'); + } else { + throw error; + } + } + } + + this.attributes.metaData.owner = owner ? owner.id : 'unknown'; + + this.set('mime_type', mimeType); + }; + + /** + * Creates a fresh AV.File object with exists url for saving to AVOS Cloud. + * @param {String} name the file name + * @param {String} url the file url. + * @param {Object} [metaData] the file metadata object. + * @param {String} [type] Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + * @return {AV.File} the file object + */ + AV.File.withURL = function (name, url, metaData, type) { + if (!name || !url) { + throw new Error("Please provide file name and url"); + } + var file = new AV.File(name, null, type); + //copy metaData properties to file. + if (metaData) { + for (var prop in metaData) { + if (!file.attributes.metaData[prop]) file.attributes.metaData[prop] = metaData[prop]; + } + } + file.attributes.url = url; + //Mark the file is from external source. + file.attributes.metaData.__source = 'external'; + return file; + }; + + /** + * Creates a file object with exists objectId. + * @param {String} objectId The objectId string + * @return {AV.File} the file object + */ + AV.File.createWithoutData = function (objectId) { + var file = new AV.File(); + file.id = objectId; + return file; + }; + + AV.File.prototype = { + className: '_File', + + _toFullJSON: function _toFullJSON(seenObjects) { + var _this = this; + + var json = _.clone(this.attributes); + AV._objectEach(json, function (val, key) { + json[key] = AV._encode(val, seenObjects); + }); + AV._objectEach(this._operations, function (val, key) { + json[key] = val; + }); + + if (_.has(this, "id")) { + json.objectId = this.id; + } + _(['createdAt', 'updatedAt']).each(function (key) { + if (_.has(_this, key)) { + var val = _this[key]; + json[key] = _.isDate(val) ? val.toJSON() : val; + } + }); + json.__type = "File"; + return json; + }, + toJSON: function toJSON() { + var json = this._toFullJSON(); + // add id and keep __type for backward compatible + if (_.has(this, 'id')) { + json.id = this.id; + } + return json; + }, + + + /** + * Returns the ACL for this file. + * @returns {AV.ACL} An instance of AV.ACL. + */ + getACL: function getACL() { + return this._acl; + }, + + /** + * Sets the ACL to be used for this file. + * @param {AV.ACL} acl An instance of AV.ACL. + */ + setACL: function setACL(acl) { + if (!(acl instanceof AV.ACL)) { + return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.'); + } + this._acl = acl; + }, + + /** + * Gets the name of the file. Before save is called, this is the filename + * given by the user. After save is called, that name gets prefixed with a + * unique identifier. + */ + name: function name() { + return this.get('name'); + }, + + /** + * Gets the url of the file. It is only available after you save the file or + * after you get the file from a AV.Object. + * @return {String} + */ + url: function url() { + return this.get('url'); + }, + + /** + * Gets the attributs of the file object. + * @param {String} The attribute name which want to get. + * @returns {Any} + */ + get: function get(attrName) { + switch (attrName) { + case 'objectId': + return this.id; + case 'url': + case 'name': + case 'mime_type': + case 'metaData': + case 'createdAt': + case 'updatedAt': + return this.attributes[attrName]; + default: + return this.attributes.metaData[attrName]; + } + }, + + /** + * Set the metaData of the file object. + * @param {Object} Object is an key value Object for setting metaData. + * @param {String} attr is an optional metadata key. + * @param {Object} value is an optional metadata value. + * @returns {String|Number|Array|Object} + */ + set: function set() { + var _this2 = this; + + var set = function set(attrName, value) { + switch (attrName) { + case 'name': + case 'url': + case 'mime_type': + case 'base64': + case 'metaData': + _this2.attributes[attrName] = value; + break; + default: + // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面 + _this2.attributes.metaData[attrName] = value; + break; + } + }; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + switch (args.length) { + case 1: + // 传入一个 Object + for (var k in args[0]) { + set(k, args[0][k]); + } + break; + case 2: + set(args[0], args[1]); + break; + } + }, + + /** + *

Returns the file's metadata JSON object if no arguments is given.Returns the + * metadata value if a key is given.Set metadata value if key and value are both given.

+ *

+    *  var metadata = file.metaData(); //Get metadata JSON object.
+    *  var size = file.metaData('size');  // Get the size metadata value.
+    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.
+    *

+ * @return {Object} The file's metadata JSON object. + * @param {String} attr an optional metadata key. + * @param {Object} value an optional metadata value. + **/ + metaData: function metaData(attr, value) { + if (attr && value) { + this.attributes.metaData[attr] = value; + return this; + } else if (attr && !value) { + return this.attributes.metaData[attr]; + } else { + return this.attributes.metaData; + } + }, + + /** + * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。 + * @return {String} 缩略图URL + * @param {Number} width 宽度,单位:像素 + * @param {Number} heigth 高度,单位:像素 + * @param {Number} quality 质量,1-100的数字,默认100 + * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。 + * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。 + */ + + thumbnailURL: function thumbnailURL(width, height, quality, scaleToFit, fmt) { + var url = this.attributes.url; + if (!url) { + throw new Error('Invalid url.'); + } + if (!width || !height || width <= 0 || height <= 0) { + throw new Error('Invalid width or height value.'); + } + quality = quality || 100; + scaleToFit = !scaleToFit ? true : scaleToFit; + if (quality <= 0 || quality > 100) { + throw new Error('Invalid quality value.'); + } + fmt = fmt || 'png'; + var mode = scaleToFit ? 2 : 1; + return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt; + }, + + /** + * Returns the file's size. + * @return {Number} The file's size in bytes. + **/ + size: function size() { + return this.metaData().size; + }, + + /** + * Returns the file's owner. + * @return {String} The file's owner id. + */ + ownerId: function ownerId() { + return this.metaData().owner; + }, + + /** + * Destroy the file. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + if (!this.id) { + return Promise.reject(new Error('The file id is not eixsts.')); + } + var request = AVRequest("files", null, this.id, 'DELETE', null, options); + return request; + }, + + /** + * Request Qiniu upload token + * @param {string} type + * @return {Promise} Resolved with the response + * @private + */ + _fileToken: function _fileToken(type) { + var route = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'fileTokens'; + + var name = this.attributes.name; + + var extName = extname(name); + if (!extName && this._extName) { + name += this._extName; + extName = this._extName; + } + // Create 16-bits uuid as qiniu key. + var key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName; + var data = { + key: key, + name: name, + ACL: this._acl, + mime_type: type, + metaData: this.attributes.metaData + }; + this._qiniu_key = key; + return AVRequest(route, null, null, 'POST', data); + }, + + + /** + * @callback UploadProgressCallback + * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes + */ + /** + * Saves the file to the AV cloud. + * @param {Object} [options] + * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。 + * @return {Promise} Promise that is resolved when the save finishes. + */ + save: function save(options) { + var _this3 = this; + + if (this.id) { + throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.'); + } + if (!this._previousSave) { + if (this._data) { + var mimeType = this.get('mime_type'); + this._previousSave = this._fileToken(mimeType).then(function (uploadInfo) { + if (uploadInfo.mime_type) { + mimeType = uploadInfo.mime_type; + _this3.set('mime_type', mimeType); + } + _this3._token = uploadInfo.token; + return Promise.resolve().then(function () { + var data = _this3._data; + if (data && data.base64) { + return parseBase64(data.base64, mimeType); + } + if (data && data.blob) { + if (!data.blob.type && mimeType) { + data.blob.type = mimeType; + } + if (!data.blob.name) { + data.blob.name = _this3.get('name'); + } + if (false) { + _this3._extName = extname(data.blob.uri); + } + return data.blob; + } + if (typeof File !== "undefined" && data instanceof File) { + if (data.size) { + _this3.attributes.metaData.size = data.size; + } + if (data.name) { + _this3._extName = extname(data.name); + } + return data; + } + if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) { + _this3.attributes.metaData.size = data.length; + return data; + } + throw new TypeError('malformed file data'); + }).then(function (data) { + var uploadPromise = void 0; + switch (uploadInfo.provider) { + case 's3': + uploadPromise = s3(uploadInfo, data, _this3, options); + break; + case 'qcloud': + uploadPromise = cos(uploadInfo, data, _this3, options); + break; + case 'qiniu': + default: + uploadPromise = qiniu(uploadInfo, data, _this3, options); + break; + } + return uploadPromise.then(tap(function () { + return _this3._callback(true); + }), function (error) { + _this3._callback(false); + throw error; + }); + }); + }); + } else if (this.attributes.url && this.attributes.metaData.__source === 'external') { + // external link file. + var data = { + name: this.attributes.name, + ACL: this._acl, + metaData: this.attributes.metaData, + mime_type: this.mimeType, + url: this.attributes.url + }; + this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then(function (response) { + _this3.attributes.name = response.name; + _this3.attributes.url = response.url; + _this3.id = response.objectId; + if (response.size) { + _this3.attributes.metaData.size = response.size; + } + return _this3; + }); + } + } + return this._previousSave; + }, + _callback: function _callback(success) { + AVRequest('fileCallback', null, null, 'post', { + token: this._token, + result: success + }).catch(debug); + delete this._token; + delete this._data; + }, + + + /** + * fetch the file from server. If the server's representation of the + * model differs from its current attributes, they will be overriden, + * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option. + * @return {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch: function fetch(options) { + var options = null; + + var request = AVRequest('files', null, this.id, 'GET', options); + return request.then(this._finishFetch.bind(this)); + }, + _finishFetch: function _finishFetch(response) { + var value = AV.Object.prototype.parse(response); + value.attributes = { + name: value.name, + url: value.url, + mime_type: value.mime_type, + bucket: value.bucket + }; + value.attributes.metaData = value.metaData || {}; + value.id = value.objectId; + // clean + delete value.objectId; + delete value.metaData; + delete value.url; + delete value.name; + delete value.mime_type; + delete value.bucket; + _.extend(this, value); + return this; + } + }; +}; + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +/*global navigator: false */ +module.exports = function (AV) { + /** + * Creates a new GeoPoint with any of the following forms:
+ * @example + * new GeoPoint(otherGeoPoint) + * new GeoPoint(30, 30) + * new GeoPoint([30, 30]) + * new GeoPoint({latitude: 30, longitude: 30}) + * new GeoPoint() // defaults to (0, 0) + * @class + * + *

Represents a latitude / longitude point that may be associated + * with a key in a AVObject or used as a reference point for geo queries. + * This allows proximity-based queries on the key.

+ * + *

Only one key in a class may contain a GeoPoint.

+ * + *

Example:

+   *   var point = new AV.GeoPoint(30.0, -20.0);
+   *   var object = new AV.Object("PlaceObject");
+   *   object.set("location", point);
+   *   object.save();

+ */ + AV.GeoPoint = function (arg1, arg2) { + if (_.isArray(arg1)) { + AV.GeoPoint._validate(arg1[0], arg1[1]); + this.latitude = arg1[0]; + this.longitude = arg1[1]; + } else if (_.isObject(arg1)) { + AV.GeoPoint._validate(arg1.latitude, arg1.longitude); + this.latitude = arg1.latitude; + this.longitude = arg1.longitude; + } else if (_.isNumber(arg1) && _.isNumber(arg2)) { + AV.GeoPoint._validate(arg1, arg2); + this.latitude = arg1; + this.longitude = arg2; + } else { + this.latitude = 0; + this.longitude = 0; + } + + // Add properties so that anyone using Webkit or Mozilla will get an error + // if they try to set values that are out of bounds. + var self = this; + if (this.__defineGetter__ && this.__defineSetter__) { + // Use _latitude and _longitude to actually store the values, and add + // getters and setters for latitude and longitude. + this._latitude = this.latitude; + this._longitude = this.longitude; + this.__defineGetter__("latitude", function () { + return self._latitude; + }); + this.__defineGetter__("longitude", function () { + return self._longitude; + }); + this.__defineSetter__("latitude", function (val) { + AV.GeoPoint._validate(val, self.longitude); + self._latitude = val; + }); + this.__defineSetter__("longitude", function (val) { + AV.GeoPoint._validate(self.latitude, val); + self._longitude = val; + }); + } + }; + + /** + * @lends AV.GeoPoint.prototype + * @property {float} latitude North-south portion of the coordinate, in range + * [-90, 90]. Throws an exception if set out of range in a modern browser. + * @property {float} longitude East-west portion of the coordinate, in range + * [-180, 180]. Throws if set out of range in a modern browser. + */ + + /** + * Throws an exception if the given lat-long is out of bounds. + * @private + */ + AV.GeoPoint._validate = function (latitude, longitude) { + if (latitude < -90.0) { + throw new Error("AV.GeoPoint latitude " + latitude + " < -90.0."); + } + if (latitude > 90.0) { + throw new Error("AV.GeoPoint latitude " + latitude + " > 90.0."); + } + if (longitude < -180.0) { + throw new Error("AV.GeoPoint longitude " + longitude + " < -180.0."); + } + if (longitude > 180.0) { + throw new Error("AV.GeoPoint longitude " + longitude + " > 180.0."); + } + }; + + /** + * Creates a GeoPoint with the user's current location, if available. + * @return {Promise.} + */ + AV.GeoPoint.current = function () { + return new AV.Promise(function (resolve, reject) { + navigator.geolocation.getCurrentPosition(function (location) { + resolve(new AV.GeoPoint({ + latitude: location.coords.latitude, + longitude: location.coords.longitude + })); + }, reject); + }); + }; + + AV.GeoPoint.prototype = { + /** + * Returns a JSON representation of the GeoPoint, suitable for AV. + * @return {Object} + */ + toJSON: function toJSON() { + AV.GeoPoint._validate(this.latitude, this.longitude); + return { + "__type": "GeoPoint", + latitude: this.latitude, + longitude: this.longitude + }; + }, + + /** + * Returns the distance from this GeoPoint to another in radians. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + radiansTo: function radiansTo(point) { + var d2r = Math.PI / 180.0; + var lat1rad = this.latitude * d2r; + var long1rad = this.longitude * d2r; + var lat2rad = point.latitude * d2r; + var long2rad = point.longitude * d2r; + var deltaLat = lat1rad - lat2rad; + var deltaLong = long1rad - long2rad; + var sinDeltaLatDiv2 = Math.sin(deltaLat / 2); + var sinDeltaLongDiv2 = Math.sin(deltaLong / 2); + // Square of half the straight line chord distance between both points. + var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2; + a = Math.min(1.0, a); + return 2 * Math.asin(Math.sqrt(a)); + }, + + /** + * Returns the distance from this GeoPoint to another in kilometers. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + kilometersTo: function kilometersTo(point) { + return this.radiansTo(point) * 6371.0; + }, + + /** + * Returns the distance from this GeoPoint to another in miles. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + milesTo: function milesTo(point) { + return this.radiansTo(point) * 3958.8; + } + }; +}; + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var AV = __webpack_require__(6); +var request = __webpack_require__(2); + +var initialize = function initialize(appId, appKey, masterKey, hookKey) { + if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) { + console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.'); + } + AV.applicationId = appId; + AV.applicationKey = appKey; + AV.masterKey = masterKey; + if (false) { + AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY; + } + AV._useMasterKey = false; +}; + +var masterKeyWarn = function masterKeyWarn() { + console.warn('MasterKey is not supposed to be used in browser.'); +}; + +/** + * Call this method first to set up your authentication tokens for AV. + * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn . + * @function AV.init + * @param {Object} options + * @param {String} options.appId application id + * @param {String} options.appKey application key + * @param {String} options.masterKey application master key +*/ + +AV.init = function () { + if (arguments.length === 1) { + var options = arguments.length <= 0 ? undefined : arguments[0]; + if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { + if ("Browser" && options.masterKey) { + masterKeyWarn(); + } + initialize(options.appId, options.appKey, options.masterKey, options.hookKey); + request.setServerUrlByRegion(options.region); + } else { + throw new Error('AV.init(): Parameter is not correct.'); + } + } else { + // 兼容旧版本的初始化方法 + if ("Browser" && (arguments.length <= 3 ? undefined : arguments[3])) { + masterKeyWarn(); + } + initialize.apply(undefined, arguments); + request.setServerUrlByRegion('cn'); + } +}; + +// If we're running in node.js, allow using the master key. +if (false) { + AV.Cloud = AV.Cloud || {}; + /** + * Switches the LeanCloud SDK to using the Master key. The Master key grants + * priveleged access to the data in LeanCloud and can be used to bypass ACLs and + * other restrictions that are applied to the client SDKs. + *

Available in Cloud Code and Node.js only. + *

+ */ + AV.Cloud.useMasterKey = function () { + AV._useMasterKey = true; + }; +} + +// 兼容老版本的初始化方法 +AV.initialize = AV.init; + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * 包含了使用了 LeanCloud + * 离线数据分析功能的函数。 + *

+ * 仅在云引擎运行环境下有效。 + *

+ * @namespace + */ + AV.Insight = AV.Insight || {}; + + _.extend(AV.Insight, /** @lends AV.Insight */{ + + /** + * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用 + * AV.Insight.JobQuery 查询任务状态和结果。 + * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
+     *                   { "sql" : "select count(*) as c,gender from _User group by gender",
+     *                     "saveAs": {
+     *                         "className" : "UserGender",
+     *                         "limit": 1
+     *                      }
+     *                   }
+     *                  
+ * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。 + * @param {AuthOptions} [options] + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + startJob: function startJob(jobConfig, options) { + if (!jobConfig || !jobConfig.sql) { + throw new Error('Please provide the sql to run the job.'); + } + var data = { + jobConfig: jobConfig, + appId: AV.applicationId + }; + var request = AVRequest("bigquery", 'jobs', null, 'POST', AV._encode(data, null, true), options); + + return request.then(function (resp) { + return AV._decode(resp).id; + }); + }, + + /** + * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。 + *

+ * 仅在云引擎运行环境下有效。 + *

+ * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成 + * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息, + * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。 + * + */ + on: function on(event, cb) {} + }); + + /** + * 创建一个对象,用于查询 Insight 任务状态和结果。 + * @class + * @param {String} id 任务 id + * @since 0.5.5 + */ + AV.Insight.JobQuery = function (id, className) { + if (!id) { + throw new Error('Please provide the job id.'); + } + this.id = id; + this.className = className; + this._skip = 0; + this._limit = 100; + }; + + AV.Insight.JobQuery.prototype = { + + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * @param {Number} n the number of results to skip. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + skip: function skip(n) { + this._skip = n; + return this; + }, + + /** + * Sets the limit of the number of results to return. The default limit is + * 100, with a maximum of 1000 results being returned at a time. + * @param {Number} n the number of results to limit to. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + limit: function limit(n) { + this._limit = n; + return this; + }, + + /** + * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数, + * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间 + * startTime、endTime 等信息。 + * + * @param {AuthOptions} [options] + * @return {Promise} A promise that will be resolved with the result + * of the function. + * + */ + find: function find(options) { + var params = { + skip: this._skip, + limit: this._limit + }; + + var request = AVRequest("bigquery", 'jobs', this.id, "GET", params, options); + var self = this; + return request.then(function (response) { + if (response.error) { + return AV.Promise.reject(new AVError(response.code, response.error)); + } + return AV.Promise.resolve(response); + }); + } + + }; +}; + +/***/ }), +/* 21 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var utils = __webpack_require__(4); + +var RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt']; +var checkReservedKey = function checkReservedKey(key) { + if (RESERVED_KEYS.indexOf(key) !== -1) { + throw new Error('key[' + key + '] is reserved'); + } +}; + +// AV.Object is analogous to the Java AVObject. +// It also implements the same interface as a Backbone model. + +module.exports = function (AV) { + /** + * Creates a new model with defined attributes. A client id (cid) is + * automatically generated and assigned for you. + * + *

You won't normally call this method directly. It is recommended that + * you use a subclass of AV.Object instead, created by calling + * extend.

+ * + *

However, if you don't want to use a subclass, or aren't sure which + * subclass is appropriate, you can use this form:

+   *     var object = new AV.Object("ClassName");
+   * 
+ * That is basically equivalent to:
+   *     var MyClass = AV.Object.extend("ClassName");
+   *     var object = new MyClass();
+   * 

+ * + * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @see AV.Object.extend + * + * @class + * + *

The fundamental unit of AV data, which implements the Backbone Model + * interface.

+ */ + AV.Object = function (attributes, options) { + // Allow new AV.Object("ClassName") as a shortcut to _create. + if (_.isString(attributes)) { + return AV.Object._create.apply(this, arguments); + } + + attributes = attributes || {}; + if (options && options.parse) { + attributes = this.parse(attributes); + attributes = this._mergeMagicFields(attributes); + } + var defaults = AV._getValue(this, 'defaults'); + if (defaults) { + attributes = _.extend({}, defaults, attributes); + } + if (options && options.collection) { + this.collection = options.collection; + } + + this._serverData = {}; // The last known data for this object from cloud. + this._opSetQueue = [{}]; // List of sets of changes to the data. + this._flags = {}; + this.attributes = {}; // The best estimate of this's current data. + + this._hashedJSON = {}; // Hash of values of containers at last save. + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this.set(attributes, { silent: true }); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this._hasData = true; + this._previousAttributes = _.clone(this.attributes); + this.initialize.apply(this, arguments); + }; + + /** + * @lends AV.Object.prototype + * @property {String} id The objectId of the AV Object. + */ + + /** + * Saves the given list of AV.Object. + * If any error is encountered, stops and calls the error handler. + * + *
+   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {
+   *     // All the objects were saved.
+   *   }, function(error) {
+   *     // An error occurred while saving one of the objects.
+   *   });
+   *
+   * @param {Array} list A list of AV.Object.
+   */
+  AV.Object.saveAll = function (list, options) {
+    return AV.Object._deepSaveAsync(list, null, options);
+  };
+
+  /**
+   * Fetch the given list of AV.Object.
+   *
+   * @param {AV.Object[]} objects A list of AV.Object
+   * @param {AuthOptions} options
+   * @return {Promise.} The given list of AV.Object, updated
+   */
+
+  AV.Object.fetchAll = function (objects, options) {
+    return AV.Promise.resolve().then(function () {
+      return AVRequest('batch', null, null, 'POST', {
+        requests: _.map(objects, function (object) {
+          if (!object.className) throw new Error('object must have className to fetch');
+          if (!object.id) throw new Error('object must have id to fetch');
+          if (object.dirty()) throw new Error('object is modified but not saved');
+          return {
+            method: 'GET',
+            path: '/1.1/classes/' + object.className + '/' + object.id
+          };
+        })
+      }, options);
+    }).then(function (response) {
+      _.forEach(objects, function (object, i) {
+        if (response[i].success) {
+          object._finishFetch(object.parse(response[i].success));
+        } else {
+          var error = new Error(response[i].error.error);
+          error.code = response[i].error.code;
+          throw error;
+        }
+      });
+      return objects;
+    });
+  };
+
+  // Attach all inheritable methods to the AV.Object prototype.
+  _.extend(AV.Object.prototype, AV.Events,
+  /** @lends AV.Object.prototype */{
+    _fetchWhenSave: false,
+
+    /**
+     * Initialize is an empty function by default. Override it with your own
+     * initialization logic.
+     */
+    initialize: function initialize() {},
+
+    /**
+      * Set whether to enable fetchWhenSave option when updating object.
+      * When set true, SDK would fetch the latest object after saving.
+      * Default is false.
+      *
+      * @deprecated use AV.Object#save with options.fetchWhenSave instead
+      * @param {boolean} enable  true to enable fetchWhenSave option.
+      */
+    fetchWhenSave: function fetchWhenSave(enable) {
+      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');
+      if (!_.isBoolean(enable)) {
+        throw new Error('Expect boolean value for fetchWhenSave');
+      }
+      this._fetchWhenSave = enable;
+    },
+
+    /**
+     * Returns the object's objectId.
+     * @return {String} the objectId.
+     */
+    getObjectId: function getObjectId() {
+      return this.id;
+    },
+
+    /**
+     * Returns the object's createdAt attribute.
+     * @return {Date}
+     */
+    getCreatedAt: function getCreatedAt() {
+      return this.createdAt || this.get('createdAt');
+    },
+
+    /**
+     * Returns the object's updatedAt attribute.
+     * @return {Date}
+     */
+    getUpdatedAt: function getUpdatedAt() {
+      return this.updatedAt || this.get('updatedAt');
+    },
+
+    /**
+     * Returns a JSON version of the object suitable for saving to AV.
+     * @return {Object}
+     */
+    toJSON: function toJSON() {
+      var json = this._toFullJSON();
+      AV._arrayEach(["__type", "className"], function (key) {
+        delete json[key];
+      });
+      return json;
+    },
+
+    _toFullJSON: function _toFullJSON(seenObjects) {
+      var _this = this;
+
+      var json = _.clone(this.attributes);
+      AV._objectEach(json, function (val, key) {
+        json[key] = AV._encode(val, seenObjects);
+      });
+      AV._objectEach(this._operations, function (val, key) {
+        json[key] = val;
+      });
+
+      if (_.has(this, "id")) {
+        json.objectId = this.id;
+      }
+      _(['createdAt', 'updatedAt']).each(function (key) {
+        if (_.has(_this, key)) {
+          var val = _this[key];
+          json[key] = _.isDate(val) ? val.toJSON() : val;
+        }
+      });
+      json.__type = "Object";
+      json.className = this.className;
+      return json;
+    },
+
+    /**
+     * Updates _hashedJSON to reflect the current state of this object.
+     * Adds any changed hash values to the set of pending changes.
+     * @private
+     */
+    _refreshCache: function _refreshCache() {
+      var self = this;
+      if (self._refreshingCache) {
+        return;
+      }
+      self._refreshingCache = true;
+      AV._objectEach(this.attributes, function (value, key) {
+        if (value instanceof AV.Object) {
+          value._refreshCache();
+        } else if (_.isObject(value)) {
+          if (self._resetCacheForKey(key)) {
+            self.set(key, new AV.Op.Set(value), { silent: true });
+          }
+        }
+      });
+      delete self._refreshingCache;
+    },
+
+    /**
+     * Returns true if this object has been modified since its last
+     * save/refresh.  If an attribute is specified, it returns true only if that
+     * particular attribute has been modified since the last save/refresh.
+     * @param {String} attr An attribute name (optional).
+     * @return {Boolean}
+     */
+    dirty: function dirty(attr) {
+      this._refreshCache();
+
+      var currentChanges = _.last(this._opSetQueue);
+
+      if (attr) {
+        return currentChanges[attr] ? true : false;
+      }
+      if (!this.id) {
+        return true;
+      }
+      if (_.keys(currentChanges).length > 0) {
+        return true;
+      }
+      return false;
+    },
+
+    /**
+     * Gets a Pointer referencing this Object.
+     * @private
+     */
+    _toPointer: function _toPointer() {
+      // if (!this.id) {
+      //   throw new Error("Can't serialize an unsaved AV.Object");
+      // }
+      return { __type: "Pointer",
+        className: this.className,
+        objectId: this.id };
+    },
+
+    /**
+     * Gets the value of an attribute.
+     * @param {String} attr The string name of an attribute.
+     */
+    get: function get(attr) {
+      switch (attr) {
+        case 'objectId':
+          return this.id;
+        case 'createdAt':
+        case 'updatedAt':
+          return this[attr];
+        default:
+          return this.attributes[attr];
+      }
+    },
+
+    /**
+     * Gets a relation on the given class for the attribute.
+     * @param {String} attr The attribute to get the relation for.
+     * @return {AV.Relation}
+     */
+    relation: function relation(attr) {
+      var value = this.get(attr);
+      if (value) {
+        if (!(value instanceof AV.Relation)) {
+          throw new Error("Called relation() on non-relation field " + attr);
+        }
+        value._ensureParentAndKey(this, attr);
+        return value;
+      } else {
+        return new AV.Relation(this, attr);
+      }
+    },
+
+    /**
+     * Gets the HTML-escaped value of an attribute.
+     */
+    escape: function escape(attr) {
+      var html = this._escapedAttributes[attr];
+      if (html) {
+        return html;
+      }
+      var val = this.attributes[attr];
+      var escaped;
+      if (utils.isNullOrUndefined(val)) {
+        escaped = '';
+      } else {
+        escaped = _.escape(val.toString());
+      }
+      this._escapedAttributes[attr] = escaped;
+      return escaped;
+    },
+
+    /**
+     * Returns true if the attribute contains a value that is not
+     * null or undefined.
+     * @param {String} attr The string name of the attribute.
+     * @return {Boolean}
+     */
+    has: function has(attr) {
+      return !utils.isNullOrUndefined(this.attributes[attr]);
+    },
+
+    /**
+     * Pulls "special" fields like objectId, createdAt, etc. out of attrs
+     * and puts them on "this" directly.  Removes them from attrs.
+     * @param attrs - A dictionary with the data for this AV.Object.
+     * @private
+     */
+    _mergeMagicFields: function _mergeMagicFields(attrs) {
+      // Check for changes of magic fields.
+      var model = this;
+      var specialFields = ["objectId", "createdAt", "updatedAt"];
+      AV._arrayEach(specialFields, function (attr) {
+        if (attrs[attr]) {
+          if (attr === "objectId") {
+            model.id = attrs[attr];
+          } else if ((attr === "createdAt" || attr === "updatedAt") && !_.isDate(attrs[attr])) {
+            model[attr] = AV._parseDate(attrs[attr]);
+          } else {
+            model[attr] = attrs[attr];
+          }
+          delete attrs[attr];
+        }
+      });
+      return attrs;
+    },
+
+    /**
+     * Returns the json to be sent to the server.
+     * @private
+     */
+    _startSave: function _startSave() {
+      this._opSetQueue.push({});
+    },
+
+    /**
+     * Called when a save fails because of an error. Any changes that were part
+     * of the save need to be merged with changes made after the save. This
+     * might throw an exception is you do conflicting operations. For example,
+     * if you do:
+     *   object.set("foo", "bar");
+     *   object.set("invalid field name", "baz");
+     *   object.save();
+     *   object.increment("foo");
+     * then this will throw when the save fails and the client tries to merge
+     * "bar" with the +1.
+     * @private
+     */
+    _cancelSave: function _cancelSave() {
+      var self = this;
+      var failedChanges = _.first(this._opSetQueue);
+      this._opSetQueue = _.rest(this._opSetQueue);
+      var nextChanges = _.first(this._opSetQueue);
+      AV._objectEach(failedChanges, function (op, key) {
+        var op1 = failedChanges[key];
+        var op2 = nextChanges[key];
+        if (op1 && op2) {
+          nextChanges[key] = op2._mergeWithPrevious(op1);
+        } else if (op1) {
+          nextChanges[key] = op1;
+        }
+      });
+      this._saving = this._saving - 1;
+    },
+
+    /**
+     * Called when a save completes successfully. This merges the changes that
+     * were saved into the known server data, and overrides it with any data
+     * sent directly from the server.
+     * @private
+     */
+    _finishSave: function _finishSave(serverData) {
+      // Grab a copy of any object referenced by this object. These instances
+      // may have already been fetched, and we don't want to lose their data.
+      // Note that doing it like this means we will unify separate copies of the
+      // same object, but that's a risk we have to take.
+      var fetchedObjects = {};
+      AV._traverse(this.attributes, function (object) {
+        if (object instanceof AV.Object && object.id && object._hasData) {
+          fetchedObjects[object.id] = object;
+        }
+      });
+
+      var savedChanges = _.first(this._opSetQueue);
+      this._opSetQueue = _.rest(this._opSetQueue);
+      this._applyOpSet(savedChanges, this._serverData);
+      this._mergeMagicFields(serverData);
+      var self = this;
+      AV._objectEach(serverData, function (value, key) {
+        self._serverData[key] = AV._decode(value, key);
+
+        // Look for any objects that might have become unfetched and fix them
+        // by replacing their values with the previously observed values.
+        var fetched = AV._traverse(self._serverData[key], function (object) {
+          if (object instanceof AV.Object && fetchedObjects[object.id]) {
+            return fetchedObjects[object.id];
+          }
+        });
+        if (fetched) {
+          self._serverData[key] = fetched;
+        }
+      });
+      this._rebuildAllEstimatedData();
+      this._saving = this._saving - 1;
+    },
+
+    /**
+     * Called when a fetch or login is complete to set the known server data to
+     * the given object.
+     * @private
+     */
+    _finishFetch: function _finishFetch(serverData, hasData) {
+      // Clear out any changes the user might have made previously.
+      this._opSetQueue = [{}];
+
+      // Bring in all the new server data.
+      this._mergeMagicFields(serverData);
+      var self = this;
+      AV._objectEach(serverData, function (value, key) {
+        self._serverData[key] = AV._decode(value, key);
+      });
+
+      // Refresh the attributes.
+      this._rebuildAllEstimatedData();
+
+      // Clear out the cache of mutable containers.
+      this._refreshCache();
+      this._opSetQueue = [{}];
+
+      this._hasData = hasData;
+    },
+
+    /**
+     * Applies the set of AV.Op in opSet to the object target.
+     * @private
+     */
+    _applyOpSet: function _applyOpSet(opSet, target) {
+      var self = this;
+      AV._objectEach(opSet, function (change, key) {
+        target[key] = change._estimate(target[key], self, key);
+        if (target[key] === AV.Op._UNSET) {
+          delete target[key];
+        }
+      });
+    },
+
+    /**
+     * Replaces the cached value for key with the current value.
+     * Returns true if the new value is different than the old value.
+     * @private
+     */
+    _resetCacheForKey: function _resetCacheForKey(key) {
+      var value = this.attributes[key];
+      if (_.isObject(value) && !(value instanceof AV.Object) && !(value instanceof AV.File)) {
+
+        value = value.toJSON ? value.toJSON() : value;
+        var json = JSON.stringify(value);
+        if (this._hashedJSON[key] !== json) {
+          var wasSet = !!this._hashedJSON[key];
+          this._hashedJSON[key] = json;
+          return wasSet;
+        }
+      }
+      return false;
+    },
+
+    /**
+     * Populates attributes[key] by starting with the last known data from the
+     * server, and applying all of the local changes that have been made to that
+     * key since then.
+     * @private
+     */
+    _rebuildEstimatedDataForKey: function _rebuildEstimatedDataForKey(key) {
+      var self = this;
+      delete this.attributes[key];
+      if (this._serverData[key]) {
+        this.attributes[key] = this._serverData[key];
+      }
+      AV._arrayEach(this._opSetQueue, function (opSet) {
+        var op = opSet[key];
+        if (op) {
+          self.attributes[key] = op._estimate(self.attributes[key], self, key);
+          if (self.attributes[key] === AV.Op._UNSET) {
+            delete self.attributes[key];
+          } else {
+            self._resetCacheForKey(key);
+          }
+        }
+      });
+    },
+
+    /**
+     * Populates attributes by starting with the last known data from the
+     * server, and applying all of the local changes that have been made since
+     * then.
+     * @private
+     */
+    _rebuildAllEstimatedData: function _rebuildAllEstimatedData() {
+      var self = this;
+
+      var previousAttributes = _.clone(this.attributes);
+
+      this.attributes = _.clone(this._serverData);
+      AV._arrayEach(this._opSetQueue, function (opSet) {
+        self._applyOpSet(opSet, self.attributes);
+        AV._objectEach(opSet, function (op, key) {
+          self._resetCacheForKey(key);
+        });
+      });
+
+      // Trigger change events for anything that changed because of the fetch.
+      AV._objectEach(previousAttributes, function (oldValue, key) {
+        if (self.attributes[key] !== oldValue) {
+          self.trigger('change:' + key, self, self.attributes[key], {});
+        }
+      });
+      AV._objectEach(this.attributes, function (newValue, key) {
+        if (!_.has(previousAttributes, key)) {
+          self.trigger('change:' + key, self, newValue, {});
+        }
+      });
+    },
+
+    /**
+     * Sets a hash of model attributes on the object, firing
+     * "change" unless you choose to silence it.
+     *
+     * 

You can call it with an object containing keys and values, or with one + * key and value. For example:

+     *   gameTurn.set({
+     *     player: player1,
+     *     diceRoll: 2
+     *   }, {
+     *     error: function(gameTurnAgain, error) {
+     *       // The set failed validation.
+     *     }
+     *   });
+     *
+     *   game.set("currentPlayer", player2, {
+     *     error: function(gameTurnAgain, error) {
+     *       // The set failed validation.
+     *     }
+     *   });
+     *
+     *   game.set("finished", true);

+ * + * @param {String} key The key to set. + * @param {Any} value The value to give it. + * @param {Object} [options] + * @param {Boolean} [options.silent] + * @return {AV.Object} self if succeeded, throws if the value is not valid. + * @see AV.Object#validate + */ + set: function set(key, value, options) { + var attrs; + if (_.isObject(key) || utils.isNullOrUndefined(key)) { + attrs = _.mapObject(key, function (v, k) { + checkReservedKey(k); + return AV._decode(v, k); + }); + options = value; + } else { + attrs = {}; + checkReservedKey(key); + attrs[key] = AV._decode(value, key); + } + + // Extract attributes and options. + options = options || {}; + if (!attrs) { + return this; + } + if (attrs instanceof AV.Object) { + attrs = attrs.attributes; + } + + // If the unset option is used, every attribute should be a Unset. + if (options.unset) { + AV._objectEach(attrs, function (unused_value, key) { + attrs[key] = new AV.Op.Unset(); + }); + } + + // Apply all the attributes to get the estimated values. + var dataToValidate = _.clone(attrs); + var self = this; + AV._objectEach(dataToValidate, function (value, key) { + if (value instanceof AV.Op) { + dataToValidate[key] = value._estimate(self.attributes[key], self, key); + if (dataToValidate[key] === AV.Op._UNSET) { + delete dataToValidate[key]; + } + } + }); + + // Run validation. + this._validate(attrs, options); + + options.changes = {}; + var escaped = this._escapedAttributes; + var prev = this._previousAttributes || {}; + + // Update attributes. + AV._arrayEach(_.keys(attrs), function (attr) { + var val = attrs[attr]; + + // If this is a relation object we need to set the parent correctly, + // since the location where it was parsed does not have access to + // this object. + if (val instanceof AV.Relation) { + val.parent = self; + } + + if (!(val instanceof AV.Op)) { + val = new AV.Op.Set(val); + } + + // See if this change will actually have any effect. + var isRealChange = true; + if (val instanceof AV.Op.Set && _.isEqual(self.attributes[attr], val.value)) { + isRealChange = false; + } + + if (isRealChange) { + delete escaped[attr]; + if (options.silent) { + self._silent[attr] = true; + } else { + options.changes[attr] = true; + } + } + + var currentChanges = _.last(self._opSetQueue); + currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]); + self._rebuildEstimatedDataForKey(attr); + + if (isRealChange) { + self.changed[attr] = self.attributes[attr]; + if (!options.silent) { + self._pending[attr] = true; + } + } else { + delete self.changed[attr]; + delete self._pending[attr]; + } + }); + + if (!options.silent) { + this.change(options); + } + return this; + }, + + /** + * Remove an attribute from the model, firing "change" unless + * you choose to silence it. This is a noop if the attribute doesn't + * exist. + */ + unset: function unset(attr, options) { + options = options || {}; + options.unset = true; + return this.set(attr, null, options); + }, + + /** + * Atomically increments the value of the given attribute the next time the + * object is saved. If no amount is specified, 1 is used by default. + * + * @param attr {String} The key. + * @param amount {Number} The amount to increment by. + */ + increment: function increment(attr, amount) { + if (_.isUndefined(amount) || _.isNull(amount)) { + amount = 1; + } + return this.set(attr, new AV.Op.Increment(amount)); + }, + + /** + * Atomically add an object to the end of the array associated with a given + * key. + * @param attr {String} The key. + * @param item {} The item to add. + */ + add: function add(attr, item) { + return this.set(attr, new AV.Op.Add(utils.ensureArray(item))); + }, + + /** + * Atomically add an object to the array associated with a given key, only + * if it is not already present in the array. The position of the insert is + * not guaranteed. + * + * @param attr {String} The key. + * @param item {} The object to add. + */ + addUnique: function addUnique(attr, item) { + return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item))); + }, + + /** + * Atomically remove all instances of an object from the array associated + * with a given key. + * + * @param attr {String} The key. + * @param item {} The object to remove. + */ + remove: function remove(attr, item) { + return this.set(attr, new AV.Op.Remove(utils.ensureArray(item))); + }, + + /** + * Returns an instance of a subclass of AV.Op describing what kind of + * modification has been performed on this field since the last time it was + * saved. For example, after calling object.increment("x"), calling + * object.op("x") would return an instance of AV.Op.Increment. + * + * @param attr {String} The key. + * @returns {AV.Op} The operation, or undefined if none. + */ + op: function op(attr) { + return _.last(this._opSetQueue)[attr]; + }, + + /** + * Clear all attributes on the model, firing "change" unless + * you choose to silence it. + */ + clear: function clear(options) { + options = options || {}; + options.unset = true; + var keysToClear = _.extend(this.attributes, this._operations); + return this.set(keysToClear, options); + }, + + /** + * Returns a JSON-encoded set of operations to be sent with the next save + * request. + * @private + */ + _getSaveJSON: function _getSaveJSON() { + var json = _.clone(_.first(this._opSetQueue)); + AV._objectEach(json, function (op, key) { + json[key] = op.toJSON(); + }); + return json; + }, + + /** + * Returns true if this object can be serialized for saving. + * @private + */ + _canBeSerialized: function _canBeSerialized() { + return AV.Object._canBeSerializedAsValue(this.attributes); + }, + + /** + * Fetch the model from the server. If the server's representation of the + * model differs from its current attributes, they will be overriden, + * triggering a "change" event. + * @param {Object} fetchOptions Optional options to set 'keys' and + * 'include' option. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch: function fetch() { + var fetchOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var options = arguments[1]; + + if (_.isArray(fetchOptions.keys)) { + fetchOptions.keys = fetchOptions.keys.join(','); + } + if (_.isArray(fetchOptions.include)) { + fetchOptions.include = fetchOptions.include.join(','); + } + + var self = this; + var request = AVRequest('classes', this.className, this.id, 'GET', fetchOptions, options); + return request.then(function (response) { + self._finishFetch(self.parse(response), true); + return self; + }); + }, + + /** + * Set a hash of model attributes, and save the model to the server. + * updatedAt will be updated when the request returns. + * You can either call it as:
+     *   object.save();
+ * or
+     *   object.save(null, options);
+ * or
+     *   object.save(attrs, options);
+ * or
+     *   object.save(key, value, options);
+ * + * For example,
+     *   gameTurn.save({
+     *     player: "Jake Cutter",
+     *     diceRoll: 2
+     *   }).then(function(gameTurnAgain) {
+     *     // The save was successful.
+     *   }, function(error) {
+     *     // The save failed.  Error is an instance of AVError.
+     *   });
+ * @param {AuthOptions} options AuthOptions plus: + * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded + * @param {AV.Query} options.query Save object only when it matches the query + * @return {AV.Promise} A promise that is fulfilled when the save + * completes. + * @see AVError + */ + save: function save(arg1, arg2, arg3) { + var i, attrs, current, options, saved; + if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) { + attrs = arg1; + options = arg2; + } else { + attrs = {}; + attrs[arg1] = arg2; + options = arg3; + } + + options = _.clone(options) || {}; + if (options.wait) { + current = _.clone(this.attributes); + } + + var setOptions = _.clone(options) || {}; + if (setOptions.wait) { + setOptions.silent = true; + } + if (attrs) { + this.set(attrs, setOptions); + } + + var model = this; + + // If there is any unsaved child, save it first. + model._refreshCache(); + + var unsavedChildren = []; + var unsavedFiles = []; + AV.Object._findUnsavedChildren(model.attributes, unsavedChildren, unsavedFiles); + if (unsavedChildren.length + unsavedFiles.length > 0) { + return AV.Object._deepSaveAsync(this.attributes, model, options).then(function () { + return model.save(null, options); + }); + } + + this._startSave(); + this._saving = (this._saving || 0) + 1; + + this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve(); + this._allPreviousSaves = this._allPreviousSaves.catch(function (e) {}).then(function () { + var method = model.id ? 'PUT' : 'POST'; + + var json = model._getSaveJSON(); + + if (model._fetchWhenSave) { + //Sepcial-case fetchWhenSave when updating object. + json._fetchWhenSave = true; + } + + if (options.fetchWhenSave) { + json._fetchWhenSave = true; + } + if (options.query) { + var queryJSON; + if (typeof options.query.toJSON === 'function') { + queryJSON = options.query.toJSON(); + if (queryJSON) { + json._where = queryJSON.where; + } + } + if (!json._where) { + var error = new Error('options.query is not an AV.Query'); + throw error; + } + } + + _.extend(json, model._flags); + + var route = "classes"; + var className = model.className; + if (model.className === "_User" && !model.id) { + // Special-case user sign-up. + route = "users"; + className = null; + } + //hook makeRequest in options. + var makeRequest = options._makeRequest || AVRequest; + var request = makeRequest(route, className, model.id, method, json, options); + + request = request.then(function (resp) { + var serverAttrs = model.parse(resp); + if (options.wait) { + serverAttrs = _.extend(attrs || {}, serverAttrs); + } + model._finishSave(serverAttrs); + if (options.wait) { + model.set(current, setOptions); + } + return model; + }, function (error) { + model._cancelSave(); + throw error; + }); + + return request; + }); + return this._allPreviousSaves; + }, + + /** + * Destroy this model on the server if it was already persisted. + * Optimistically removes the model from its collection, if it has one. + * @param {AuthOptions} options AuthOptions plus: + * @param {Boolean} [options.wait] wait for the server to respond + * before removal. + * + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + options = options || {}; + var model = this; + + var triggerDestroy = function triggerDestroy() { + model.trigger('destroy', model, model.collection, options); + }; + + if (!this.id) { + return triggerDestroy(); + } + + if (!options.wait) { + triggerDestroy(); + } + + var request = AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options); + return request.then(function () { + if (options.wait) { + triggerDestroy(); + } + return model; + }); + }, + + /** + * Converts a response into the hash of attributes to be set on the model. + * @ignore + */ + parse: function parse(resp) { + var output = _.clone(resp); + _(["createdAt", "updatedAt"]).each(function (key) { + if (output[key]) { + output[key] = AV._parseDate(output[key]); + } + }); + if (!output.updatedAt) { + output.updatedAt = output.createdAt; + } + return output; + }, + + /** + * Creates a new model with identical attributes to this one. + * @return {AV.Object} + */ + clone: function clone() { + return new this.constructor(this.attributes); + }, + + /** + * Returns true if this object has never been saved to AV. + * @return {Boolean} + */ + isNew: function isNew() { + return !this.id; + }, + + /** + * Call this method to manually fire a `"change"` event for this model and + * a `"change:attribute"` event for each changed attribute. + * Calling this will cause all objects observing the model to update. + */ + change: function change(options) { + options = options || {}; + var changing = this._changing; + this._changing = true; + + // Silent changes become pending changes. + var self = this; + AV._objectEach(this._silent, function (attr) { + self._pending[attr] = true; + }); + + // Silent changes are triggered. + var changes = _.extend({}, options.changes, this._silent); + this._silent = {}; + AV._objectEach(changes, function (unused_value, attr) { + self.trigger('change:' + attr, self, self.get(attr), options); + }); + if (changing) { + return this; + } + + // This is to get around lint not letting us make a function in a loop. + var deleteChanged = function deleteChanged(value, attr) { + if (!self._pending[attr] && !self._silent[attr]) { + delete self.changed[attr]; + } + }; + + // Continue firing `"change"` events while there are pending changes. + while (!_.isEmpty(this._pending)) { + this._pending = {}; + this.trigger('change', this, options); + // Pending and silent changes still remain. + AV._objectEach(this.changed, deleteChanged); + self._previousAttributes = _.clone(this.attributes); + } + + this._changing = false; + return this; + }, + + /** + * Determine if the model has changed since the last "change" + * event. If you specify an attribute name, determine if that attribute + * has changed. + * @param {String} attr Optional attribute name + * @return {Boolean} + */ + hasChanged: function hasChanged(attr) { + if (!arguments.length) { + return !_.isEmpty(this.changed); + } + return this.changed && _.has(this.changed, attr); + }, + + /** + * Returns an object containing all the attributes that have changed, or + * false if there are no changed attributes. Useful for determining what + * parts of a view need to be updated and/or what attributes need to be + * persisted to the server. Unset attributes will be set to undefined. + * You can also pass an attributes object to diff against the model, + * determining if there *would be* a change. + */ + changedAttributes: function changedAttributes(diff) { + if (!diff) { + return this.hasChanged() ? _.clone(this.changed) : false; + } + var changed = {}; + var old = this._previousAttributes; + AV._objectEach(diff, function (diffVal, attr) { + if (!_.isEqual(old[attr], diffVal)) { + changed[attr] = diffVal; + } + }); + return changed; + }, + + /** + * Gets the previous value of an attribute, recorded at the time the last + * "change" event was fired. + * @param {String} attr Name of the attribute to get. + */ + previous: function previous(attr) { + if (!arguments.length || !this._previousAttributes) { + return null; + } + return this._previousAttributes[attr]; + }, + + /** + * Gets all of the attributes of the model at the time of the previous + * "change" event. + * @return {Object} + */ + previousAttributes: function previousAttributes() { + return _.clone(this._previousAttributes); + }, + + /** + * Checks if the model is currently in a valid state. It's only possible to + * get into an *invalid* state if you're using silent changes. + * @return {Boolean} + */ + isValid: function isValid() { + try { + this.validate(this.attributes); + } catch (error) { + return false; + } + return true; + }, + + /** + * You should not call this function directly unless you subclass + * AV.Object, in which case you can override this method + * to provide additional validation on set and + * save. Your implementation should throw an Error if + * the attrs is invalid + * + * @param {Object} attrs The current data to validate. + * @see AV.Object#set + */ + validate: function validate(attrs) { + if (_.has(attrs, "ACL") && !(attrs.ACL instanceof AV.ACL)) { + throw new AVError(AVError.OTHER_CAUSE, "ACL must be a AV.ACL."); + } + }, + + /** + * Run validation against a set of incoming attributes, returning `true` + * if all is well. If a specific `error` callback has been passed, + * call that instead of firing the general `"error"` event. + * @private + */ + _validate: function _validate(attrs, options) { + if (options.silent || !this.validate) { + return; + } + attrs = _.extend({}, this.attributes, attrs); + this.validate(attrs); + }, + + /** + * Returns the ACL for this object. + * @returns {AV.ACL} An instance of AV.ACL. + * @see AV.Object#get + */ + getACL: function getACL() { + return this.get("ACL"); + }, + + /** + * Sets the ACL to be used for this object. + * @param {AV.ACL} acl An instance of AV.ACL. + * @param {Object} options Optional Backbone-like options object to be + * passed in to set. + * @return {Boolean} Whether the set passed validation. + * @see AV.Object#set + */ + setACL: function setACL(acl, options) { + return this.set("ACL", acl, options); + }, + + disableBeforeHook: function disableBeforeHook() { + this.ignoreHook('beforeSave'); + this.ignoreHook('beforeUpdate'); + this.ignoreHook('beforeDelete'); + }, + + disableAfterHook: function disableAfterHook() { + this.ignoreHook('afterSave'); + this.ignoreHook('afterUpdate'); + this.ignoreHook('afterDelete'); + }, + + ignoreHook: function ignoreHook(hookName) { + if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) { + console.trace('Unsupported hookName: ' + hookName); + } + + if (!AV.hookKey) { + console.trace('ignoreHook required hookKey'); + } + + if (!this._flags.__ignore_hooks) { + this._flags.__ignore_hooks = []; + } + + this._flags.__ignore_hooks.push(hookName); + } + }); + + /** + * Creates an instance of a subclass of AV.Object for the give classname + * and id. + * @param {String} className The name of the AV class backing this model. + * @param {String} id The object id of this model. + * @return {AV.Object} A new subclass instance of AV.Object. + */ + AV.Object.createWithoutData = function (className, id, hasData) { + var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + result.id = id; + result._hasData = hasData; + return result; + }; + /** + * Delete objects in batch. + * @param {AV.Object[]} objects The AV.Object array to be deleted. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the save + * completes. + */ + AV.Object.destroyAll = function (objects) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!objects || objects.length === 0) { + return AV.Promise.resolve(); + } + var objectsByClassNameAndFlags = _.groupBy(objects, function (object) { + return JSON.stringify({ + className: object.className, + flags: object._flags + }); + }); + var body = { + requests: _.map(objectsByClassNameAndFlags, function (objects) { + var ids = _.map(objects, 'id').join(','); + return { + method: 'DELETE', + path: '/1.1/classes/' + objects[0].className + '/' + ids, + body: objects[0]._flags + }; + }) + }; + return AVRequest('batch', null, null, 'POST', body, options); + }; + + /** + * Returns the appropriate subclass for making new instances of the given + * className string. + * @private + */ + AV.Object._getSubclass = function (className) { + if (!_.isString(className)) { + throw new Error('AV.Object._getSubclass requires a string argument.'); + } + var ObjectClass = AV.Object._classMap[className]; + if (!ObjectClass) { + ObjectClass = AV.Object.extend(className); + AV.Object._classMap[className] = ObjectClass; + } + return ObjectClass; + }; + + /** + * Creates an instance of a subclass of AV.Object for the given classname. + * @private + */ + AV.Object._create = function (className, attributes, options, noDefaultACL) { + var ObjectClass = AV.Object._getSubclass(className); + return new ObjectClass(attributes, options, noDefaultACL); + }; + + // Set up a map of className to class so that we can create new instances of + // AV Objects from JSON automatically. + AV.Object._classMap = {}; + + AV.Object._extend = AV._extend; + + /** + * Creates a new model with defined attributes, + * It's the same with + *
+   *   new AV.Object(attributes, options);
+   *  
+ * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @return {AV.Object} + * @since v0.4.4 + * @see AV.Object + * @see AV.Object.extend + */ + AV.Object['new'] = function (attributes, options) { + return new AV.Object(attributes, options); + }; + + /** + * Creates a new subclass of AV.Object for the given AV class name. + * + *

Every extension of a AV class will inherit from the most recent + * previous extension of that class. When a AV.Object is automatically + * created by parsing JSON, it will use the most recent extension of that + * class.

+ * + *

You should call either:

+   *     var MyClass = AV.Object.extend("MyClass", {
+   *         Instance properties
+   *     }, {
+   *         Class properties
+   *     });
+ * or, for Backbone compatibility:
+   *     var MyClass = AV.Object.extend({
+   *         className: "MyClass",
+   *         Other instance properties
+   *     }, {
+   *         Class properties
+   *     });

+ * + * @param {String} className The name of the AV class backing this model. + * @param {Object} protoProps Instance properties to add to instances of the + * class returned from this method. + * @param {Object} classProps Class properties to add the class returned from + * this method. + * @return {Class} A new subclass of AV.Object. + */ + AV.Object.extend = function (className, protoProps, classProps) { + // Handle the case with only two args. + if (!_.isString(className)) { + if (className && _.has(className, "className")) { + return AV.Object.extend(className.className, className, protoProps); + } else { + throw new Error("AV.Object.extend's first argument should be the className."); + } + } + + // If someone tries to subclass "User", coerce it to the right type. + if (className === "User") { + className = "_User"; + } + + var NewClassObject = null; + if (_.has(AV.Object._classMap, className)) { + var OldClassObject = AV.Object._classMap[className]; + // This new subclass has been told to extend both from "this" and from + // OldClassObject. This is multiple inheritance, which isn't supported. + // For now, let's just pick one. + if (protoProps || classProps) { + NewClassObject = OldClassObject._extend(protoProps, classProps); + } else { + return OldClassObject; + } + } else { + protoProps = protoProps || {}; + protoProps._className = className; + NewClassObject = this._extend(protoProps, classProps); + } + // Extending a subclass should reuse the classname automatically. + NewClassObject.extend = function (arg0) { + if (_.isString(arg0) || arg0 && _.has(arg0, "className")) { + return AV.Object.extend.apply(NewClassObject, arguments); + } + var newArguments = [className].concat(_.toArray(arguments)); + return AV.Object.extend.apply(NewClassObject, newArguments); + }; + NewClassObject['new'] = function (attributes, options) { + return new NewClassObject(attributes, options); + }; + AV.Object._classMap[className] = NewClassObject; + return NewClassObject; + }; + + // ES6 class syntax support + Object.defineProperty(AV.Object.prototype, 'className', { + get: function get() { + var className = this._className || this.constructor._LCClassName || this.constructor.name; + // If someone tries to subclass "User", coerce it to the right type. + if (className === "User") { + return "_User"; + } + return className; + } + }); + + /** + * Register a class. + * If a subclass of AV.Object is defined with your own implement + * rather then AV.Object.extend, the subclass must be registered. + * @param {Function} klass A subclass of AV.Object + * @param {String} [name] Specify the name of the class. Useful when the class might be uglified. + * @example + * class Person extend AV.Object {} + * AV.Object.register(Person); + */ + AV.Object.register = function (klass, name) { + if (!(klass.prototype instanceof AV.Object)) { + throw new Error('registered class is not a subclass of AV.Object'); + } + var className = name || klass.name; + if (!className.length) { + throw new Error('registered class must be named'); + } + if (name) { + klass._LCClassName = name; + } + AV.Object._classMap[className] = klass; + }; + + AV.Object._findUnsavedChildren = function (object, children, files) { + AV._traverse(object, function (object) { + if (object instanceof AV.Object) { + object._refreshCache(); + if (object.dirty()) { + children.push(object); + } + return; + } + + if (object instanceof AV.File) { + if (!object.url() && !object.id) { + files.push(object); + } + return; + } + }); + }; + + AV.Object._canBeSerializedAsValue = function (object) { + var canBeSerializedAsValue = true; + + if (object instanceof AV.Object || object instanceof AV.File) { + canBeSerializedAsValue = !!object.id; + } else if (_.isArray(object)) { + AV._arrayEach(object, function (child) { + if (!AV.Object._canBeSerializedAsValue(child)) { + canBeSerializedAsValue = false; + } + }); + } else if (_.isObject(object)) { + AV._objectEach(object, function (child) { + if (!AV.Object._canBeSerializedAsValue(child)) { + canBeSerializedAsValue = false; + } + }); + } + + return canBeSerializedAsValue; + }; + + AV.Object._deepSaveAsync = function (object, model, options) { + var unsavedChildren = []; + var unsavedFiles = []; + AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles); + if (model) { + unsavedChildren = _.filter(unsavedChildren, function (object) { + return object != model; + }); + } + + var promise = AV.Promise.resolve(); + _.each(unsavedFiles, function (file) { + promise = promise.then(function () { + return file.save(); + }); + }); + + var objects = _.uniq(unsavedChildren); + var remaining = _.uniq(objects); + + return promise.then(function () { + return AV.Promise._continueWhile(function () { + return remaining.length > 0; + }, function () { + + // Gather up all the objects that can be saved in this batch. + var batch = []; + var newRemaining = []; + AV._arrayEach(remaining, function (object) { + // Limit batches to 20 objects. + if (batch.length > 20) { + newRemaining.push(object); + return; + } + + if (object._canBeSerialized()) { + batch.push(object); + } else { + newRemaining.push(object); + } + }); + remaining = newRemaining; + + // If we can't save any objects, there must be a circular reference. + if (batch.length === 0) { + return AV.Promise.reject(new AVError(AVError.OTHER_CAUSE, "Tried to save a batch with a cycle.")); + } + + // Reserve a spot in every object's save queue. + var readyToStart = AV.Promise.resolve(_.map(batch, function (object) { + return object._allPreviousSaves || AV.Promise.resolve(); + })); + + // Save a single batch, whether previous saves succeeded or failed. + var bathSavePromise = readyToStart.then(function () { + return AVRequest("batch", null, null, "POST", { + requests: _.map(batch, function (object) { + var json = object._getSaveJSON(); + _.extend(json, object._flags); + var method = "POST"; + + var path = "/1.1/classes/" + object.className; + if (object.id) { + path = path + "/" + object.id; + method = "PUT"; + } + + object._startSave(); + + return { + method: method, + path: path, + body: json + }; + }) + + }, options).then(function (response) { + var error; + AV._arrayEach(batch, function (object, i) { + if (response[i].success) { + object._finishSave(object.parse(response[i].success)); + } else { + error = error || response[i].error; + object._cancelSave(); + } + }); + if (error) { + return AV.Promise.reject(new AVError(error.code, error.error)); + } + }); + }); + AV._arrayEach(batch, function (object) { + object._allPreviousSaves = bathSavePromise; + }); + return bathSavePromise; + }); + }).then(function () { + return object; + }); + }; +}; + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + + /** + * @private + * @class + * A AV.Op is an atomic operation that can be applied to a field in a + * AV.Object. For example, calling object.set("foo", "bar") + * is an example of a AV.Op.Set. Calling object.unset("foo") + * is a AV.Op.Unset. These operations are stored in a AV.Object and + * sent to the server as part of object.save() operations. + * Instances of AV.Op should be immutable. + * + * You should not create subclasses of AV.Op or instantiate AV.Op + * directly. + */ + AV.Op = function () { + this._initialize.apply(this, arguments); + }; + + AV.Op.prototype = { + _initialize: function _initialize() {} + }; + + _.extend(AV.Op, { + /** + * To create a new Op, call AV.Op._extend(); + * @private + */ + _extend: AV._extend, + + // A map of __op string to decoder function. + _opDecoderMap: {}, + + /** + * Registers a function to convert a json object with an __op field into an + * instance of a subclass of AV.Op. + * @private + */ + _registerDecoder: function _registerDecoder(opName, decoder) { + AV.Op._opDecoderMap[opName] = decoder; + }, + + /** + * Converts a json object into an instance of a subclass of AV.Op. + * @private + */ + _decode: function _decode(json) { + var decoder = AV.Op._opDecoderMap[json.__op]; + if (decoder) { + return decoder(json); + } else { + return undefined; + } + } + }); + + /* + * Add a handler for Batch ops. + */ + AV.Op._registerDecoder("Batch", function (json) { + var op = null; + AV._arrayEach(json.ops, function (nextOp) { + nextOp = AV.Op._decode(nextOp); + op = nextOp._mergeWithPrevious(op); + }); + return op; + }); + + /** + * @private + * @class + * A Set operation indicates that either the field was changed using + * AV.Object.set, or it is a mutable container that was detected as being + * changed. + */ + AV.Op.Set = AV.Op._extend( /** @lends AV.Op.Set.prototype */{ + _initialize: function _initialize(value) { + this._value = value; + }, + + /** + * Returns the new value of this field after the set. + */ + value: function value() { + return this._value; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return AV._encode(this.value()); + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + return this; + }, + + _estimate: function _estimate(oldValue) { + return this.value(); + } + }); + + /** + * A sentinel value that is returned by AV.Op.Unset._estimate to + * indicate the field should be deleted. Basically, if you find _UNSET as a + * value in your object, you should remove that key. + */ + AV.Op._UNSET = {}; + + /** + * @private + * @class + * An Unset operation indicates that this field has been deleted from the + * object. + */ + AV.Op.Unset = AV.Op._extend( /** @lends AV.Op.Unset.prototype */{ + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Delete" }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + return this; + }, + + _estimate: function _estimate(oldValue) { + return AV.Op._UNSET; + } + }); + + AV.Op._registerDecoder("Delete", function (json) { + return new AV.Op.Unset(); + }); + + /** + * @private + * @class + * An Increment is an atomic operation where the numeric value for the field + * will be increased by a given amount. + */ + AV.Op.Increment = AV.Op._extend( + /** @lends AV.Op.Increment.prototype */{ + + _initialize: function _initialize(amount) { + this._amount = amount; + }, + + /** + * Returns the amount to increment by. + * @return {Number} the amount to increment by. + */ + amount: function amount() { + return this._amount; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Increment", amount: this._amount }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.amount()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(previous.value() + this.amount()); + } else if (previous instanceof AV.Op.Increment) { + return new AV.Op.Increment(this.amount() + previous.amount()); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return this.amount(); + } + return oldValue + this.amount(); + } + }); + + AV.Op._registerDecoder("Increment", function (json) { + return new AV.Op.Increment(json.amount); + }); + + /** + * @private + * @class + * Add is an atomic operation where the given objects will be appended to the + * array that is stored in this field. + */ + AV.Op.Add = AV.Op._extend( /** @lends AV.Op.Add.prototype */{ + _initialize: function _initialize(objects) { + this._objects = objects; + }, + + /** + * Returns the objects to be added to the array. + * @return {Array} The objects to be added to the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Add", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.objects()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.Add) { + return new AV.Op.Add(previous.objects().concat(this.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return _.clone(this.objects()); + } else { + return oldValue.concat(this.objects()); + } + } + }); + + AV.Op._registerDecoder("Add", function (json) { + return new AV.Op.Add(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * AddUnique is an atomic operation where the given items will be appended to + * the array that is stored in this field only if they were not already + * present in the array. + */ + AV.Op.AddUnique = AV.Op._extend( + /** @lends AV.Op.AddUnique.prototype */{ + + _initialize: function _initialize(objects) { + this._objects = _.uniq(objects); + }, + + /** + * Returns the objects to be added to the array. + * @return {Array} The objects to be added to the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "AddUnique", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.objects()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.AddUnique) { + return new AV.Op.AddUnique(this._estimate(previous.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return _.clone(this.objects()); + } else { + // We can't just take the _.uniq(_.union(...)) of oldValue and + // this.objects, because the uniqueness may not apply to oldValue + // (especially if the oldValue was set via .set()) + var newValue = _.clone(oldValue); + AV._arrayEach(this.objects(), function (obj) { + if (obj instanceof AV.Object && obj.id) { + var matchingObj = _.find(newValue, function (anObj) { + return anObj instanceof AV.Object && anObj.id === obj.id; + }); + if (!matchingObj) { + newValue.push(obj); + } else { + var index = _.indexOf(newValue, matchingObj); + newValue[index] = obj; + } + } else if (!_.contains(newValue, obj)) { + newValue.push(obj); + } + }); + return newValue; + } + } + }); + + AV.Op._registerDecoder("AddUnique", function (json) { + return new AV.Op.AddUnique(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * Remove is an atomic operation where the given objects will be removed from + * the array that is stored in this field. + */ + AV.Op.Remove = AV.Op._extend( /** @lends AV.Op.Remove.prototype */{ + _initialize: function _initialize(objects) { + this._objects = _.uniq(objects); + }, + + /** + * Returns the objects to be removed from the array. + * @return {Array} The objects to be removed from the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Remove", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return previous; + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.Remove) { + return new AV.Op.Remove(_.union(previous.objects(), this.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return []; + } else { + var newValue = _.difference(oldValue, this.objects()); + // If there are saved AV Objects being removed, also remove them. + AV._arrayEach(this.objects(), function (obj) { + if (obj instanceof AV.Object && obj.id) { + newValue = _.reject(newValue, function (other) { + return other instanceof AV.Object && other.id === obj.id; + }); + } + }); + return newValue; + } + } + }); + + AV.Op._registerDecoder("Remove", function (json) { + return new AV.Op.Remove(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * A Relation operation indicates that the field is an instance of + * AV.Relation, and objects are being added to, or removed from, that + * relation. + */ + AV.Op.Relation = AV.Op._extend( + /** @lends AV.Op.Relation.prototype */{ + + _initialize: function _initialize(adds, removes) { + this._targetClassName = null; + + var self = this; + + var pointerToId = function pointerToId(object) { + if (object instanceof AV.Object) { + if (!object.id) { + throw new Error('You can\'t add an unsaved AV.Object to a relation.'); + } + if (!self._targetClassName) { + self._targetClassName = object.className; + } + if (self._targetClassName !== object.className) { + throw new Error("Tried to create a AV.Relation with 2 different types: " + self._targetClassName + " and " + object.className + "."); + } + return object.id; + } + return object; + }; + + this.relationsToAdd = _.uniq(_.map(adds, pointerToId)); + this.relationsToRemove = _.uniq(_.map(removes, pointerToId)); + }, + + /** + * Returns an array of unfetched AV.Object that are being added to the + * relation. + * @return {Array} + */ + added: function added() { + var self = this; + return _.map(this.relationsToAdd, function (objectId) { + var object = AV.Object._create(self._targetClassName); + object.id = objectId; + return object; + }); + }, + + /** + * Returns an array of unfetched AV.Object that are being removed from + * the relation. + * @return {Array} + */ + removed: function removed() { + var self = this; + return _.map(this.relationsToRemove, function (objectId) { + var object = AV.Object._create(self._targetClassName); + object.id = objectId; + return object; + }); + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + var adds = null; + var removes = null; + var self = this; + var idToPointer = function idToPointer(id) { + return { __type: 'Pointer', + className: self._targetClassName, + objectId: id }; + }; + var pointers = null; + if (this.relationsToAdd.length > 0) { + pointers = _.map(this.relationsToAdd, idToPointer); + adds = { "__op": "AddRelation", "objects": pointers }; + } + + if (this.relationsToRemove.length > 0) { + pointers = _.map(this.relationsToRemove, idToPointer); + removes = { "__op": "RemoveRelation", "objects": pointers }; + } + + if (adds && removes) { + return { "__op": "Batch", "ops": [adds, removes] }; + } + + return adds || removes || {}; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + throw new Error('You can\'t modify a relation after deleting it.'); + } else if (previous instanceof AV.Op.Relation) { + if (previous._targetClassName && previous._targetClassName !== this._targetClassName) { + throw new Error("Related object must be of class " + previous._targetClassName + ", but " + this._targetClassName + " was passed in."); + } + var newAdd = _.union(_.difference(previous.relationsToAdd, this.relationsToRemove), this.relationsToAdd); + var newRemove = _.union(_.difference(previous.relationsToRemove, this.relationsToAdd), this.relationsToRemove); + + var newRelation = new AV.Op.Relation(newAdd, newRemove); + newRelation._targetClassName = this._targetClassName; + return newRelation; + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue, object, key) { + if (!oldValue) { + var relation = new AV.Relation(object, key); + relation.targetClassName = this._targetClassName; + } else if (oldValue instanceof AV.Relation) { + if (this._targetClassName) { + if (oldValue.targetClassName) { + if (oldValue.targetClassName !== this._targetClassName) { + throw new Error("Related object must be a " + oldValue.targetClassName + ", but a " + this._targetClassName + " was passed in."); + } + } else { + oldValue.targetClassName = this._targetClassName; + } + } + return oldValue; + } else { + throw new Error('Op is invalid after previous op.'); + } + } + }); + + AV.Op._registerDecoder("AddRelation", function (json) { + return new AV.Op.Relation(AV._decode(json.objects), []); + }); + AV.Op._registerDecoder("RemoveRelation", function (json) { + return new AV.Op.Relation([], AV._decode(json.objects)); + }); +}; + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + AV.Installation = AV.Object.extend("_Installation"); + + /** + * @namespace + */ + AV.Push = AV.Push || {}; + + /** + * Sends a push notification. + * @param {Object} data The data of the push notification. + * @param {String[]} [data.channels] An Array of channels to push to. + * @param {Date} [data.push_time] A Date object for when to send the push. + * @param {Date} [data.expiration_time] A Date object for when to expire + * the push. + * @param {Number} [data.expiration_interval] The seconds from now to expire the push. + * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match + * a set of installations to push to. + * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match + * a set of installations to push to. + * @param {Date} data.data The data to send as part of the push + * @param {AuthOptions} [options] + * @return {Promise} + */ + AV.Push.send = function (data, options) { + if (data.where) { + data.where = data.where.toJSON().where; + } + + if (data.where && data.cql) { + throw new Error("Both where and cql can't be set"); + } + + if (data.push_time) { + data.push_time = data.push_time.toJSON(); + } + + if (data.expiration_time) { + data.expiration_time = data.expiration_time.toJSON(); + } + + if (data.expiration_time && data.expiration_time_interval) { + throw new Error("Both expiration_time and expiration_time_interval can't be set"); + } + + var request = AVRequest('push', null, null, 'POST', data, options); + return request; + }; +}; + +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var debug = __webpack_require__(5)('leancloud:query'); +var Promise = __webpack_require__(1); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; + +var _require = __webpack_require__(4), + ensureArray = _require.ensureArray; + +var requires = function requires(value, message) { + if (value === undefined) { + throw new Error(message); + } +}; + +// AV.Query is a way to create a list of AV.Objects. +module.exports = function (AV) { + /** + * Creates a new AV.Query for the given AV.Object subclass. + * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string. + * @class + * + *

AV.Query defines a query that is used to fetch AV.Objects. The + * most common use case is finding all objects that match a query through the + * find method. For example, this sample code fetches all objects + * of class MyClass. It calls a different function depending on + * whether the fetch succeeded or not. + * + *

+   * var query = new AV.Query(MyClass);
+   * query.find().then(function(results) {
+   *   // results is an array of AV.Object.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ * + *

An AV.Query can also be used to retrieve a single object whose id is + * known, through the get method. For example, this sample code fetches an + * object of class MyClass and id myId. It calls a + * different function depending on whether the fetch succeeded or not. + * + *

+   * var query = new AV.Query(MyClass);
+   * query.get(myId).then(function(object) {
+   *   // object is an instance of AV.Object.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ * + *

An AV.Query can also be used to count the number of objects that match + * the query without retrieving all of those objects. For example, this + * sample code counts the number of objects of the class MyClass + *

+   * var query = new AV.Query(MyClass);
+   * query.count().then(function(number) {
+   *   // There are number instances of MyClass.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ */ + AV.Query = function (objectClass) { + if (_.isString(objectClass)) { + objectClass = AV.Object._getSubclass(objectClass); + } + + this.objectClass = objectClass; + + this.className = objectClass.prototype.className; + + this._where = {}; + this._include = []; + this._select = []; + this._limit = -1; // negative limit means, do not send a limit + this._skip = 0; + this._extraOptions = {}; + }; + + /** + * Constructs a AV.Query that is the OR of the passed in queries. For + * example: + *
var compoundQuery = AV.Query.or(query1, query2, query3);
+ * + * will create a compoundQuery that is an or of the query1, query2, and + * query3. + * @param {...AV.Query} var_args The list of queries to OR. + * @return {AV.Query} The query that is the OR of the passed in queries. + */ + AV.Query.or = function () { + var queries = _.toArray(arguments); + var className = null; + AV._arrayEach(queries, function (q) { + if (_.isNull(className)) { + className = q.className; + } + + if (className !== q.className) { + throw new Error('All queries must be for the same class'); + } + }); + var query = new AV.Query(className); + query._orQuery(queries); + return query; + }; + + /** + * Constructs a AV.Query that is the AND of the passed in queries. For + * example: + *
var compoundQuery = AV.Query.and(query1, query2, query3);
+ * + * will create a compoundQuery that is an 'and' of the query1, query2, and + * query3. + * @param {...AV.Query} var_args The list of queries to AND. + * @return {AV.Query} The query that is the AND of the passed in queries. + */ + AV.Query.and = function () { + var queries = _.toArray(arguments); + var className = null; + AV._arrayEach(queries, function (q) { + if (_.isNull(className)) { + className = q.className; + } + + if (className !== q.className) { + throw new Error('All queries must be for the same class'); + } + }); + var query = new AV.Query(className); + query._andQuery(queries); + return query; + }; + + /** + * Retrieves a list of AVObjects that satisfy the CQL. + * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}. + * + * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}. + * @param {Array} pvalues An array contains placeholder values. + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the results when + * the query completes. + */ + AV.Query.doCloudQuery = function (cql, pvalues, options) { + var params = { cql: cql }; + if (_.isArray(pvalues)) { + params.pvalues = pvalues; + } else { + options = pvalues; + } + + var request = AVRequest('cloudQuery', null, null, 'GET', params, options); + return request.then(function (response) { + //query to process results. + var query = new AV.Query(response.className); + var results = _.map(response.results, function (json) { + var obj = query._newObject(response); + if (obj._finishFetch) { + obj._finishFetch(query._processResult(json), true); + } + return obj; + }); + return { + results: results, + count: response.count, + className: response.className + }; + }); + }; + + AV.Query._extend = AV._extend; + + AV.Query.prototype = { + //hook to iterate result. Added by dennis. + _processResult: function _processResult(obj) { + return obj; + }, + + /** + * Constructs an AV.Object whose id is already known by fetching data from + * the server. + * + * @param {String} objectId The id of the object to be fetched. + * @param {AuthOptions} options + * @return {Promise.} + */ + get: function get(objectId, options) { + if (!objectId) { + var errorObject = new AVError(AVError.OBJECT_NOT_FOUND, "Object not found."); + throw errorObject; + } + + var self = this; + + var obj = self._newObject(); + obj.id = objectId; + + var queryJSON = self.toJSON(); + var fetchOptions = {}; + + if (queryJSON.keys) fetchOptions.keys = queryJSON.keys; + if (queryJSON.include) fetchOptions.include = queryJSON.include; + + return obj.fetch(fetchOptions, options); + }, + + /** + * Returns a JSON representation of this query. + * @return {Object} + */ + toJSON: function toJSON() { + var params = { + where: this._where + }; + + if (this._include.length > 0) { + params.include = this._include.join(","); + } + if (this._select.length > 0) { + params.keys = this._select.join(","); + } + if (this._limit >= 0) { + params.limit = this._limit; + } + if (this._skip > 0) { + params.skip = this._skip; + } + if (this._order !== undefined) { + params.order = this._order; + } + + AV._objectEach(this._extraOptions, function (v, k) { + params[k] = v; + }); + + return params; + }, + + _newObject: function _newObject(response) { + var obj; + if (response && response.className) { + obj = new AV.Object(response.className); + } else { + obj = new this.objectClass(); + } + return obj; + }, + _createRequest: function _createRequest() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.toJSON(); + var options = arguments[1]; + + if (JSON.stringify(params).length > 2000) { + var body = { + requests: [{ + method: 'GET', + path: '/1.1/classes/' + this.className, + params: params + }] + }; + return AVRequest('batch', null, null, 'POST', body, options).then(function (response) { + var result = response[0]; + if (result.success) { + return result.success; + } + var error = new Error(result.error.error || 'Unknown batch error'); + error.code = result.error.code; + throw error; + }); + } + return AVRequest('classes', this.className, null, "GET", params, options); + }, + _parseResponse: function _parseResponse(response) { + var _this = this; + + return _.map(response.results, function (json) { + var obj = _this._newObject(response); + if (obj._finishFetch) { + obj._finishFetch(_this._processResult(json), true); + } + return obj; + }); + }, + + + /** + * Retrieves a list of AVObjects that satisfy this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the results when + * the query completes. + */ + find: function find(options) { + var request = this._createRequest(undefined, options); + return request.then(this._parseResponse.bind(this)); + }, + + + /** + * scan a Query. masterKey required. + * + * @since 2.1.0 + * @param {object} [options] + * @param {string} [options.orderedBy] specify the key to sort + * @param {number} [options.batchSize] specify the batch size for each request + * @param {AuthOptions} [authOptions] + * @return {AsyncIterator.} + * @example const scan = new AV.Query(TestClass).scan({ + * orderedBy: 'objectId', + * batchSize: 10, + * }, { + * useMasterKey: true, + * }); + * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next())); + * getTen().then(results => { + * // results are fisrt 10 instances of TestClass + * return getTen(); + * }).then(results => { + * // 11 - 20 + * }); + */ + scan: function scan() { + var _this2 = this; + + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + orderedBy = _ref.orderedBy, + batchSize = _ref.batchSize; + + var authOptions = arguments[1]; + + var condition = this.toJSON(); + debug('scan %O', condition); + if (condition.order) { + console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.'); + delete condition.order; + } + if (condition.skip) { + console.warn('The skip option of the query is ignored for Query#scan.'); + delete condition.skip; + } + if (condition.limit) { + console.warn('The limit option of the query is ignored for Query#scan.'); + delete condition.limit; + } + if (orderedBy) condition.scan_key = orderedBy; + if (batchSize) condition.limit = batchSize; + var promise = Promise.resolve([]); + var cursor = void 0; + var done = false; + return { + next: function next() { + promise = promise.then(function (remainResults) { + if (done) return []; + if (remainResults.length > 1) return remainResults; + // no cursor means we have reached the end + // except for the first time + if (!cursor && remainResults.length !== 0) { + done = true; + return remainResults; + } + // when only 1 item left in queue + // start the next request to see if it is the last one + return AVRequest('scan/classes', _this2.className, null, 'GET', cursor ? _.extend({}, condition, { cursor: cursor }) : condition, authOptions).then(function (response) { + cursor = response.cursor; + return _this2._parseResponse(response); + }).then(function (results) { + if (!results.length) done = true; + return remainResults.concat(results); + }); + }); + return promise.then(function (remainResults) { + return remainResults.shift(); + }).then(function (result) { + return { + value: result, + done: done + }; + }); + } + }; + }, + + + /** + * Delete objects retrieved by this query. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the save + * completes. + */ + destroyAll: function destroyAll(options) { + var self = this; + return self.find(options).then(function (objects) { + return AV.Object.destroyAll(objects, options); + }); + }, + + /** + * Counts the number of objects that match this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the count when + * the query completes. + */ + count: function count(options) { + var params = this.toJSON(); + params.limit = 0; + params.count = 1; + var request = this._createRequest(params, options); + + return request.then(function (response) { + return response.count; + }); + }, + + /** + * Retrieves at most one AV.Object that satisfies this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the object when + * the query completes. + */ + first: function first(options) { + var self = this; + + var params = this.toJSON(); + params.limit = 1; + var request = this._createRequest(params, options); + + return request.then(function (response) { + return _.map(response.results, function (json) { + var obj = self._newObject(); + if (obj._finishFetch) { + obj._finishFetch(self._processResult(json), true); + } + return obj; + })[0]; + }); + }, + + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * @param {Number} n the number of results to skip. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + skip: function skip(n) { + requires(n, 'undefined is not a valid skip value'); + this._skip = n; + return this; + }, + + /** + * Sets the limit of the number of results to return. The default limit is + * 100, with a maximum of 1000 results being returned at a time. + * @param {Number} n the number of results to limit to. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + limit: function limit(n) { + requires(n, 'undefined is not a valid limit value'); + this._limit = n; + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be equal to the provided value. + * @param {String} key The key to check. + * @param value The value that the AV.Object must contain. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + equalTo: function equalTo(key, value) { + requires(key, 'undefined is not a valid key'); + requires(value, 'undefined is not a valid value'); + this._where[key] = AV._encode(value); + return this; + }, + + /** + * Helper for condition queries + * @private + */ + _addCondition: function _addCondition(key, condition, value) { + requires(key, 'undefined is not a valid condition key'); + requires(condition, 'undefined is not a valid condition'); + requires(value, 'undefined is not a valid condition value'); + + // Check if we already have a condition + if (!this._where[key]) { + this._where[key] = {}; + } + this._where[key][condition] = AV._encode(value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular + * array key's length to be equal to the provided value. + * @param {String} key The array key to check. + * @param value The length value. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + sizeEqualTo: function sizeEqualTo(key, value) { + this._addCondition(key, "$size", value); + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be not equal to the provided value. + * @param {String} key The key to check. + * @param value The value that must not be equalled. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + notEqualTo: function notEqualTo(key, value) { + this._addCondition(key, "$ne", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than the provided value. + * @param {String} key The key to check. + * @param value The value that provides an upper bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + lessThan: function lessThan(key, value) { + this._addCondition(key, "$lt", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than the provided value. + * @param {String} key The key to check. + * @param value The value that provides an lower bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + greaterThan: function greaterThan(key, value) { + this._addCondition(key, "$gt", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than or equal to the provided value. + * @param {String} key The key to check. + * @param value The value that provides an upper bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + lessThanOrEqualTo: function lessThanOrEqualTo(key, value) { + this._addCondition(key, "$lte", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than or equal to the provided value. + * @param {String} key The key to check. + * @param value The value that provides an lower bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + greaterThanOrEqualTo: function greaterThanOrEqualTo(key, value) { + this._addCondition(key, "$gte", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be contained in the provided list of values. + * @param {String} key The key to check. + * @param {Array} values The values that will match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + containedIn: function containedIn(key, values) { + this._addCondition(key, "$in", values); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * not be contained in the provided list of values. + * @param {String} key The key to check. + * @param {Array} values The values that will not match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + notContainedIn: function notContainedIn(key, values) { + this._addCondition(key, "$nin", values); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * contain each one of the provided list of values. + * @param {String} key The key to check. This key's value must be an array. + * @param {Array} values The values that will match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + containsAll: function containsAll(key, values) { + this._addCondition(key, "$all", values); + return this; + }, + + /** + * Add a constraint for finding objects that contain the given key. + * @param {String} key The key that should exist. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + exists: function exists(key) { + this._addCondition(key, "$exists", true); + return this; + }, + + /** + * Add a constraint for finding objects that do not contain a given key. + * @param {String} key The key that should not exist + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotExist: function doesNotExist(key) { + this._addCondition(key, "$exists", false); + return this; + }, + + /** + * Add a regular expression constraint for finding string values that match + * the provided regular expression. + * This may be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {RegExp} regex The regular expression pattern to match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matches: function matches(key, regex, modifiers) { + this._addCondition(key, "$regex", regex); + if (!modifiers) { + modifiers = ""; + } + // Javascript regex options support mig as inline options but store them + // as properties of the object. We support mi & should migrate them to + // modifiers + if (regex.ignoreCase) { + modifiers += 'i'; + } + if (regex.multiline) { + modifiers += 'm'; + } + + if (modifiers && modifiers.length) { + this._addCondition(key, "$options", modifiers); + } + return this; + }, + + /** + * Add a constraint that requires that a key's value matches a AV.Query + * constraint. + * @param {String} key The key that the contains the object to match the + * query. + * @param {AV.Query} query The query that should match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matchesQuery: function matchesQuery(key, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$inQuery", queryJSON); + return this; + }, + + /** + * Add a constraint that requires that a key's value not matches a + * AV.Query constraint. + * @param {String} key The key that the contains the object to match the + * query. + * @param {AV.Query} query The query that should not match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotMatchQuery: function doesNotMatchQuery(key, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$notInQuery", queryJSON); + return this; + }, + + /** + * Add a constraint that requires that a key's value matches a value in + * an object returned by a different AV.Query. + * @param {String} key The key that contains the value that is being + * matched. + * @param {String} queryKey The key in the objects returned by the query to + * match against. + * @param {AV.Query} query The query to run. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matchesKeyInQuery: function matchesKeyInQuery(key, queryKey, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$select", { key: queryKey, query: queryJSON }); + return this; + }, + + /** + * Add a constraint that requires that a key's value not match a value in + * an object returned by a different AV.Query. + * @param {String} key The key that contains the value that is being + * excluded. + * @param {String} queryKey The key in the objects returned by the query to + * match against. + * @param {AV.Query} query The query to run. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotMatchKeyInQuery: function doesNotMatchKeyInQuery(key, queryKey, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$dontSelect", { key: queryKey, query: queryJSON }); + return this; + }, + + /** + * Add constraint that at least one of the passed in queries matches. + * @param {Array} queries + * @return {AV.Query} Returns the query, so you can chain this call. + * @private + */ + _orQuery: function _orQuery(queries) { + var queryJSON = _.map(queries, function (q) { + return q.toJSON().where; + }); + + this._where.$or = queryJSON; + return this; + }, + + /** + * Add constraint that both of the passed in queries matches. + * @param {Array} queries + * @return {AV.Query} Returns the query, so you can chain this call. + * @private + */ + _andQuery: function _andQuery(queries) { + var queryJSON = _.map(queries, function (q) { + return q.toJSON().where; + }); + + this._where.$and = queryJSON; + return this; + }, + + /** + * Converts a string into a regex that matches it. + * Surrounding with \Q .. \E does this, we just need to escape \E's in + * the text separately. + * @private + */ + _quote: function _quote(s) { + return "\\Q" + s.replace("\\E", "\\E\\\\E\\Q") + "\\E"; + }, + + /** + * Add a constraint for finding string values that contain a provided + * string. This may be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} substring The substring that the value must contain. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + contains: function contains(key, value) { + this._addCondition(key, "$regex", this._quote(value)); + return this; + }, + + /** + * Add a constraint for finding string values that start with a provided + * string. This query will use the backend index, so it will be fast even + * for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} prefix The substring that the value must start with. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + startsWith: function startsWith(key, value) { + this._addCondition(key, "$regex", "^" + this._quote(value)); + return this; + }, + + /** + * Add a constraint for finding string values that end with a provided + * string. This will be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} suffix The substring that the value must end with. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + endsWith: function endsWith(key, value) { + this._addCondition(key, "$regex", this._quote(value) + "$"); + return this; + }, + + /** + * Sorts the results in ascending order by the given key. + * + * @param {String} key The key to order by. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + ascending: function ascending(key) { + requires(key, 'undefined is not a valid key'); + this._order = key; + return this; + }, + + /** + * Also sorts the results in ascending order by the given key. The previous sort keys have + * precedence over this key. + * + * @param {String} key The key to order by + * @return {AV.Query} Returns the query so you can chain this call. + */ + addAscending: function addAscending(key) { + requires(key, 'undefined is not a valid key'); + if (this._order) this._order += ',' + key;else this._order = key; + return this; + }, + + /** + * Sorts the results in descending order by the given key. + * + * @param {String} key The key to order by. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + descending: function descending(key) { + requires(key, 'undefined is not a valid key'); + this._order = "-" + key; + return this; + }, + + /** + * Also sorts the results in descending order by the given key. The previous sort keys have + * precedence over this key. + * + * @param {String} key The key to order by + * @return {AV.Query} Returns the query so you can chain this call. + */ + addDescending: function addDescending(key) { + requires(key, 'undefined is not a valid key'); + if (this._order) this._order += ',-' + key;else this._order = '-' + key; + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + near: function near(key, point) { + if (!(point instanceof AV.GeoPoint)) { + // Try to cast it to a GeoPoint, so that near("loc", [20,30]) works. + point = new AV.GeoPoint(point); + } + this._addCondition(key, "$nearSphere", point); + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param maxDistance Maximum distance (in radians) of results to return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinRadians: function withinRadians(key, point, distance) { + this.near(key, point); + this._addCondition(key, "$maxDistance", distance); + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 3958.8 miles. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Number} maxDistance Maximum distance (in miles) of results to + * return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinMiles: function withinMiles(key, point, distance) { + return this.withinRadians(key, point, distance / 3958.8); + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 6371.0 kilometers. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Number} maxDistance Maximum distance (in kilometers) of results + * to return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinKilometers: function withinKilometers(key, point, distance) { + return this.withinRadians(key, point, distance / 6371.0); + }, + + /** + * Add a constraint to the query that requires a particular key's + * coordinates be contained within a given rectangular geographic bounding + * box. + * @param {String} key The key to be constrained. + * @param {AV.GeoPoint} southwest + * The lower-left inclusive corner of the box. + * @param {AV.GeoPoint} northeast + * The upper-right inclusive corner of the box. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinGeoBox: function withinGeoBox(key, southwest, northeast) { + if (!(southwest instanceof AV.GeoPoint)) { + southwest = new AV.GeoPoint(southwest); + } + if (!(northeast instanceof AV.GeoPoint)) { + northeast = new AV.GeoPoint(northeast); + } + this._addCondition(key, '$within', { '$box': [southwest, northeast] }); + return this; + }, + + /** + * Include nested AV.Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetch. + * @param {String[]} keys The name of the key to include. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + include: function include(keys) { + var _this3 = this; + + requires(keys, 'undefined is not a valid key'); + _(arguments).forEach(function (keys) { + _this3._include = _this3._include.concat(ensureArray(keys)); + }); + return this; + }, + + /** + * Restrict the fields of the returned AV.Objects to include only the + * provided keys. If this is called multiple times, then all of the keys + * specified in each of the calls will be included. + * @param {String[]} keys The names of the keys to include. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + select: function select(keys) { + var _this4 = this; + + requires(keys, 'undefined is not a valid key'); + _(arguments).forEach(function (keys) { + _this4._select = _this4._select.concat(ensureArray(keys)); + }); + return this; + }, + + /** + * Iterates over each result of a query, calling a callback for each one. If + * the callback returns a promise, the iteration will not continue until + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are + * processed in an unspecified order. The query may not have any sort order, + * and may not use limit or skip. + * @param callback {Function} Callback that will be called with each result + * of the query. + * @return {Promise} A promise that will be fulfilled once the + * iteration has completed. + */ + each: function each(callback) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + + if (this._order || this._skip || this._limit >= 0) { + var error = new Error("Cannot iterate on a query with sort, skip, or limit."); + return AV.Promise.reject(error); + } + + var query = new AV.Query(this.objectClass); + // We can override the batch size from the options. + // This is undocumented, but useful for testing. + query._limit = options.batchSize || 100; + query._where = _.clone(this._where); + query._include = _.clone(this._include); + + query.ascending('objectId'); + + var finished = false; + return AV.Promise._continueWhile(function () { + return !finished; + }, function () { + return query.find(options).then(function (results) { + var callbacksDone = AV.Promise.resolve(); + _.each(results, function (result) { + callbacksDone = callbacksDone.then(function () { + return callback(result); + }); + }); + + return callbacksDone.then(function () { + if (results.length >= query._limit) { + query.greaterThan("objectId", results[results.length - 1].id); + } else { + finished = true; + } + }); + }); + }); + } + }; + + AV.FriendShipQuery = AV.Query._extend({ + _objectClass: AV.User, + _newObject: function _newObject() { + return new AV.User(); + }, + _processResult: function _processResult(json) { + if (json && json[this._friendshipTag]) { + var user = json[this._friendshipTag]; + if (user.__type === 'Pointer' && user.className === '_User') { + delete user.__type; + delete user.className; + } + return user; + } else { + return null; + } + } + }); +}; + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); + +module.exports = function (AV) { + /** + * Creates a new Relation for the given parent object and key. This + * constructor should rarely be used directly, but rather created by + * {@link AV.Object#relation}. + * @param {AV.Object} parent The parent of this relation. + * @param {String} key The key for this relation on the parent. + * @see AV.Object#relation + * @class + * + *

+ * A class that is used to access all of the children of a many-to-many + * relationship. Each instance of AV.Relation is associated with a + * particular parent object and key. + *

+ */ + AV.Relation = function (parent, key) { + if (!_.isString(key)) { + throw new TypeError('key must be a string'); + } + this.parent = parent; + this.key = key; + this.targetClassName = null; + }; + + /** + * Creates a query that can be used to query the parent objects in this relation. + * @param {String} parentClass The parent class or name. + * @param {String} relationKey The relation field key in parent. + * @param {AV.Object} child The child object. + * @return {AV.Query} + */ + AV.Relation.reverseQuery = function (parentClass, relationKey, child) { + var query = new AV.Query(parentClass); + query.equalTo(relationKey, child._toPointer()); + return query; + }; + + AV.Relation.prototype = { + /** + * Makes sure that this relation has the right parent and key. + * @private + */ + _ensureParentAndKey: function _ensureParentAndKey(parent, key) { + this.parent = this.parent || parent; + this.key = this.key || key; + if (this.parent !== parent) { + throw new Error("Internal Error. Relation retrieved from two different Objects."); + } + if (this.key !== key) { + throw new Error("Internal Error. Relation retrieved from two different keys."); + } + }, + + /** + * Adds a AV.Object or an array of AV.Objects to the relation. + * @param {AV.Object|AV.Object[]} objects The item or items to add. + */ + add: function add(objects) { + if (!_.isArray(objects)) { + objects = [objects]; + } + + var change = new AV.Op.Relation(objects, []); + this.parent.set(this.key, change); + this.targetClassName = change._targetClassName; + }, + + /** + * Removes a AV.Object or an array of AV.Objects from this relation. + * @param {AV.Object|AV.Object[]} objects The item or items to remove. + */ + remove: function remove(objects) { + if (!_.isArray(objects)) { + objects = [objects]; + } + + var change = new AV.Op.Relation([], objects); + this.parent.set(this.key, change); + this.targetClassName = change._targetClassName; + }, + + /** + * Returns a JSON version of the object suitable for saving to disk. + * @return {Object} + */ + toJSON: function toJSON() { + return { "__type": "Relation", "className": this.targetClassName }; + }, + + /** + * Returns a AV.Query that is limited to objects in this + * relation. + * @return {AV.Query} + */ + query: function query() { + var targetClass; + var query; + if (!this.targetClassName) { + targetClass = AV.Object._getSubclass(this.parent.className); + query = new AV.Query(targetClass); + query._extraOptions.redirectClassNameForKey = this.key; + } else { + targetClass = AV.Object._getSubclass(this.targetClassName); + query = new AV.Query(targetClass); + } + query._addCondition("$relatedTo", "object", this.parent._toPointer()); + query._addCondition("$relatedTo", "key", this.key); + + return query; + } + }; +}; + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); + +module.exports = function (AV) { + AV.Role = AV.Object.extend("_Role", /** @lends AV.Role.prototype */{ + // Instance Methods + + /** + * Represents a Role on the AV server. Roles represent groupings of + * Users for the purposes of granting permissions (e.g. specifying an ACL + * for an Object). Roles are specified by their sets of child users and + * child roles, all of which are granted any permissions that the parent + * role has. + * + *

Roles must have a name (which cannot be changed after creation of the + * role), and must specify an ACL.

+ * An AV.Role is a local representation of a role persisted to the AV + * cloud. + * @class AV.Role + * @param {String} name The name of the Role to create. + * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL + * `{'*': { read: true }}` will be used. + */ + constructor: function constructor(name, acl, noDefaultACL) { + if (_.isString(name)) { + AV.Object.prototype.constructor.call(this, null, null); + this.setName(name); + } else { + AV.Object.prototype.constructor.call(this, name, acl); + } + if (acl === undefined) { + if (!noDefaultACL) { + if (!this.getACL()) { + console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.'); + var defaultAcl = new AV.ACL(); + defaultAcl.setPublicReadAccess(true); + this.setACL(defaultAcl); + } + } + } else if (!(acl instanceof AV.ACL)) { + throw new TypeError('acl must be an instance of AV.ACL'); + } else { + this.setACL(acl); + } + }, + + /** + * Gets the name of the role. You can alternatively call role.get("name") + * + * @return {String} the name of the role. + */ + getName: function getName() { + return this.get("name"); + }, + + /** + * Sets the name for a role. This value must be set before the role has + * been saved to the server, and cannot be set once the role has been + * saved. + * + *

+ * A role's name can only contain alphanumeric characters, _, -, and + * spaces. + *

+ * + *

This is equivalent to calling role.set("name", name)

+ * + * @param {String} name The name of the role. + */ + setName: function setName(name, options) { + return this.set("name", name, options); + }, + + /** + * Gets the AV.Relation for the AV.Users that are direct + * children of this role. These users are granted any privileges that this + * role has been granted (e.g. read or write access through ACLs). You can + * add or remove users from the role through this relation. + * + *

This is equivalent to calling role.relation("users")

+ * + * @return {AV.Relation} the relation for the users belonging to this + * role. + */ + getUsers: function getUsers() { + return this.relation("users"); + }, + + /** + * Gets the AV.Relation for the AV.Roles that are direct + * children of this role. These roles' users are granted any privileges that + * this role has been granted (e.g. read or write access through ACLs). You + * can add or remove child roles from this role through this relation. + * + *

This is equivalent to calling role.relation("roles")

+ * + * @return {AV.Relation} the relation for the roles belonging to this + * role. + */ + getRoles: function getRoles() { + return this.relation("roles"); + }, + + /** + * @ignore + */ + validate: function validate(attrs, options) { + if ("name" in attrs && attrs.name !== this.getName()) { + var newName = attrs.name; + if (this.id && this.id !== attrs.objectId) { + // Check to see if the objectId being set matches this.id. + // This happens during a fetch -- the id is set before calling fetch. + // Let the name be set in this case. + return new AVError(AVError.OTHER_CAUSE, "A role's name can only be set before it has been saved."); + } + if (!_.isString(newName)) { + return new AVError(AVError.OTHER_CAUSE, "A role's name must be a String."); + } + if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) { + return new AVError(AVError.OTHER_CAUSE, "A role's name can only contain alphanumeric characters, _," + " -, and spaces."); + } + } + if (AV.Object.prototype.validate) { + return AV.Object.prototype.validate.call(this, attrs, options); + } + return false; + } + }); +}; + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + /** + * A builder to generate sort string for app searching.For example: + * @class + * @since 0.5.1 + * @example + * var builder = new AV.SearchSortBuilder(); + * builder.ascending('key1').descending('key2','max'); + * var query = new AV.SearchQuery('Player'); + * query.sortBy(builder); + * query.find().then(); + */ + AV.SearchSortBuilder = function () { + this._sortFields = []; + }; + + AV.SearchSortBuilder.prototype = { + _addField: function _addField(key, order, mode, missing) { + var field = {}; + field[key] = { + order: order || 'asc', + mode: mode || 'avg', + missing: '_' + (missing || 'last') + }; + this._sortFields.push(field); + return this; + }, + + /** + * Sorts the results in ascending order by the given key and options. + * + * @param {String} key The key to order by. + * @param {String} mode The sort mode, default is 'avg', you can choose + * 'max' or 'min' too. + * @param {String} missing The missing key behaviour, default is 'last', + * you can choose 'first' too. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + ascending: function ascending(key, mode, missing) { + return this._addField(key, 'asc', mode, missing); + }, + + /** + * Sorts the results in descending order by the given key and options. + * + * @param {String} key The key to order by. + * @param {String} mode The sort mode, default is 'avg', you can choose + * 'max' or 'min' too. + * @param {String} missing The missing key behaviour, default is 'last', + * you can choose 'first' too. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + descending: function descending(key, mode, missing) { + return this._addField(key, 'desc', mode, missing); + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Object} options The other options such as mode,order, unit etc. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + whereNear: function whereNear(key, point, options) { + options = options || {}; + var field = {}; + var geo = { + lat: point.latitude, + lon: point.longitude + }; + var m = { + order: options.order || 'asc', + mode: options.mode || 'avg', + unit: options.unit || 'km' + }; + m[key] = geo; + field['_geo_distance'] = m; + + this._sortFields.push(field); + return this; + }, + + /** + * Build a sort string by configuration. + * @return {String} the sort string. + */ + build: function build() { + return JSON.stringify(AV._encode(this._sortFields)); + } + }; + + /** + * App searching query.Use just like AV.Query: + * + * Visit App Searching Guide + * for more details. + * @class + * @since 0.5.1 + * @example + * var query = new AV.SearchQuery('Player'); + * query.queryString('*'); + * query.find().then(function(results) { + * console.log('Found %d objects', query.hits()); + * //Process results + * }); + */ + AV.SearchQuery = AV.Query._extend( /** @lends AV.SearchQuery.prototype */{ + _sid: null, + _hits: 0, + _queryString: null, + _highlights: null, + _sortBuilder: null, + _createRequest: function _createRequest(params, options) { + return AVRequest('search/select', null, null, 'GET', params || this.toJSON(), options); + }, + + /** + * Sets the sid of app searching query.Default is null. + * @param {String} sid Scroll id for searching. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + sid: function sid(_sid) { + this._sid = _sid; + return this; + }, + + /** + * Sets the query string of app searching. + * @param {String} q The query string. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + queryString: function queryString(q) { + this._queryString = q; + return this; + }, + + /** + * Sets the highlight fields. Such as + *

+     *   query.highlights('title');
+     *   //or pass an array.
+     *   query.highlights(['title', 'content'])
+     * 
+ * @param {String[]} highlights a list of fields. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + highlights: function highlights(_highlights) { + var objects; + if (_highlights && _.isString(_highlights)) { + objects = arguments; + } else { + objects = _highlights; + } + this._highlights = objects; + return this; + }, + + /** + * Sets the sort builder for this query. + * @see AV.SearchSortBuilder + * @param { AV.SearchSortBuilder} builder The sort builder. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + * + */ + sortBy: function sortBy(builder) { + this._sortBuilder = builder; + return this; + }, + + /** + * Returns the number of objects that match this query. + * @return {Number} + */ + hits: function hits() { + if (!this._hits) { + this._hits = 0; + } + return this._hits; + }, + + _processResult: function _processResult(json) { + delete json['className']; + delete json['_app_url']; + delete json['_deeplink']; + return json; + }, + + /** + * Returns true when there are more documents can be retrieved by this + * query instance, you can call find function to get more results. + * @see AV.SearchQuery#find + * @return {Boolean} + */ + hasMore: function hasMore() { + return !this._hitEnd; + }, + + /** + * Reset current query instance state(such as sid, hits etc) except params + * for a new searching. After resetting, hasMore() will return true. + */ + reset: function reset() { + this._hitEnd = false; + this._sid = null; + this._hits = 0; + }, + + /** + * Retrieves a list of AVObjects that satisfy this query. + * Either options.success or options.error is called when the find + * completes. + * + * @see AV.Query#find + * @return {AV.Promise} A promise that is resolved with the results when + * the query completes. + */ + find: function find() { + var self = this; + + var request = this._createRequest(); + + return request.then(function (response) { + //update sid for next querying. + if (response.sid) { + self._oldSid = self._sid; + self._sid = response.sid; + } else { + self._sid = null; + self._hitEnd = true; + } + self._hits = response.hits || 0; + + return _.map(response.results, function (json) { + if (json.className) { + response.className = json.className; + } + var obj = self._newObject(response); + obj.appURL = json['_app_url']; + obj._finishFetch(self._processResult(json), true); + return obj; + }); + }); + }, + + toJSON: function toJSON() { + var params = AV.SearchQuery.__super__.toJSON.call(this); + delete params.where; + if (this.className) { + params.clazz = this.className; + } + if (this._sid) { + params.sid = this._sid; + } + if (!this._queryString) { + throw new Error('Please set query string.'); + } else { + params.q = this._queryString; + } + if (this._highlights) { + params.highlights = this._highlights.join(','); + } + if (this._sortBuilder && params.order) { + throw new Error('sort and order can not be set at same time.'); + } + if (this._sortBuilder) { + params.sort = this._sortBuilder.build(); + } + + return params; + } + }); +}; + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _ = __webpack_require__(0); +var AVRequest = __webpack_require__(2).request; + +module.exports = function (AV) { + var getUser = function getUser() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return AV.User.currentAsync().then(function (currUser) { + return currUser || AV.User._fetchUserBySessionToken(options.sessionToken); + }); + }; + + var getUserPointer = function getUserPointer(options) { + return getUser(options).then(function (currUser) { + return AV.Object.createWithoutData('_User', currUser.id)._toPointer(); + }); + }; + + /** + * Contains functions to deal with Status in LeanCloud. + * @class + */ + AV.Status = function (imageUrl, message) { + this.data = {}; + this.inboxType = 'default'; + this.query = null; + if (imageUrl && (typeof imageUrl === 'undefined' ? 'undefined' : _typeof(imageUrl)) === 'object') { + this.data = imageUrl; + } else { + if (imageUrl) { + this.data.image = imageUrl; + } + if (message) { + this.data.message = message; + } + } + return this; + }; + + AV.Status.prototype = { + /** + * Gets the value of an attribute in status data. + * @param {String} attr The string name of an attribute. + */ + get: function get(attr) { + return this.data[attr]; + }, + /** + * Sets a hash of model attributes on the status data. + * @param {String} key The key to set. + * @param {} value The value to give it. + */ + set: function set(key, value) { + this.data[key] = value; + return this; + }, + /** + * Destroy this status,then it will not be avaiable in other user's inboxes. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + if (!this.id) return AV.Promise.reject(new Error('The status id is not exists.')); + var request = AVRequest('statuses', null, this.id, 'DELETE', options); + return request; + }, + /** + * Cast the AV.Status object to an AV.Object pointer. + * @return {AV.Object} A AV.Object pointer. + */ + toObject: function toObject() { + if (!this.id) return null; + return AV.Object.createWithoutData('_Status', this.id); + }, + _getDataJSON: function _getDataJSON() { + var json = _.clone(this.data); + return AV._encode(json); + }, + /** + * Send a status by a AV.Query object. + * @since 0.3.0 + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * // send a status to male users + * var status = new AVStatus('image url', 'a message'); + * status.query = new AV.Query('_User'); + * status.query.equalTo('gender', 'male'); + * status.send().then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + send: function send() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + if (!this.query) { + return AV.Status.sendStatusToFollowers(this, options); + } + + return getUserPointer(options).then(function (currUser) { + var query = _this.query.toJSON(); + query.className = _this.query.className; + var data = {}; + data.query = query; + _this.data = _this.data || {}; + _this.data.source = _this.data.source || currUser; + data.data = _this._getDataJSON(); + data.inboxType = _this.inboxType || 'default'; + + return AVRequest('statuses', null, null, 'POST', data, options); + }).then(function (response) { + _this.id = response.objectId; + _this.createdAt = AV._parseDate(response.createdAt); + return _this; + }); + }, + + _finishFetch: function _finishFetch(serverData) { + this.id = serverData.objectId; + this.createdAt = AV._parseDate(serverData.createdAt); + this.updatedAt = AV._parseDate(serverData.updatedAt); + this.messageId = serverData.messageId; + delete serverData.messageId; + delete serverData.objectId; + delete serverData.createdAt; + delete serverData.updatedAt; + this.data = AV._decode(serverData); + } + }; + + /** + * Send a status to current signined user's followers. + * @since 0.3.0 + * @param {AV.Status} status A status object to be send to followers. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * var status = new AVStatus('image url', 'a message'); + * AV.Status.sendStatusToFollowers(status).then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + AV.Status.sendStatusToFollowers = function (status) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + return getUserPointer(options).then(function (currUser) { + var query = {}; + query.className = '_Follower'; + query.keys = 'follower'; + query.where = { user: currUser }; + var data = {}; + data.query = query; + status.data = status.data || {}; + status.data.source = status.data.source || currUser; + data.data = status._getDataJSON(); + data.inboxType = status.inboxType || 'default'; + + var request = AVRequest('statuses', null, null, 'POST', data, options); + return request.then(function (response) { + status.id = response.objectId; + status.createdAt = AV._parseDate(response.createdAt); + return status; + }); + }); + }; + + /** + *

Send a status from current signined user to other user's private status inbox.

+ * @since 0.3.0 + * @param {AV.Status} status A status object to be send to followers. + * @param {String} target The target user or user's objectId. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * // send a private status to user '52e84e47e4b0f8de283b079b' + * var status = new AVStatus('image url', 'a message'); + * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + AV.Status.sendPrivateStatus = function (status, target) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + if (!target) { + throw new Error("Invalid target user."); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error("Invalid target user."); + } + return getUserPointer(options).then(function (currUser) { + var query = {}; + query.className = '_User'; + query.where = { objectId: userObjectId }; + var data = {}; + data.query = query; + status.data = status.data || {}; + status.data.source = status.data.source || currUser; + data.data = status._getDataJSON(); + data.inboxType = 'private'; + status.inboxType = 'private'; + + var request = AVRequest('statuses', null, null, 'POST', data, options); + return request.then(function (response) { + status.id = response.objectId; + status.createdAt = AV._parseDate(response.createdAt); + return status; + }); + }); + }; + + /** + * Count unread statuses in someone's inbox. + * @since 0.3.0 + * @param {Object} owner The status owner. + * @param {String} inboxType The inbox type, 'default' by default. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the count + * completes. + * @example + * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){ + * console.log(response.unread); //unread statuses number. + * console.log(response.total); //total statuses number. + * }); + */ + AV.Status.countUnreadStatuses = function (owner) { + var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!_.isString(inboxType)) options = inboxType; + if (!options.sessionToken && owner == null && !AV.User.current()) { + throw new Error('Please signin an user or pass the owner objectId.'); + } + return getUser(options).then(function (owner) { + var params = {}; + params.inboxType = AV._encode(inboxType); + params.owner = AV._encode(owner); + return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options); + }); + }; + + /** + * reset unread statuses count in someone's inbox. + * @since 2.1.0 + * @param {Object} owner The status owner. + * @param {String} inboxType The inbox type, 'default' by default. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the reset + * completes. + * @example + * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){ + * console.log(response.unread); //unread statuses number. + * console.log(response.total); //total statuses number. + * }); + */ + AV.Status.resetUnreadCount = function (owner) { + var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!_.isString(inboxType)) options = inboxType; + if (!options.sessionToken && owner == null && !AV.User.current()) { + throw new Error('Please signin an user or pass the owner objectId.'); + } + return getUser(options).then(function (owner) { + var params = {}; + params.inboxType = AV._encode(inboxType); + params.owner = AV._encode(owner); + return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options); + }); + }; + + /** + * Create a status query to find someone's published statuses. + * @since 0.3.0 + * @param {Object} source The status source. + * @return {AV.Query} The query object for status. + * @example + * //Find current user's published statuses. + * var query = AV.Status.statusQuery(AV.User.current()); + * query.find().then(function(statuses){ + * //process statuses + * }); + */ + AV.Status.statusQuery = function (source) { + var query = new AV.Query('_Status'); + if (source) { + query.equalTo('source', source); + } + return query; + }; + + /** + *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

+ * @class + */ + AV.InboxQuery = AV.Query._extend( /** @lends AV.InboxQuery.prototype */{ + _objectClass: AV.Status, + _sinceId: 0, + _maxId: 0, + _inboxType: 'default', + _owner: null, + _newObject: function _newObject() { + return new AV.Status(); + }, + _createRequest: function _createRequest(params, options) { + return AVRequest('subscribe/statuses', null, null, 'GET', params || this.toJSON(), options); + }, + + /** + * Sets the messageId of results to skip before returning any results. + * This is useful for pagination. + * Default is zero. + * @param {Number} n the mesage id. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + sinceId: function sinceId(id) { + this._sinceId = id; + return this; + }, + /** + * Sets the maximal messageId of results。 + * This is useful for pagination. + * Default is zero that is no limition. + * @param {Number} n the mesage id. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + maxId: function maxId(id) { + this._maxId = id; + return this; + }, + /** + * Sets the owner of the querying inbox. + * @param {Object} owner The inbox owner. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + owner: function owner(_owner) { + this._owner = _owner; + return this; + }, + /** + * Sets the querying inbox type.default is 'default'. + * @param {Object} owner The inbox type. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + inboxType: function inboxType(type) { + this._inboxType = type; + return this; + }, + toJSON: function toJSON() { + var params = AV.InboxQuery.__super__.toJSON.call(this); + params.owner = AV._encode(this._owner); + params.inboxType = AV._encode(this._inboxType); + params.sinceId = AV._encode(this._sinceId); + params.maxId = AV._encode(this._maxId); + return params; + } + }); + + /** + * Create a inbox status query to find someone's inbox statuses. + * @since 0.3.0 + * @param {Object} owner The inbox's owner + * @param {String} inboxType The inbox type,'default' by default. + * @return {AV.InboxQuery} The inbox query object. + * @see AV.InboxQuery + * @example + * //Find current user's default inbox statuses. + * var query = AV.Status.inboxQuery(AV.User.current()); + * //find the statuses after the last message id + * query.sinceId(lastMessageId); + * query.find().then(function(statuses){ + * //process statuses + * }); + */ + AV.Status.inboxQuery = function (owner, inboxType) { + var query = new AV.InboxQuery(AV.Status); + if (owner) { + query._owner = owner; + } + if (inboxType) { + query._inboxType = inboxType; + } + return query; + }; +}; + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var _ = __webpack_require__(0); +var AVError = __webpack_require__(3); +var AVRequest = __webpack_require__(2).request; +var Promise = __webpack_require__(1); + +var getWeappLoginCode = function getWeappLoginCode() { + if (typeof wx === 'undefined' || typeof wx.login !== 'function') { + throw new Error('Weapp Login is only available in Weapp'); + } + return new Promise(function (resolve, reject) { + wx.login({ + success: function success(_ref) { + var code = _ref.code, + errMsg = _ref.errMsg; + + if (code) { + resolve(code); + } else { + reject(new Error(errMsg)); + } + } + }); + }); +}; + +module.exports = function (AV) { + /** + * @class + * + *

An AV.User object is a local representation of a user persisted to the + * LeanCloud server. This class is a subclass of an AV.Object, and retains the + * same functionality of an AV.Object, but also extends it with various + * user specific methods, like authentication, signing up, and validation of + * uniqueness.

+ */ + AV.User = AV.Object.extend("_User", /** @lends AV.User.prototype */{ + // Instance Variables + _isCurrentUser: false, + + // Instance Methods + + /** + * Internal method to handle special fields in a _User response. + * @private + */ + _mergeMagicFields: function _mergeMagicFields(attrs) { + if (attrs.sessionToken) { + this._sessionToken = attrs.sessionToken; + delete attrs.sessionToken; + } + AV.User.__super__._mergeMagicFields.call(this, attrs); + }, + + /** + * Removes null values from authData (which exist temporarily for + * unlinking) + * @private + */ + _cleanupAuthData: function _cleanupAuthData() { + if (!this.isCurrent()) { + return; + } + var authData = this.get('authData'); + if (!authData) { + return; + } + AV._objectEach(this.get('authData'), function (value, key) { + if (!authData[key]) { + delete authData[key]; + } + }); + }, + + /** + * Synchronizes authData for all providers. + * @private + */ + _synchronizeAllAuthData: function _synchronizeAllAuthData() { + var authData = this.get('authData'); + if (!authData) { + return; + } + + var self = this; + AV._objectEach(this.get('authData'), function (value, key) { + self._synchronizeAuthData(key); + }); + }, + + /** + * Synchronizes auth data for a provider (e.g. puts the access token in the + * right place to be used by the Facebook SDK). + * @private + */ + _synchronizeAuthData: function _synchronizeAuthData(provider) { + if (!this.isCurrent()) { + return; + } + var authType; + if (_.isString(provider)) { + authType = provider; + provider = AV.User._authProviders[authType]; + } else { + authType = provider.getAuthType(); + } + var authData = this.get('authData'); + if (!authData || !provider) { + return; + } + var success = provider.restoreAuthentication(authData[authType]); + if (!success) { + this._unlinkFrom(provider); + } + }, + + _handleSaveResult: function _handleSaveResult(makeCurrent) { + // Clean up and synchronize the authData object, removing any unset values + if (makeCurrent && !AV._config.disableCurrentUser) { + this._isCurrentUser = true; + } + this._cleanupAuthData(); + this._synchronizeAllAuthData(); + // Don't keep the password around. + delete this._serverData.password; + this._rebuildEstimatedDataForKey("password"); + this._refreshCache(); + if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) { + // Some old version of leanengine-node-sdk will overwrite + // AV.User._saveCurrentUser which returns no Promise. + // So we need a Promise wrapper. + return Promise.resolve(AV.User._saveCurrentUser(this)); + } else { + return Promise.resolve(); + } + }, + + /** + * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can + * call linkWith on the user (even if it doesn't exist yet on the server). + * @private + */ + _linkWith: function _linkWith(provider, data) { + var _this = this; + + var authType; + if (_.isString(provider)) { + authType = provider; + provider = AV.User._authProviders[provider]; + } else { + authType = provider.getAuthType(); + } + if (data) { + var authData = this.get('authData') || {}; + authData[authType] = data; + return this.save({ authData: authData }).then(function (model) { + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + } else { + return provider.authenticate().then(function (result) { + return _this._linkWith(provider, result); + }); + } + }, + + /** + * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。 + * 仅在小程序中可用。 + * + * @return {AV.User} + */ + linkWithWeapp: function linkWithWeapp() { + var _this2 = this; + + return getWeappLoginCode().then(function (code) { + return _this2._linkWith('lc_weapp', { code: code }); + }); + }, + + + /** + * Unlinks a user from a service. + * @private + */ + _unlinkFrom: function _unlinkFrom(provider) { + var _this3 = this; + + if (_.isString(provider)) { + provider = AV.User._authProviders[provider]; + } + return this._linkWith(provider, null).then(function (model) { + _this3._synchronizeAuthData(provider); + return model; + }); + }, + + /** + * Checks whether a user is linked to a service. + * @private + */ + _isLinked: function _isLinked(provider) { + var authType; + if (_.isString(provider)) { + authType = provider; + } else { + authType = provider.getAuthType(); + } + var authData = this.get('authData') || {}; + return !!authData[authType]; + }, + + logOut: function logOut() { + this._logOutWithAll(); + this._isCurrentUser = false; + }, + + /** + * Deauthenticates all providers. + * @private + */ + _logOutWithAll: function _logOutWithAll() { + var authData = this.get('authData'); + if (!authData) { + return; + } + var self = this; + AV._objectEach(this.get('authData'), function (value, key) { + self._logOutWith(key); + }); + }, + + /** + * Deauthenticates a single provider (e.g. removing access tokens from the + * Facebook SDK). + * @private + */ + _logOutWith: function _logOutWith(provider) { + if (!this.isCurrent()) { + return; + } + if (_.isString(provider)) { + provider = AV.User._authProviders[provider]; + } + if (provider && provider.deauthenticate) { + provider.deauthenticate(); + } + }, + + /** + * Signs up a new user. You should call this instead of save for + * new AV.Users. This will create a new AV.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {Object} attrs Extra fields to set on the new user, or null. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the signup + * finishes. + * @see AV.User.signUp + */ + signUp: function signUp(attrs, options) { + var error; + + var username = attrs && attrs.username || this.get("username"); + if (!username || username === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up user with an empty name."); + throw error; + } + + var password = attrs && attrs.password || this.get("password"); + if (!password || password === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up user with an empty password."); + throw error; + } + + return this.save(attrs, options).then(function (model) { + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + }, + + /** + * Signs up a new user with mobile phone and sms code. + * You should call this instead of save for + * new AV.Users. This will create a new AV.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {Object} attrs Extra fields to set on the new user, or null. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the signup + * finishes. + * @see AV.User.signUpOrlogInWithMobilePhone + * @see AV.Cloud.requestSmsCode + */ + signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(attrs) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var error; + + var mobilePhoneNumber = attrs && attrs.mobilePhoneNumber || this.get("mobilePhoneNumber"); + if (!mobilePhoneNumber || mobilePhoneNumber === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up or login user by mobilePhoneNumber " + "with an empty mobilePhoneNumber."); + throw error; + } + + var smsCode = attrs && attrs.smsCode || this.get("smsCode"); + if (!smsCode || smsCode === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up or login user by mobilePhoneNumber " + "with an empty smsCode."); + throw error; + } + + options._makeRequest = function (route, className, id, method, json) { + return AVRequest('usersByMobilePhone', null, null, "POST", json); + }; + return this.save(attrs, options).then(function (model) { + delete model.attributes.smsCode; + delete model._serverData.smsCode; + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + }, + + /** + * Logs in a AV.User. On success, this saves the session to localStorage, + * so you can retrieve the currently logged in user using + * current. + * + *

A username and password must be set before calling logIn.

+ * + * @see AV.User.logIn + * @return {Promise} A promise that is fulfilled with the user when + * the login is complete. + */ + logIn: function logIn() { + var model = this; + var request = AVRequest('login', null, null, 'POST', this.toJSON()); + return request.then(function (resp) { + var serverAttrs = model.parse(resp); + model._finishFetch(serverAttrs); + return model._handleSaveResult(true).then(function () { + if (!serverAttrs.smsCode) delete model.attributes['smsCode']; + return model; + }); + }); + }, + /** + * @see AV.Object#save + */ + save: function save(arg1, arg2, arg3) { + var i, attrs, current, options, saved; + if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) { + attrs = arg1; + options = arg2; + } else { + attrs = {}; + attrs[arg1] = arg2; + options = arg3; + } + options = options || {}; + + return AV.Object.prototype.save.call(this, attrs, options).then(function (model) { + return model._handleSaveResult(false).then(function () { + return model; + }); + }); + }, + + /** + * Follow a user + * @since 0.3.0 + * @param {AV.User | String} target The target user or user's objectId to follow. + * @param {AuthOptions} options + */ + follow: function follow(target, options) { + if (!this.id) { + throw new Error('Please signin.'); + } + if (!target) { + throw new Error('Invalid target user.'); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error('Invalid target user.'); + } + var route = 'users/' + this.id + '/friendship/' + userObjectId; + var request = AVRequest(route, null, null, 'POST', null, options); + return request; + }, + + /** + * Unfollow a user. + * @since 0.3.0 + * @param {AV.User | String} target The target user or user's objectId to unfollow. + * @param {AuthOptions} options + */ + unfollow: function unfollow(target, options) { + if (!this.id) { + throw new Error('Please signin.'); + } + if (!target) { + throw new Error('Invalid target user.'); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error('Invalid target user.'); + } + var route = 'users/' + this.id + '/friendship/' + userObjectId; + var request = AVRequest(route, null, null, 'DELETE', null, options); + return request; + }, + + /** + *Create a follower query to query the user's followers. + * @since 0.3.0 + * @see AV.User#followerQuery + */ + followerQuery: function followerQuery() { + return AV.User.followerQuery(this.id); + }, + + /** + *Create a followee query to query the user's followees. + * @since 0.3.0 + * @see AV.User#followeeQuery + */ + followeeQuery: function followeeQuery() { + return AV.User.followeeQuery(this.id); + }, + + /** + * @see AV.Object#fetch + */ + fetch: function fetch(fetchOptions, options) { + return AV.Object.prototype.fetch.call(this, fetchOptions, options).then(function (model) { + return model._handleSaveResult(false).then(function () { + return model; + }); + }); + }, + + /** + * Update user's new password safely based on old password. + * @param {String} oldPassword the old password. + * @param {String} newPassword the new password. + * @param {AuthOptions} options + */ + updatePassword: function updatePassword(oldPassword, newPassword, options) { + var route = 'users/' + this.id + '/updatePassword'; + var params = { + old_password: oldPassword, + new_password: newPassword + }; + var request = AVRequest(route, null, null, 'PUT', params, options); + return request; + }, + + /** + * Returns true if current would return this user. + * @see AV.User#current + */ + isCurrent: function isCurrent() { + return this._isCurrentUser; + }, + + /** + * Returns get("username"). + * @return {String} + * @see AV.Object#get + */ + getUsername: function getUsername() { + return this.get("username"); + }, + + /** + * Returns get("mobilePhoneNumber"). + * @return {String} + * @see AV.Object#get + */ + getMobilePhoneNumber: function getMobilePhoneNumber() { + return this.get("mobilePhoneNumber"); + }, + + /** + * Calls set("mobilePhoneNumber", phoneNumber, options) and returns the result. + * @param {String} mobilePhoneNumber + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setMobilePhoneNumber: function setMobilePhoneNumber(phone, options) { + return this.set("mobilePhoneNumber", phone, options); + }, + + /** + * Calls set("username", username, options) and returns the result. + * @param {String} username + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setUsername: function setUsername(username, options) { + return this.set("username", username, options); + }, + + /** + * Calls set("password", password, options) and returns the result. + * @param {String} password + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setPassword: function setPassword(password, options) { + return this.set("password", password, options); + }, + + /** + * Returns get("email"). + * @return {String} + * @see AV.Object#get + */ + getEmail: function getEmail() { + return this.get("email"); + }, + + /** + * Calls set("email", email, options) and returns the result. + * @param {String} email + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setEmail: function setEmail(email, options) { + return this.set("email", email, options); + }, + + /** + * Checks whether this user is the current user and has been authenticated. + * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(), + * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id + * @return (Boolean) whether this user is the current user and is logged in. + */ + authenticated: function authenticated() { + console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。'); + return !!this._sessionToken && !AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id; + }, + + /** + * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。 + * + * @since 2.0.0 + * @return Promise. + */ + isAuthenticated: function isAuthenticated() { + var _this4 = this; + + return Promise.resolve().then(function () { + return !!_this4._sessionToken && AV.User._fetchUserBySessionToken(_this4._sessionToken).then(function () { + return true; + }, function (error) { + if (error.code === 211) { + return false; + } + throw error; + }); + }); + }, + + + /** + * Get sessionToken of current user. + * @return {String} sessionToken + */ + getSessionToken: function getSessionToken() { + return this._sessionToken; + }, + + + /** + * Refresh sessionToken of current user. + * @since 2.1.0 + * @param {AuthOptions} [options] + * @return {Promise.} user with refreshed sessionToken + */ + refreshSessionToken: function refreshSessionToken(options) { + var _this5 = this; + + return AVRequest('users/' + this.id + '/refreshSessionToken', null, null, 'PUT', null, options).then(function (response) { + _this5._finishFetch(response); + return _this5._handleSaveResult(true).then(function () { + return _this5; + }); + }); + }, + + + /** + * Get this user's Roles. + * @param {AuthOptions} [options] + * @return {Promise} A promise that is fulfilled with the roles when + * the query is complete. + */ + getRoles: function getRoles(options) { + return AV.Relation.reverseQuery("_Role", "users", this).find(options); + } + }, /** @lends AV.User */{ + // Class Variables + + // The currently logged-in user. + _currentUser: null, + + // Whether currentUser is known to match the serialized version on disk. + // This is useful for saving a localstorage check if you try to load + // _currentUser frequently while there is none stored. + _currentUserMatchesDisk: false, + + // The localStorage key suffix that the current user is stored under. + _CURRENT_USER_KEY: "currentUser", + + // The mapping of auth provider names to actual providers + _authProviders: {}, + + // Class Methods + + /** + * Signs up a new user with a username (or email) and password. + * This will create a new AV.User on the server, and also persist the + * session in localStorage so that you can access the user using + * {@link #current}. + * + * @param {String} username The username (or email) to sign up with. + * @param {String} password The password to sign up with. + * @param {Object} attrs Extra fields to set on the new user. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the signup completes. + * @see AV.User#signUp + */ + signUp: function signUp(username, password, attrs, options) { + attrs = attrs || {}; + attrs.username = username; + attrs.password = password; + var user = AV.Object._create("_User"); + return user.signUp(attrs, options); + }, + + /** + * Logs in a user with a username (or email) and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} username The username (or email) to log in with. + * @param {String} password The password to log in with. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logIn: function logIn(username, password, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ username: username, password: password }); + return user.logIn(options); + }, + + /** + * Logs in a user with a session token. On success, this saves the session + * to disk, so you can retrieve the currently logged in user using + * current. + * + * @param {String} sessionToken The sessionToken to log in with. + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + become: function become(sessionToken) { + return this._fetchUserBySessionToken(sessionToken).then(function (user) { + return user._handleSaveResult(true).then(function () { + return user; + }); + }); + }, + + _fetchUserBySessionToken: function _fetchUserBySessionToken(sessionToken) { + var user = AV.Object._create("_User"); + return AVRequest("users", "me", null, "GET", { + session_token: sessionToken + }).then(function (resp) { + var serverAttrs = user.parse(resp); + user._finishFetch(serverAttrs); + return user; + }); + }, + + /** + * Logs in a user with a mobile phone number and sms code sent by + * AV.User.requestLoginSmsCode.On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} mobilePhone The user's mobilePhoneNumber + * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logInWithMobilePhoneSmsCode: function logInWithMobilePhoneSmsCode(mobilePhone, smsCode, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode }); + return user.logIn(options); + }, + + /** + * Sign up or logs in a user with a mobilePhoneNumber and smsCode. + * On success, this saves the session to disk, so you can retrieve the currently + * logged in user using current. + * + * @param {String} mobilePhoneNumber The user's mobilePhoneNumber. + * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode + * @param {Object} attributes The user's other attributes such as username etc. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#signUpOrlogInWithMobilePhone + * @see AV.Cloud.requestSmsCode + */ + signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(mobilePhoneNumber, smsCode, attrs, options) { + attrs = attrs || {}; + attrs.mobilePhoneNumber = mobilePhoneNumber; + attrs.smsCode = smsCode; + var user = AV.Object._create("_User"); + return user.signUpOrlogInWithMobilePhone(attrs, options); + }, + + /** + * Logs in a user with a mobile phone number and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} mobilePhone The user's mobilePhoneNumber + * @param {String} password The password to log in with. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logInWithMobilePhone: function logInWithMobilePhone(mobilePhone, password, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password }); + return user.logIn(options); + }, + + /** + * Sign up or logs in a user with a third party auth data(AccessToken). + * On success, this saves the session to disk, so you can retrieve the currently + * logged in user using current. + * + * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 } + * @param {string} platform Available platform for sign up. + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) { + * //Access user here + * }).catch(function(error) { + * //console.error("error: ", error); + * }); + * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户} + */ + signUpOrlogInWithAuthData: function signUpOrlogInWithAuthData(authData, platform) { + return AV.User._logInWith(platform, authData); + }, + + + /** + * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。 + * 仅在小程序中可用。 + * + * @since 2.0.0 + * @return {AV.User} + */ + loginWithWeapp: function loginWithWeapp() { + var _this6 = this; + + return getWeappLoginCode().then(function (code) { + return _this6.signUpOrlogInWithAuthData({ code: code }, 'lc_weapp'); + }); + }, + + + /** + * Associate a user with a third party auth data(AccessToken). + * + * @param {AV.User} userObj A user which you want to associate. + * @param {string} platform Available platform for sign up. + * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 } + * @return {Promise} A promise that is fulfilled with the user when completed. + * @example AV.User.associateWithAuthData(loginUser, 'weixin', { + * openid: 'abc123', + * access_token: '123abc', + * expires_in: 1382686496 + * }).then(function(user) { + * //Access user here + * }).catch(function(error) { + * //console.error("error: ", error); + * }); + */ + associateWithAuthData: function associateWithAuthData(userObj, platform, authData) { + return userObj._linkWith(platform, authData); + }, + + /** + * Logs out the currently logged in user session. This will remove the + * session from disk, log out of linked services, and future calls to + * current will return null. + * @return {Promise} + */ + logOut: function logOut() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return Promise.resolve(null); + } + + if (AV.User._currentUser !== null) { + AV.User._currentUser._logOutWithAll(); + AV.User._currentUser._isCurrentUser = false; + } + AV.User._currentUserMatchesDisk = true; + AV.User._currentUser = null; + return AV.localStorage.removeItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)); + }, + + /** + *Create a follower query for special user to query the user's followers. + * @param {String} userObjectId The user object id. + * @return {AV.FriendShipQuery} + * @since 0.3.0 + */ + followerQuery: function followerQuery(userObjectId) { + if (!userObjectId || !_.isString(userObjectId)) { + throw new Error('Invalid user object id.'); + } + var query = new AV.FriendShipQuery('_Follower'); + query._friendshipTag = 'follower'; + query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId)); + return query; + }, + + /** + *Create a followee query for special user to query the user's followees. + * @param {String} userObjectId The user object id. + * @return {AV.FriendShipQuery} + * @since 0.3.0 + */ + followeeQuery: function followeeQuery(userObjectId) { + if (!userObjectId || !_.isString(userObjectId)) { + throw new Error('Invalid user object id.'); + } + var query = new AV.FriendShipQuery('_Followee'); + query._friendshipTag = 'followee'; + query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId)); + return query; + }, + + /** + * Requests a password reset email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * reset their password on the AV site. + * + * @param {String} email The email address associated with the user that + * forgot their password. + * @return {Promise} + */ + requestPasswordReset: function requestPasswordReset(email) { + var json = { email: email }; + var request = AVRequest("requestPasswordReset", null, null, "POST", json); + return request; + }, + + /** + * Requests a verify email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * verify their email address on the AV site. + * + * @param {String} email The email address associated with the user that + * doesn't verify their email address. + * @return {Promise} + */ + requestEmailVerify: function requestEmailVerify(email) { + var json = { email: email }; + var request = AVRequest("requestEmailVerify", null, null, "POST", json); + return request; + }, + + /** + * Requests a verify sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * verify their mobile phone number by calling AV.User.verifyMobilePhone + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that doesn't verify their mobile phone number. + * @return {Promise} + */ + requestMobilePhoneVerify: function requestMobilePhoneVerify(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestMobilePhoneVerify", null, null, "POST", json); + return request; + }, + + /** + * Requests a reset password sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * reset their account's password by calling AV.User.resetPasswordBySmsCode + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that doesn't verify their mobile phone number. + * @return {Promise} + */ + requestPasswordResetBySmsCode: function requestPasswordResetBySmsCode(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestPasswordResetBySmsCode", null, null, "POST", json); + return request; + }, + + /** + * Makes a call to reset user's account password by sms code and new password. + * The sms code is sent by AV.User.requestPasswordResetBySmsCode. + * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode + * @param {String} password The new password. + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + resetPasswordBySmsCode: function resetPasswordBySmsCode(code, password) { + var json = { password: password }; + var request = AVRequest("resetPasswordBySmsCode", null, code, "PUT", json); + return request; + }, + + /** + * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode + * If verify successfully,the user mobilePhoneVerified attribute will be true. + * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + verifyMobilePhone: function verifyMobilePhone(code) { + var request = AVRequest("verifyMobilePhone", null, code, "POST", null); + return request; + }, + + /** + * Requests a logIn sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * login by AV.User.logInWithMobilePhoneSmsCode function. + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that want to login by AV.User.logInWithMobilePhoneSmsCode + * @return {Promise} + */ + requestLoginSmsCode: function requestLoginSmsCode(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestLoginSmsCode", null, null, "POST", json); + return request; + }, + + /** + * Retrieves the currently logged in AVUser with a valid session, + * either from memory or localStorage, if necessary. + * @return {Promise.} resolved with the currently logged in AV.User. + */ + currentAsync: function currentAsync() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return Promise.resolve(null); + } + + if (AV.User._currentUser) { + return Promise.resolve(AV.User._currentUser); + } + + if (AV.User._currentUserMatchesDisk) { + + return Promise.resolve(AV.User._currentUser); + } + + return AV.localStorage.getItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)).then(function (userData) { + if (!userData) { + return null; + } + + // Load the user from local storage. + AV.User._currentUserMatchesDisk = true; + + AV.User._currentUser = AV.Object._create("_User"); + AV.User._currentUser._isCurrentUser = true; + + var json = JSON.parse(userData); + AV.User._currentUser.id = json._id; + delete json._id; + AV.User._currentUser._sessionToken = json._sessionToken; + delete json._sessionToken; + AV.User._currentUser._finishFetch(json); + //AV.User._currentUser.set(json); + + AV.User._currentUser._synchronizeAllAuthData(); + AV.User._currentUser._refreshCache(); + AV.User._currentUser._opSetQueue = [{}]; + return AV.User._currentUser; + }); + }, + + /** + * Retrieves the currently logged in AVUser with a valid session, + * either from memory or localStorage, if necessary. + * @return {AV.User} The currently logged in AV.User. + */ + current: function current() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return null; + } + + if (AV.User._currentUser) { + return AV.User._currentUser; + } + + if (AV.User._currentUserMatchesDisk) { + + return AV.User._currentUser; + } + + // Load the user from local storage. + AV.User._currentUserMatchesDisk = true; + + var userData = AV.localStorage.getItem(AV._getAVPath(AV.User._CURRENT_USER_KEY)); + if (!userData) { + + return null; + } + AV.User._currentUser = AV.Object._create("_User"); + AV.User._currentUser._isCurrentUser = true; + + var json = JSON.parse(userData); + AV.User._currentUser.id = json._id; + delete json._id; + AV.User._currentUser._sessionToken = json._sessionToken; + delete json._sessionToken; + AV.User._currentUser._finishFetch(json); + //AV.User._currentUser.set(json); + + AV.User._currentUser._synchronizeAllAuthData(); + AV.User._currentUser._refreshCache(); + AV.User._currentUser._opSetQueue = [{}]; + return AV.User._currentUser; + }, + + /** + * Persists a user as currentUser to localStorage, and into the singleton. + * @private + */ + _saveCurrentUser: function _saveCurrentUser(user) { + var promise; + if (AV.User._currentUser !== user) { + promise = AV.User.logOut(); + } else { + promise = Promise.resolve(); + } + return promise.then(function () { + user._isCurrentUser = true; + AV.User._currentUser = user; + + var json = user.toJSON(); + json._id = user.id; + json._sessionToken = user._sessionToken; + return AV.localStorage.setItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY), JSON.stringify(json)).then(function () { + AV.User._currentUserMatchesDisk = true; + }); + }); + }, + + _registerAuthenticationProvider: function _registerAuthenticationProvider(provider) { + AV.User._authProviders[provider.getAuthType()] = provider; + // Synchronize the current user with the auth provider. + if (!AV._config.disableCurrentUser && AV.User.current()) { + AV.User.current()._synchronizeAuthData(provider.getAuthType()); + } + }, + + _logInWith: function _logInWith(provider, options) { + var user = AV.Object._create("_User"); + return user._linkWith(provider, options); + } + + }); +}; + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/*! + * LeanCloud JavaScript SDK + * https://leancloud.cn + * + * Copyright 2016 LeanCloud.cn, Inc. + * The LeanCloud JavaScript SDK is freely distributable under the MIT license. + */ + +var AV = __webpack_require__(6); + +AV._ = __webpack_require__(0); +AV.version = __webpack_require__(12); +AV.Promise = __webpack_require__(1); +AV.localStorage = __webpack_require__(11); +AV.Cache = __webpack_require__(10); +AV.Error = __webpack_require__(3); + +__webpack_require__(19); +__webpack_require__(16)(AV); +__webpack_require__(18)(AV); +__webpack_require__(14)(AV); +__webpack_require__(22)(AV); +__webpack_require__(25)(AV); +__webpack_require__(17)(AV); +__webpack_require__(21)(AV); +__webpack_require__(26)(AV); +__webpack_require__(29)(AV); +__webpack_require__(24)(AV); +__webpack_require__(15)(AV); +__webpack_require__(23)(AV); +__webpack_require__(28)(AV); +__webpack_require__(27)(AV); +__webpack_require__(20)(AV); + +module.exports = AV; + +/** + * Options to controll the authentication for an operation + * @typedef {Object} AuthOptions + * @property {String} [sessionToken] Specify a user to excute the operation as. + * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided. + * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set. + */ + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = []; + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var version = __webpack_require__(12); +var comments = ["Browser" || 'Node.js'].concat(__webpack_require__(31)); + +module.exports = 'LeanCloud-JS-SDK/' + version + ' (' + comments.join('; ') + ')'; + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var debug = __webpack_require__(5)('cos'); +var Promise = __webpack_require__(1); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + var uploadUrl = uploadInfo.upload_url + "?sign=" + encodeURIComponent(uploadInfo.token); + + return new Promise(function (resolve, reject) { + var req = request('POST', uploadUrl).field('fileContent', data).field('op', 'upload'); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (res) { + debug(res.status, res.body, res.text); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var Promise = __webpack_require__(1); +var debug = __webpack_require__(5)('qiniu'); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + // Get the uptoken to upload files to qiniu. + var uptoken = uploadInfo.token; + return new Promise(function (resolve, reject) { + var req = request('POST', 'https://up.qbox.me').field('file', data).field('name', file.attributes.name).field('key', file._qiniu_key).field('token', uptoken); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (res) { + debug(res.status, res.body, res.text); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var request = __webpack_require__(7); +var AVPromise = __webpack_require__(1); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + return new Promise(function (resolve, reject) { + // 海外节点,针对 S3 才会返回 upload_url + var req = request('PUT', uploadInfo.upload_url).set('Content-Type', file.get('mime_type')).send(data); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var _ = __webpack_require__(0); +var Promise = __webpack_require__(1); + +// interface Storage { +// readonly attribute boolean async; +// string getItem(string key); +// void setItem(string key, string value); +// void removeItem(string key); +// void clear(); +// Promise getItemAsync(string key); +// Promise setItemAsync(string key, string value); +// Promise removeItemAsync(string key); +// Promise clearAsync(); +// } +var Storage = {}; +var apiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +var localStorage = global.localStorage; + +try { + var testKey = '__storejs__'; + localStorage.setItem(testKey, testKey); + if (localStorage.getItem(testKey) != testKey) { + throw new Error(); + } + localStorage.removeItem(testKey); +} catch (e) { + localStorage = __webpack_require__(43); +} + +// in browser, `localStorage.async = false` will excute `localStorage.setItem('async', false)` +_(apiNames).each(function (apiName) { + Storage[apiName] = function () { + return global.localStorage[apiName].apply(global.localStorage, arguments); + }; +}); +Storage.async = false; + +module.exports = Storage; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var dataURItoBlob = function dataURItoBlob(dataURI, type) { + var byteString; + + // 传入的 base64,不是 dataURL + if (dataURI.indexOf('base64') < 0) { + byteString = atob(dataURI); + } else if (dataURI.split(',')[0].indexOf('base64') >= 0) { + type = type || dataURI.split(',')[0].split(':')[1].split(';')[0]; + byteString = atob(dataURI.split(',')[1]); + } else { + byteString = unescape(dataURI.split(',')[1]); + } + var ia = new Uint8Array(byteString.length); + for (var i = 0; i < byteString.length; i++) { + ia[i] = byteString.charCodeAt(i); + } + return new Blob([ia], { type: type }); +}; + +module.exports = dataURItoBlob; + +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + + +/***/ }), +/* 39 */ +/***/ (function(module, exports) { + +(function() { + var base64map + = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', + + crypt = { + // Bit-wise rotation left + rotl: function(n, b) { + return (n << b) | (n >>> (32 - b)); + }, + + // Bit-wise rotation right + rotr: function(n, b) { + return (n << (32 - b)) | (n >>> b); + }, + + // Swap big-endian to little-endian and vice versa + endian: function(n) { + // If number given, swap endian + if (n.constructor == Number) { + return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00; + } + + // Else, assume array and swap all items + for (var i = 0; i < n.length; i++) + n[i] = crypt.endian(n[i]); + return n; + }, + + // Generate an array of any length of random bytes + randomBytes: function(n) { + for (var bytes = []; n > 0; n--) + bytes.push(Math.floor(Math.random() * 256)); + return bytes; + }, + + // Convert a byte array to big-endian 32-bit words + bytesToWords: function(bytes) { + for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) + words[b >>> 5] |= bytes[i] << (24 - b % 32); + return words; + }, + + // Convert big-endian 32-bit words to a byte array + wordsToBytes: function(words) { + for (var bytes = [], b = 0; b < words.length * 32; b += 8) + bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); + return bytes; + }, + + // Convert a byte array to a hex string + bytesToHex: function(bytes) { + for (var hex = [], i = 0; i < bytes.length; i++) { + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 0xF).toString(16)); + } + return hex.join(''); + }, + + // Convert a hex string to a byte array + hexToBytes: function(hex) { + for (var bytes = [], c = 0; c < hex.length; c += 2) + bytes.push(parseInt(hex.substr(c, 2), 16)); + return bytes; + }, + + // Convert a byte array to a base-64 string + bytesToBase64: function(bytes) { + for (var base64 = [], i = 0; i < bytes.length; i += 3) { + var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; + for (var j = 0; j < 4; j++) + if (i * 8 + j * 6 <= bytes.length * 8) + base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); + else + base64.push('='); + } + return base64.join(''); + }, + + // Convert a base-64 string to a byte array + base64ToBytes: function(base64) { + // Remove non-base-64 characters + base64 = base64.replace(/[^A-Z0-9+\/]/ig, ''); + + for (var bytes = [], i = 0, imod4 = 0; i < base64.length; + imod4 = ++i % 4) { + if (imod4 == 0) continue; + bytes.push(((base64map.indexOf(base64.charAt(i - 1)) + & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) + | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); + } + return bytes; + } + }; + + module.exports = crypt; +})(); + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __webpack_require__(45); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (namespaces || '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + + +/***/ }), +/* 41 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var require;/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version 4.1.0 + */ + +(function (global, factory) { + true ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; +} + +function isFunction(x) { + return typeof x === 'function'; +} + +var _isArray = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +var isArray = _isArray; + +var len = 0; +var vertxNext = undefined; +var customSchedulerFn = undefined; + +var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +}; + +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = typeof window !== 'undefined' ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + + return useSetTimeout(); +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + node.data = iterations = ++iterations % 2; + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } + + len = 0; +} + +function attemptVertx() { + try { + var r = require; + var vertx = __webpack_require__(51); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} + +var scheduleFlush = undefined; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && "function" === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} + +function then(onFulfillment, onRejection) { + var _arguments = arguments; + + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var _state = parent._state; + + if (_state) { + (function () { + var callback = _arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; +} + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} + +var PROMISE_ID = Math.random().toString(36).substring(16); + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + _resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + _reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return _resolve(promise, value); + }, function (reason) { + return _reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then$$) { + if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$ === GET_THEN_ERROR) { + _reject(promise, GET_THEN_ERROR.error); + GET_THEN_ERROR.error = null; + } else if (then$$ === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$)) { + handleForeignThenable(promise, maybeThenable, then$$); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + + parent._onerror = null; + + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { + return; + } + + var child = undefined, + callback = undefined, + detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value.error = null; + } else { + succeeded = true; + } + + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + _resolve(promise, value); + } else if (failed) { + _reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + _reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + _resolve(promise, value); + }, function rejectPromise(reason) { + _reject(promise, reason); + }); + } catch (e) { + _reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + _reject(this.promise, validationError()); + } +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._enumerate = function () { + var length = this.length; + var _input = this._input; + + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(_input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + + if (resolve$$ === resolve) { + var _then = getThen(entry); + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$) { + return resolve$$(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$(entry), i); + } +}; + +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; + +Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); +}; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +function all(entries) { + return new Enumerator(this, entries).promise; +} + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = resolve; +Promise.reject = reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; + +Promise.prototype = { + constructor: Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + let result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + let author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: then, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function _catch(onRejection) { + return this.then(null, onRejection); + } +}; + +function polyfill() { + var local = undefined; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } + + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + + local.Promise = Promise; +} + +// Strange compat.. +Promise.polyfill = polyfill; +Promise.Promise = Promise; + +return Promise; + +}))); +//# sourceMappingURL=es6-promise.map + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9))) + +/***/ }), +/* 42 */ +/***/ (function(module, exports) { + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + + +/***/ }), +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +(function(root) { + var localStorageMemory = {}; + var cache = {}; + + /** + * number of stored items. + */ + localStorageMemory.length = 0; + + /** + * returns item for passed key, or null + * + * @para {String} key + * name of item to be returned + * @returns {String|null} + */ + localStorageMemory.getItem = function(key) { + return cache[key] || null; + }; + + /** + * sets item for key to passed value, as String + * + * @para {String} key + * name of item to be set + * @para {String} value + * value, will always be turned into a String + * @returns {undefined} + */ + localStorageMemory.setItem = function(key, value) { + if (typeof value === 'undefined') { + localStorageMemory.removeItem(key); + } else { + if (!(cache.hasOwnProperty(key))) { + localStorageMemory.length++; + } + + cache[key] = '' + value; + } + }; + + /** + * removes item for passed key + * + * @para {String} key + * name of item to be removed + * @returns {undefined} + */ + localStorageMemory.removeItem = function(key) { + if (cache.hasOwnProperty(key)) { + delete cache[key]; + localStorageMemory.length--; + } + }; + + /** + * returns name of key at passed index + * + * @para {Number} index + * Position for key to be returned (starts at 0) + * @returns {String|null} + */ + localStorageMemory.key = function(index) { + return Object.keys(cache)[index] || null; + }; + + /** + * removes all stored items and sets length to 0 + * + * @returns {undefined} + */ + localStorageMemory.clear = function() { + cache = {}; + localStorageMemory.length = 0; + }; + + if (true) { + module.exports = localStorageMemory; + } else { + root.localStorageMemory = localStorageMemory; + } +})(this); + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +(function(){ + var crypt = __webpack_require__(39), + utf8 = __webpack_require__(13).utf8, + isBuffer = __webpack_require__(42), + bin = __webpack_require__(13).bin, + + // The core + md5 = function (message, options) { + // Convert to byte array + if (message.constructor == String) + if (options && options.encoding === 'binary') + message = bin.stringToBytes(message); + else + message = utf8.stringToBytes(message); + else if (isBuffer(message)) + message = Array.prototype.slice.call(message, 0); + else if (!Array.isArray(message)) + message = message.toString(); + // else, assume byte array already + + var m = crypt.bytesToWords(message), + l = message.length * 8, + a = 1732584193, + b = -271733879, + c = -1732584194, + d = 271733878; + + // Swap endian + for (var i = 0; i < m.length; i++) { + m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF | + ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00; + } + + // Padding + m[l >>> 5] |= 0x80 << (l % 32); + m[(((l + 64) >>> 9) << 4) + 14] = l; + + // Method shortcuts + var FF = md5._ff, + GG = md5._gg, + HH = md5._hh, + II = md5._ii; + + for (var i = 0; i < m.length; i += 16) { + + var aa = a, + bb = b, + cc = c, + dd = d; + + a = FF(a, b, c, d, m[i+ 0], 7, -680876936); + d = FF(d, a, b, c, m[i+ 1], 12, -389564586); + c = FF(c, d, a, b, m[i+ 2], 17, 606105819); + b = FF(b, c, d, a, m[i+ 3], 22, -1044525330); + a = FF(a, b, c, d, m[i+ 4], 7, -176418897); + d = FF(d, a, b, c, m[i+ 5], 12, 1200080426); + c = FF(c, d, a, b, m[i+ 6], 17, -1473231341); + b = FF(b, c, d, a, m[i+ 7], 22, -45705983); + a = FF(a, b, c, d, m[i+ 8], 7, 1770035416); + d = FF(d, a, b, c, m[i+ 9], 12, -1958414417); + c = FF(c, d, a, b, m[i+10], 17, -42063); + b = FF(b, c, d, a, m[i+11], 22, -1990404162); + a = FF(a, b, c, d, m[i+12], 7, 1804603682); + d = FF(d, a, b, c, m[i+13], 12, -40341101); + c = FF(c, d, a, b, m[i+14], 17, -1502002290); + b = FF(b, c, d, a, m[i+15], 22, 1236535329); + + a = GG(a, b, c, d, m[i+ 1], 5, -165796510); + d = GG(d, a, b, c, m[i+ 6], 9, -1069501632); + c = GG(c, d, a, b, m[i+11], 14, 643717713); + b = GG(b, c, d, a, m[i+ 0], 20, -373897302); + a = GG(a, b, c, d, m[i+ 5], 5, -701558691); + d = GG(d, a, b, c, m[i+10], 9, 38016083); + c = GG(c, d, a, b, m[i+15], 14, -660478335); + b = GG(b, c, d, a, m[i+ 4], 20, -405537848); + a = GG(a, b, c, d, m[i+ 9], 5, 568446438); + d = GG(d, a, b, c, m[i+14], 9, -1019803690); + c = GG(c, d, a, b, m[i+ 3], 14, -187363961); + b = GG(b, c, d, a, m[i+ 8], 20, 1163531501); + a = GG(a, b, c, d, m[i+13], 5, -1444681467); + d = GG(d, a, b, c, m[i+ 2], 9, -51403784); + c = GG(c, d, a, b, m[i+ 7], 14, 1735328473); + b = GG(b, c, d, a, m[i+12], 20, -1926607734); + + a = HH(a, b, c, d, m[i+ 5], 4, -378558); + d = HH(d, a, b, c, m[i+ 8], 11, -2022574463); + c = HH(c, d, a, b, m[i+11], 16, 1839030562); + b = HH(b, c, d, a, m[i+14], 23, -35309556); + a = HH(a, b, c, d, m[i+ 1], 4, -1530992060); + d = HH(d, a, b, c, m[i+ 4], 11, 1272893353); + c = HH(c, d, a, b, m[i+ 7], 16, -155497632); + b = HH(b, c, d, a, m[i+10], 23, -1094730640); + a = HH(a, b, c, d, m[i+13], 4, 681279174); + d = HH(d, a, b, c, m[i+ 0], 11, -358537222); + c = HH(c, d, a, b, m[i+ 3], 16, -722521979); + b = HH(b, c, d, a, m[i+ 6], 23, 76029189); + a = HH(a, b, c, d, m[i+ 9], 4, -640364487); + d = HH(d, a, b, c, m[i+12], 11, -421815835); + c = HH(c, d, a, b, m[i+15], 16, 530742520); + b = HH(b, c, d, a, m[i+ 2], 23, -995338651); + + a = II(a, b, c, d, m[i+ 0], 6, -198630844); + d = II(d, a, b, c, m[i+ 7], 10, 1126891415); + c = II(c, d, a, b, m[i+14], 15, -1416354905); + b = II(b, c, d, a, m[i+ 5], 21, -57434055); + a = II(a, b, c, d, m[i+12], 6, 1700485571); + d = II(d, a, b, c, m[i+ 3], 10, -1894986606); + c = II(c, d, a, b, m[i+10], 15, -1051523); + b = II(b, c, d, a, m[i+ 1], 21, -2054922799); + a = II(a, b, c, d, m[i+ 8], 6, 1873313359); + d = II(d, a, b, c, m[i+15], 10, -30611744); + c = II(c, d, a, b, m[i+ 6], 15, -1560198380); + b = II(b, c, d, a, m[i+13], 21, 1309151649); + a = II(a, b, c, d, m[i+ 4], 6, -145523070); + d = II(d, a, b, c, m[i+11], 10, -1120210379); + c = II(c, d, a, b, m[i+ 2], 15, 718787259); + b = II(b, c, d, a, m[i+ 9], 21, -343485551); + + a = (a + aa) >>> 0; + b = (b + bb) >>> 0; + c = (c + cc) >>> 0; + d = (d + dd) >>> 0; + } + + return crypt.endian([a, b, c, d]); + }; + + // Auxiliary functions + md5._ff = function (a, b, c, d, x, s, t) { + var n = a + (b & c | ~b & d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._gg = function (a, b, c, d, x, s, t) { + var n = a + (b & d | c & ~d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._hh = function (a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._ii = function (a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + + // Package private blocksize + md5._blocksize = 16; + md5._digestsize = 16; + + module.exports = function (message, options) { + if (message === undefined || message === null) + throw new Error('Illegal argument ' + message); + + var digestbytes = crypt.wordsToBytes(md5(message, options)); + return options && options.asBytes ? digestbytes : + options && options.asString ? bin.bytesToString(digestbytes) : + crypt.bytesToHex(digestbytes); + }; + +})(); + + +/***/ }), +/* 45 */ +/***/ (function(module, exports) { + +/** + * Helpers. + */ + +var s = 1000 +var m = s * 60 +var h = m * 60 +var d = h * 24 +var y = d * 365.25 + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {} + var type = typeof val + if (type === 'string' && val.length > 0) { + return parse(val) + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? + fmtLong(val) : + fmtShort(val) + } + throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) +} + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str) + if (str.length > 10000) { + return + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) + if (!match) { + return + } + var n = parseFloat(match[1]) + var type = (match[2] || 'ms').toLowerCase() + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y + case 'days': + case 'day': + case 'd': + return n * d + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n + default: + return undefined + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd' + } + if (ms >= h) { + return Math.round(ms / h) + 'h' + } + if (ms >= m) { + return Math.round(ms / m) + 'm' + } + if (ms >= s) { + return Math.round(ms / s) + 's' + } + return ms + 'ms' +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms' +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name + } + return Math.ceil(ms / n) + ' ' + name + 's' +} + + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Check if `fn` is a function. + * + * @param {Function} fn + * @return {Boolean} + * @api private + */ +var isObject = __webpack_require__(8); + +function isFunction(fn) { + var tag = isObject(fn) ? Object.prototype.toString.call(fn) : ''; + return tag === '[object Function]'; +} + +module.exports = isFunction; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Module of mixed-in functions shared between node and client code + */ +var isObject = __webpack_require__(8); + +/** + * Expose `RequestBase`. + */ + +module.exports = RequestBase; + +/** + * Initialize a new `RequestBase`. + * + * @api public + */ + +function RequestBase(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in RequestBase.prototype) { + obj[key] = RequestBase.prototype[key]; + } + return obj; +} + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.clearTimeout = function _clearTimeout(){ + clearTimeout(this._timer); + clearTimeout(this._responseTimeoutTimer); + delete this._timer; + delete this._responseTimeoutTimer; + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.parse = function parse(fn){ + this._parser = fn; + return this; +}; + +/** + * Set format of binary response body. + * In browser valid formats are 'blob' and 'arraybuffer', + * which return Blob and ArrayBuffer, respectively. + * + * In Node all values result in Buffer. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.responseType = function(val){ + this._responseType = val; + return this; +}; + +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + +RequestBase.prototype.serialize = function serialize(fn){ + this._serializer = fn; + return this; +}; + +/** + * Set timeouts. + * + * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. + * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. + * + * Value of 0 or false means no timeout. + * + * @param {Number|Object} ms or {response, read, deadline} + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.timeout = function timeout(options){ + if (!options || 'object' !== typeof options) { + this._timeout = options; + this._responseTimeout = 0; + return this; + } + + for(var option in options) { + switch(option) { + case 'deadline': + this._timeout = options.deadline; + break; + case 'response': + this._responseTimeout = options.response; + break; + default: + console.warn("Unknown timeout option", option); + } + } + return this; +}; + +/** + * Set number of retry attempts on error. + * + * Failed requests will be retried 'count' times if timeout or err.code >= 500. + * + * @param {Number} count + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.retry = function retry(count){ + // Default to 1 if no count passed or true + if (arguments.length === 0 || count === true) count = 1; + if (count <= 0) count = 0; + this._maxRetries = count; + this._retries = 0; + return this; +}; + +/** + * Retry request + * + * @return {Request} for chaining + * @api private + */ + +RequestBase.prototype._retry = function() { + this.clearTimeout(); + + // node + if (this.req) { + this.req = null; + this.req = this.request(); + } + + this._aborted = false; + this.timedout = false; + + return this._end(); +}; + +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} [reject] + * @return {Request} + */ + +RequestBase.prototype.then = function then(resolve, reject) { + if (!this._fullfilledPromise) { + var self = this; + if (this._endCalled) { + console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"); + } + this._fullfilledPromise = new Promise(function(innerResolve, innerReject){ + self.end(function(err, res){ + if (err) innerReject(err); else innerResolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +} + +RequestBase.prototype.catch = function(cb) { + return this.then(undefined, cb); +}; + +/** + * Allow for extension + */ + +RequestBase.prototype.use = function use(fn) { + fn(this); + return this; +} + +RequestBase.prototype.ok = function(cb) { + if ('function' !== typeof cb) throw Error("Callback required"); + this._okCallback = cb; + return this; +}; + +RequestBase.prototype._isResponseOK = function(res) { + if (!res) { + return false; + } + + if (this._okCallback) { + return this._okCallback(res); + } + + return res.status >= 200 && res.status < 300; +}; + + +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + +RequestBase.prototype.get = function(field){ + return this._header[field.toLowerCase()]; +}; + +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + +RequestBase.prototype.getHeader = RequestBase.prototype.get; + +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.set = function(field, val){ + if (isObject(field)) { + for (var key in field) { + this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; + +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + */ +RequestBase.prototype.unset = function(field){ + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; + +/** + * Write the field `name` and `val`, or multiple fields with one object + * for "multipart/form-data" request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * + * request.post('/upload') + * .field({ foo: 'bar', baz: 'qux' }) + * .end(callback); + * ``` + * + * @param {String|Object} name + * @param {String|Blob|File|Buffer|fs.ReadStream} val + * @return {Request} for chaining + * @api public + */ +RequestBase.prototype.field = function(name, val) { + + // name should be either a string or an object. + if (null === name || undefined === name) { + throw new Error('.field(name, val) name can not be empty'); + } + + if (this._data) { + console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObject(name)) { + for (var key in name) { + this.field(key, name[key]); + } + return this; + } + + if (Array.isArray(val)) { + for (var i in val) { + this.field(name, val[i]); + } + return this; + } + + // val should be defined now + if (null === val || undefined === val) { + throw new Error('.field(name, val) val can not be empty'); + } + if ('boolean' === typeof val) { + val = '' + val; + } + this._getFormData().append(name, val); + return this; +}; + +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */ +RequestBase.prototype.abort = function(){ + if (this._aborted) { + return this; + } + this._aborted = true; + this.xhr && this.xhr.abort(); // browser + this.req && this.req.abort(); // node + this.clearTimeout(); + this.emit('abort'); + return this; +}; + +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ + +RequestBase.prototype.withCredentials = function(on){ + // This is browser-only functionality. Node side is no-op. + if(on==undefined) on = true; + this._withCredentials = on; + return this; +}; + +/** + * Set the max redirects to `n`. Does noting in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.redirects = function(n){ + this._maxRedirects = n; + return this; +}; + +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + +RequestBase.prototype.toJSON = function(){ + return { + method: this.method, + url: this.url, + data: this._data, + headers: this._header + }; +}; + + +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.send = function(data){ + var isObj = isObject(data); + var type = this._header['content-type']; + + if (this._formData) { + console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); + } + + if (isObj && !this._data) { + if (Array.isArray(data)) { + this._data = []; + } else if (!this._isHost(data)) { + this._data = {}; + } + } else if (data && this._data && this._isHost(this._data)) { + throw Error("Can't merge these send calls"); + } + + // merge + if (isObj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + + if (!isObj || this._isHost(data)) { + return this; + } + + // default to json + if (!type) this.type('json'); + return this; +}; + + +/** + * Sort `querystring` by the sort function + * + * + * Examples: + * + * // default order + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery() + * .end(callback) + * + * // customized sort function + * request.get('/user') + * .query('name=Nick') + * .query('search=Manny') + * .sortQuery(function(a, b){ + * return a.length - b.length; + * }) + * .end(callback) + * + * + * @param {Function} sort + * @return {Request} for chaining + * @api public + */ + +RequestBase.prototype.sortQuery = function(sort) { + // _sort default to true but otherwise can be a function or boolean + this._sort = typeof sort === 'undefined' ? true : sort; + return this; +}; + +/** + * Invoke callback with timeout error. + * + * @api private + */ + +RequestBase.prototype._timeoutError = function(reason, timeout, errno){ + if (this._aborted) { + return; + } + var err = new Error(reason + timeout + 'ms exceeded'); + err.timeout = timeout; + err.code = 'ECONNABORTED'; + err.errno = errno; + this.timedout = true; + this.abort(); + this.callback(err); +}; + +RequestBase.prototype._setTimeouts = function() { + var self = this; + + // deadline + if (this._timeout && !this._timer) { + this._timer = setTimeout(function(){ + self._timeoutError('Timeout of ', self._timeout, 'ETIME'); + }, this._timeout); + } + // response timeout + if (this._responseTimeout && !this._responseTimeoutTimer) { + this._responseTimeoutTimer = setTimeout(function(){ + self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); + }, this._responseTimeout); + } +} + + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * Module dependencies. + */ + +var utils = __webpack_require__(50); + +/** + * Expose `ResponseBase`. + */ + +module.exports = ResponseBase; + +/** + * Initialize a new `ResponseBase`. + * + * @api public + */ + +function ResponseBase(obj) { + if (obj) return mixin(obj); +} + +/** + * Mixin the prototype properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in ResponseBase.prototype) { + obj[key] = ResponseBase.prototype[key]; + } + return obj; +} + +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + +ResponseBase.prototype.get = function(field){ + return this.header[field.toLowerCase()]; +}; + +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + +ResponseBase.prototype._setHeaderProperties = function(header){ + // TODO: moar! + // TODO: make this a util + + // content-type + var ct = header['content-type'] || ''; + this.type = utils.type(ct); + + // params + var params = utils.params(ct); + for (var key in params) this[key] = params[key]; + + this.links = {}; + + // links + try { + if (header.link) { + this.links = utils.parseLinks(header.link); + } + } catch (err) { + // ignore + } +}; + +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + +ResponseBase.prototype._setStatusProperties = function(status){ + var type = status / 100 | 0; + + // status / class + this.status = this.statusCode = status; + this.statusType = type; + + // basics + this.info = 1 == type; + this.ok = 2 == type; + this.redirect = 3 == type; + this.clientError = 4 == type; + this.serverError = 5 == type; + this.error = (4 == type || 5 == type) + ? this.toError() + : false; + + // sugar + this.accepted = 202 == status; + this.noContent = 204 == status; + this.badRequest = 400 == status; + this.unauthorized = 401 == status; + this.notAcceptable = 406 == status; + this.forbidden = 403 == status; + this.notFound = 404 == status; +}; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports) { + +var ERROR_CODES = [ + 'ECONNRESET', + 'ETIMEDOUT', + 'EADDRINFO', + 'ESOCKETTIMEDOUT' +]; + +/** + * Determine if a request should be retried. + * (Borrowed from segmentio/superagent-retry) + * + * @param {Error} err + * @param {Response} [res] + * @returns {Boolean} + */ +module.exports = function shouldRetry(err, res) { + if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true; + if (res && res.status && res.status >= 500) return true; + // Superagent timeout + if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true; + if (err && 'crossDomain' in err) return true; + return false; +}; + + +/***/ }), +/* 50 */ +/***/ (function(module, exports) { + + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.type = function(str){ + return str.split(/ *; */).shift(); +}; + +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.params = function(str){ + return str.split(/ *; */).reduce(function(obj, str){ + var parts = str.split(/ *= */); + var key = parts.shift(); + var val = parts.shift(); + + if (key && val) obj[key] = val; + return obj; + }, {}); +}; + +/** + * Parse Link header fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +exports.parseLinks = function(str){ + return str.split(/ *, */).reduce(function(obj, str){ + var parts = str.split(/ *; */); + var url = parts[0].slice(1, -1); + var rel = parts[1].split(/ *= */)[1].slice(1, -1); + obj[rel] = url; + return obj; + }, {}); +}; + +/** + * Strip content related fields from `header`. + * + * @param {Object} header + * @return {Object} header + * @api private + */ + +exports.cleanHeader = function(header, shouldStripCookie){ + delete header['content-type']; + delete header['content-length']; + delete header['transfer-encoding']; + delete header['host']; + if (shouldStripCookie) { + delete header['cookie']; + } + return header; +}; + +/***/ }), +/* 51 */ +/***/ (function(module, exports) { + +/* (ignored) */ + +/***/ }) +/******/ ]); +}); +//# sourceMappingURL=av.js.map \ No newline at end of file diff --git a/dist/av.js.map b/dist/av.js.map new file mode 100644 index 000000000..1b471dc0d --- /dev/null +++ b/dist/av.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap fda3052434ab8851837a","webpack:///./~/underscore/underscore.js","webpack:///./src/promise.js","webpack:///./src/request.js","webpack:///./src/error.js","webpack:///./src/utils/index.js","webpack:///./~/debug/src/browser.js","webpack:///./src/av.js","webpack:///./~/superagent/lib/client.js","webpack:///./~/superagent/lib/is-object.js","webpack:///(webpack)/buildin/global.js","webpack:///./src/cache.js","webpack:///./src/localstorage.js","webpack:///./src/version.js","webpack:///./~/charenc/charenc.js","webpack:///./src/acl.js","webpack:///./src/cloudfunction.js","webpack:///./src/event.js","webpack:///./src/file.js","webpack:///./src/geopoint.js","webpack:///./src/init.js","webpack:///./src/insight.js","webpack:///./src/object.js","webpack:///./src/op.js","webpack:///./src/push.js","webpack:///./src/query.js","webpack:///./src/relation.js","webpack:///./src/role.js","webpack:///./src/search.js","webpack:///./src/status.js","webpack:///./src/user.js","webpack:///./src/index.js","webpack:///./src/ua/comments-browser.js","webpack:///./src/ua/index.js","webpack:///./src/uploader/cos.js","webpack:///./src/uploader/qiniu-browser.js","webpack:///./src/uploader/s3.js","webpack:///./src/utils/localstorage-browser.js","webpack:///./src/utils/parse-base64-browser.js","webpack:///./~/component-emitter/index.js","webpack:///./~/crypt/crypt.js","webpack:///./~/debug/src/debug.js","webpack:///./~/es6-promise/dist/es6-promise.js","webpack:///./~/is-buffer/index.js","webpack:///./~/localstorage-memory/lib/localstorage-memory.js","webpack:///./~/md5/md5.js","webpack:///./~/ms/index.js","webpack:///./~/superagent/lib/is-function.js","webpack:///./~/superagent/lib/request-base.js","webpack:///./~/superagent/lib/response-base.js","webpack:///./~/superagent/lib/should-retry.js","webpack:///./~/superagent/lib/utils.js","webpack:///vertx (ignored)"],"names":["_","require","Promise","_continueWhile","predicate","asyncFunction","then","resolve","module","exports","request","debug","md5","Cache","AVError","AV","getSessionToken","getServerURLPromise","API_HOST","cn","us","sign","key","isMasterKey","now","Date","getTime","signature","requestsCount","ajax","method","resourceUrl","data","headers","onprogress","count","reject","req","set","send","on","end","err","res","status","body","text","header","statusCode","responseText","response","setAppKey","signKey","applicationKey","setHeaders","authOptions","applicationId","useMasterKey","_useMasterKey","masterKey","console","warn","hookKey","_config","applicationProduction","String","userAgent","sessionToken","disableCurrentUser","User","currentAsync","currentUser","_sessionToken","createApiUrl","route","className","objectId","dataObject","serverURL","APIServerURL","apiURL","charAt","length","_fetchWhenSave","_where","encodeURIComponent","JSON","stringify","toLowerCase","indexOf","k","cacheServerURL","ttl","setAsync","handleError","error","api_server","location","catch","errorJSON","code","message","parse","e","setServerUrl","newRegion","findKey","item","region","refreshServerUrlByRouter","url","servers","setServerUrlByRegion","getAsync","AVRequest","Error","extend","OTHER_CAUSE","INTERNAL_SERVER_ERROR","CONNECTION_FAILED","OBJECT_NOT_FOUND","INVALID_QUERY","INVALID_CLASS_NAME","MISSING_OBJECT_ID","INVALID_KEY_NAME","INVALID_POINTER","INVALID_JSON","COMMAND_UNAVAILABLE","NOT_INITIALIZED","INCORRECT_TYPE","INVALID_CHANNEL_NAME","PUSH_MISCONFIGURED","OBJECT_TOO_LARGE","OPERATION_FORBIDDEN","CACHE_MISS","INVALID_NESTED_KEY","INVALID_FILE_NAME","INVALID_ACL","TIMEOUT","INVALID_EMAIL_ADDRESS","MISSING_CONTENT_TYPE","MISSING_CONTENT_LENGTH","INVALID_CONTENT_LENGTH","FILE_TOO_LARGE","FILE_SAVE_ERROR","FILE_DELETE_ERROR","DUPLICATE_VALUE","INVALID_ROLE_NAME","EXCEEDED_QUOTA","SCRIPT_FAILED","VALIDATION_ERROR","INVALID_IMAGE_DATA","UNSAVED_FILE_ERROR","INVALID_PUSH_TIME_ERROR","USERNAME_MISSING","PASSWORD_MISSING","USERNAME_TAKEN","EMAIL_TAKEN","EMAIL_MISSING","EMAIL_NOT_FOUND","SESSION_MISSING","MUST_CREATE_USER_THROUGH_SIGNUP","ACCOUNT_ALREADY_LINKED","LINKED_ID_MISSING","INVALID_LINKED_SESSION","UNSUPPORTED_SERVICE","X_DOMAIN_REQUEST","isNullOrUndefined","x","isNull","isUndefined","ensureArray","isArray","target","undefined","user","tap","interceptor","value","global","AVConfig","EmptyConstructor","inherits","parent","protoProps","staticProps","child","hasOwnProperty","constructor","apply","arguments","prototype","__super__","setProduction","production","_getAVPath","path","isString","substring","_installationId","_getInstallationId","localStorage","getItemAsync","hexOctet","Math","floor","random","toString","setItemAsync","_parseDate","iso8601","regexp","RegExp","match","exec","year","month","day","hour","minute","second","milli","UTC","_extend","classProps","_getValue","object","prop","isFunction","_encode","seenObjects","disallowObjects","Object","include","_hasData","_toPointer","dirty","concat","_toFullJSON","ACL","toJSON","isDate","GeoPoint","map","isRegExp","source","Relation","Op","File","id","isObject","mapObject","v","_decode","__op","__type","pointer","_create","keys","clone","_finishFetch","iso","latitude","longitude","relation","targetClassName","file","name","_encodeObjectOrArray","encodeAVObject","_arrayEach","each","_traverse","func","seen","push","attributes","index","newChild","_each","_objectEach","obj","callback","storage","removeAsync","removeItemAsync","bind","getCacheData","cacheData","expired","expiredAt","cache","syncApiNames","async","apiName","PUBLIC_KEY","arg1","self","permissionsById","setReadAccess","setWriteAccess","accessList","userId","allowed","permission","isBoolean","_setAccess","accessType","Role","getName","permissions","isEmpty","_getAccess","getReadAccess","getWriteAccess","setPublicReadAccess","getPublicReadAccess","setPublicWriteAccess","getPublicWriteAccess","getRoleReadAccess","role","getRoleWriteAccess","setRoleReadAccess","setRoleWriteAccess","Cloud","run","options","resp","result","rpc","getServerDate","requestSmsCode","mobilePhoneNumber","verifySmsCode","phone","params","eventSplitter","slice","Array","Events","events","context","calls","event","node","tail","list","split","_callbacks","shift","next","off","cb","ctx","trigger","args","all","rest","call","unbind","cos","qiniu","s3","parseBase64","avConfig","extname","b64Digit","number","fromCharCode","encodeBase64","array","chunks","ceil","times","i","b1","b2","b3","has2","has3","join","mimeType","metaData","base64","TypeError","size","_extName","_data","owner","current","withURL","type","__source","createWithoutData","json","val","_operations","has","getACL","_acl","setACL","acl","get","attrName","attr","thumbnailURL","width","height","quality","scaleToFit","fmt","mode","ownerId","destroy","_fileToken","extName","mime_type","_qiniu_key","save","_previousSave","uploadInfo","_token","token","blob","uri","Buffer","isBuffer","uploadPromise","provider","_callback","success","fetch","bucket","arg2","_validate","isNumber","__defineGetter__","__defineSetter__","_latitude","_longitude","navigator","geolocation","getCurrentPosition","coords","radiansTo","point","d2r","PI","lat1rad","long1rad","lat2rad","long2rad","deltaLat","deltaLong","sinDeltaLatDiv2","sin","sinDeltaLongDiv2","a","min","asin","sqrt","kilometersTo","milesTo","initialize","appId","appKey","process","env","LEANCLOUD_APP_HOOK_KEY","masterKeyWarn","init","Insight","startJob","jobConfig","sql","JobQuery","_skip","_limit","skip","n","limit","find","utils","RESERVED_KEYS","checkReservedKey","_mergeMagicFields","defaults","collection","_serverData","_opSetQueue","_flags","_hashedJSON","_escapedAttributes","cid","uniqueId","changed","_silent","_pending","silent","_previousAttributes","saveAll","_deepSaveAsync","fetchAll","objects","requests","forEach","fetchWhenSave","enable","getObjectId","getCreatedAt","createdAt","getUpdatedAt","updatedAt","_refreshCache","_refreshingCache","_resetCacheForKey","Set","currentChanges","last","_ensureParentAndKey","escape","html","escaped","attrs","model","specialFields","_startSave","_cancelSave","failedChanges","first","nextChanges","op","op1","op2","_mergeWithPrevious","_saving","_finishSave","serverData","fetchedObjects","savedChanges","_applyOpSet","fetched","_rebuildAllEstimatedData","hasData","opSet","change","_estimate","_UNSET","wasSet","_rebuildEstimatedDataForKey","previousAttributes","oldValue","newValue","unset","unused_value","Unset","dataToValidate","changes","prev","isRealChange","isEqual","increment","amount","Increment","add","Add","addUnique","AddUnique","remove","Remove","clear","keysToClear","_getSaveJSON","_canBeSerialized","_canBeSerializedAsValue","fetchOptions","arg3","saved","wait","setOptions","unsavedChildren","unsavedFiles","_findUnsavedChildren","_allPreviousSaves","query","queryJSON","where","makeRequest","_makeRequest","serverAttrs","triggerDestroy","output","isNew","changing","_changing","deleteChanged","hasChanged","changedAttributes","diff","old","diffVal","previous","isValid","validate","disableBeforeHook","ignoreHook","disableAfterHook","hookName","contains","trace","__ignore_hooks","destroyAll","objectsByClassNameAndFlags","groupBy","flags","ids","_getSubclass","ObjectClass","_classMap","noDefaultACL","NewClassObject","OldClassObject","_className","arg0","newArguments","toArray","defineProperty","_LCClassName","register","klass","children","files","canBeSerializedAsValue","filter","promise","uniq","remaining","batch","newRemaining","readyToStart","bathSavePromise","_initialize","_opDecoderMap","_registerDecoder","opName","decoder","ops","nextOp","_value","_amount","_objects","matchingObj","anObj","union","difference","other","adds","removes","_targetClassName","pointerToId","relationsToAdd","relationsToRemove","added","removed","idToPointer","pointers","newAdd","newRemove","newRelation","Installation","Push","cql","push_time","expiration_time","expiration_time_interval","requires","Query","objectClass","_include","_select","_extraOptions","or","queries","q","_orQuery","and","_andQuery","doCloudQuery","pvalues","results","_newObject","_processResult","errorObject","_order","order","_createRequest","_parseResponse","scan","orderedBy","batchSize","condition","scan_key","cursor","done","remainResults","equalTo","_addCondition","sizeEqualTo","notEqualTo","lessThan","greaterThan","lessThanOrEqualTo","greaterThanOrEqualTo","containedIn","values","notContainedIn","containsAll","exists","doesNotExist","matches","regex","modifiers","ignoreCase","multiline","matchesQuery","doesNotMatchQuery","matchesKeyInQuery","queryKey","doesNotMatchKeyInQuery","$or","$and","_quote","s","replace","startsWith","endsWith","ascending","addAscending","descending","addDescending","near","withinRadians","distance","withinMiles","withinKilometers","withinGeoBox","southwest","northeast","select","finished","callbacksDone","FriendShipQuery","_objectClass","_friendshipTag","reverseQuery","parentClass","relationKey","targetClass","redirectClassNameForKey","setName","defaultAcl","getUsers","getRoles","newName","test","SearchSortBuilder","_sortFields","_addField","missing","field","whereNear","geo","lat","lon","m","unit","build","SearchQuery","_sid","_hits","_queryString","_highlights","_sortBuilder","sid","queryString","highlights","sortBy","builder","hits","hasMore","_hitEnd","reset","_oldSid","appURL","clazz","sort","getUser","currUser","_fetchUserBySessionToken","getUserPointer","Status","imageUrl","inboxType","image","toObject","_getDataJSON","sendStatusToFollowers","messageId","sendPrivateStatus","userObjectId","countUnreadStatuses","resetUnreadCount","statusQuery","InboxQuery","_sinceId","_maxId","_inboxType","_owner","sinceId","maxId","inboxQuery","getWeappLoginCode","wx","login","errMsg","_isCurrentUser","_cleanupAuthData","isCurrent","authData","_synchronizeAllAuthData","_synchronizeAuthData","authType","_authProviders","getAuthType","restoreAuthentication","_unlinkFrom","_handleSaveResult","makeCurrent","password","_saveCurrentUser","_linkWith","authenticate","linkWithWeapp","_isLinked","logOut","_logOutWithAll","_logOutWith","deauthenticate","signUp","username","signUpOrlogInWithMobilePhone","smsCode","logIn","follow","unfollow","followerQuery","followeeQuery","updatePassword","oldPassword","newPassword","old_password","new_password","getUsername","getMobilePhoneNumber","setMobilePhoneNumber","setUsername","setPassword","getEmail","setEmail","email","authenticated","isAuthenticated","refreshSessionToken","_currentUser","_currentUserMatchesDisk","_CURRENT_USER_KEY","become","session_token","logInWithMobilePhoneSmsCode","mobilePhone","logInWithMobilePhone","signUpOrlogInWithAuthData","platform","_logInWith","loginWithWeapp","associateWithAuthData","userObj","requestPasswordReset","requestEmailVerify","requestMobilePhoneVerify","requestPasswordResetBySmsCode","resetPasswordBySmsCode","verifyMobilePhone","requestLoginSmsCode","userData","_id","getItem","_registerAuthenticationProvider","version","comments","upload","saveOptions","_bucket","uploadUrl","upload_url","uptoken","AVPromise","Storage","apiNames","testKey","setItem","removeItem","dataURItoBlob","dataURI","byteString","atob","unescape","ia","Uint8Array","charCodeAt","Blob"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA,mDAA2C,cAAc;;AAEzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,mCAA2B,0BAA0B,EAAE;AACvD,yCAAiC,eAAe;AAChD;AACA;AACA;;AAEA;AACA,8DAAsD,+DAA+D;;AAErH;AACA;;AAEA;AACA;;;;;;;AChEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,yBAAyB,gBAAgB;AACzC;AACA;AACA;AACA,uBAAuB,OAAO;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sCAAsC,YAAY;AAClD;AACA;AACA,KAAK;AACL;AACA,uCAAuC,YAAY;AACnD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,8BAA8B;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,YAAY;AACtD;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,YAAY;AACtD;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,6BAA6B,gBAAgB;AAC7C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA,oDAAoD;AACpD,GAAG;;AAEH;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA,0CAA0C;AAC1C,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,4DAA4D,YAAY;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,YAAY;AAC1D;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,8CAA8C,YAAY;AAC1D;AACA;AACA,qBAAqB,gBAAgB;AACrC;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,uBAAuB,gBAAgB;AACvC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,6CAA6C,YAAY;AACzD;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,8BAA8B;AAC1C;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,sDAAsD;AACtD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0CAA0C,0BAA0B;AACpE;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA,qBAAqB,cAAc;AACnC;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,qBAAqB,YAAY;AACjC;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,YAAY;AAC3B;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,OAAO,eAAe;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA,qBAAqB,eAAe;AACpC;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,yBAAyB,gBAAgB;AACzC;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB;AACnB;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,4CAA4C,mBAAmB;AAC/D;AACA;AACA,yCAAyC,YAAY;AACrD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,qDAAqD;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,6EAA6E;AAC7E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA,qCAAqC;AACrC;AACA;AACA;;AAEA;AACA;AACA;AACA,0BAA0B;AAC1B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,mBAAmB,OAAO;AAC1B;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,eAAe;AACf,cAAc;AACd,cAAc;AACd,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAChB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B;;AAE5B;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA,OAAO;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AS,+CAA+C,EAAE;AAC1D,SAAS,gDAAgD,EAAE;AAC3D,SAAS,gDAAgD,EAAE;AAC3D,SAAS,4CAA4C,EAAE;AACvD;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA,iBAAiB,iBAAiB;AAClC,iBAAiB,sCAAsC;;AAEvD;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB,aAAa;AACb;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,qCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,kBAAkB;AAClB;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,cAAc;;AAEd,qCAAqC,SAAS;AAC9C;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4CAA4C;AAC5C,wCAAwC;AACxC;AACA;AACA;AACA;AACA;AACA,iBAAiB,aAAa;AAC9B,8BAA8B;AAC9B;AACA;AACA;AACA;AACA;AACA,iBAAiB,aAAa,iBAAiB;AAC/C;AACA;AACA;AACA;AACA,0BAA0B,aAAa;AACvC,8BAA8B;AAC9B;AACA;AACA;AACA;AACA,0BAA0B,aAAa,iBAAiB;AACxD;AACA,WAAW,eAAe;AAC1B,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,mBAAmB;AACnB,oBAAoB;AACpB;AACA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oCAAoC;AACpC,OAAO;AACP;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,kBAAkB;AAClB;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA,kDAAkD;AAClD;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA,yDAAyD,iBAAiB;AAC1E;AACA,U;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,gBAAgB;AAC/B;AACA,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,wEAAwE,mBAAmB;AAC3F;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,UAAU;AACrB,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,SAAS,sBAAsB,WAAW,YAAY;;AAEtD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,4FAA4F;AAC5F;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,eAAe;AAC1B,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,eAAe;AAC1B,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,eAAe;AAC1B,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA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AO;AAClB,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,sBAAsB;AACvC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,MAAM;AACjB,YAAY;AACZ;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,2CAA2C,SAAS;AACpD;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;;;;;;AClKA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,qBAAqB,cAAc;AACnC;AACA;AACA,KAAK;;AAEL;AACA;AACA,0BAA0B,OAAO;AACjC;AACA;AACA,KAAK;;AAEL;AACA;AACA,wCAAwC,kBAAkB;AAC1D;AACA;AACA,KAAK;;AAEL;AACA;AACA,iCAAiC,uBAAuB;AACxD;AACA;AACA,KAAK;;AAEL;AACA;AACA,+BAA+B,kBAAkB;AACjD;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA,iCAAiC,gBAAgB;AACjD;AACA;AACA,KAAK;;AAEL;AACA;AACA,kCAAkC,kBAAkB;AACpD;AACA,uBAAuB,OAAO;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;;AAEA,4CAA4C;AAC5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,CAAC;;;;;;;;AC9FD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;;AAEA;AACA;AACA,cAAc;AACd;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mBAAmB,iBAAiB;AACpC;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA,iBAAiB,SAAS;AAC1B,4BAA4B;AAC5B;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA,yCAAyC,SAAS;AAClD;AACA;AACA;AACA;AACA,yCAAyC,SAAS;AAClD;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,MAAM;AACjB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;;;;;;;8CCzMA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC,qBAAqB;;AAEtB;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,iFAAiF;;AAEjF;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,0BAA0B,sBAAsB;;AAEhD;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,iBAAiB,SAAS;AAC1B;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA,CAAC;AACD;AACA;;AAEA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP,KAAK;AACL,GAAG;AACH;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,IAAI;AACd;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,iBAAiB,wBAAwB;AACzC;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,iBAAiB,uCAAuC;AACxD;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,OAAO;AACP;AACA,GAAG;AACH;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,MAAM;AAChB,UAAU,OAAO;AACjB;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,UAAU,MAAM;AAChB;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL,GAAG;AACH;AACA;AACA,qBAAqB,YAAY;AACjC;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA,UAAU,IAAI;AACd;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;;AAEH;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;AACH;;AAEA;AACA,UAAU,SAAS;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,KAAK;;AAEL;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,eAAe;AACf;AACA;AACA;AACA,WAAW;AACX,SAAS;AACT;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;;AAEA;AACA,YAAY,SAAS;AACrB,YAAY,SAAS;AACrB;AACA,aAAa;AACb;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA,YAAY,SAAS;AACrB;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA,SAAS;AACT;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA,CAAC;AACD;;;;;;;;ACroCA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;;;;;ACpBA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA,eAAe;AACf;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA,YAAY,OAAO;AACnB;AACA,eAAe;AACf;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA,eAAe;AACf;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,eAAe;AACf;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA;AACA,CAAC;;;;;;;ACjFD;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,mBAAmB,cAAc;AACjC;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,mBAAmB,cAAc;;AAEjC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA,CAAC;;;;;;;AC/JD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,OAAO;AAClB,YAAY,MAAM;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpJA;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY;AACZ;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;;;;;;;ACdA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW;AACX;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc,QAAQ;AACjC,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB,YAAY;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kCAAkC;AAClC,OAAO;AACP,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gBAAgB,oDAAoD;AACpE;AACA;AACA,WAAW,cAAc;AACzB,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa,yBAAyB;AACtC;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,sCAAsC;AACjD,YAAY,QAAQ;AACpB;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B;AAC/B,+BAA+B;AAC/B;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,YAAY,OAAO;AACnB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mBAAmB,YAAY;AAC/B;AACA;AACA;AACA;AACA,kBAAkB,aAAa;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB,aAAa;AAC/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,cAAc;AACzB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,YAAY;AACZ;AACA;AACA;AACA,WAAW,SAAS;AACpB,YAAY,QAAQ;AACpB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;;;;;;;;AC7kBA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,2CAA2C;AAC3C;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACpIA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,SAAS;AACpB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;ACrBA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA,uBAAuB;AACvB;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA,uBAAuB;AACvB;AACA;AACA;;AAEA;AACA;AACA,GAAG,IAAI;AACP;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY;AACZ;AACA;;AAEA;AACA;AACA,8BAA8B;AAC9B;AACA;AACA;AACA;AACA,GAAG,IAAI;AACP;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;;;;;;ACnEA,e","file":"av.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"AV\"] = factory();\n\telse\n\t\troot[\"AV\"] = factory();\n})(this, function() {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// identity function for calling harmony imports with the correct context\n \t__webpack_require__.i = function(value) { return value; };\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, {\n \t\t\t\tconfigurable: false,\n \t\t\t\tenumerable: true,\n \t\t\t\tget: getter\n \t\t\t});\n \t\t}\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 30);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap fda3052434ab8851837a","// Underscore.js 1.8.3\n// http://underscorejs.org\n// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n// Underscore may be freely distributed under the MIT license.\n\n(function() {\n\n // Baseline setup\n // --------------\n\n // Establish the root object, `window` in the browser, or `exports` on the server.\n var root = this;\n\n // Save the previous value of the `_` variable.\n var previousUnderscore = root._;\n\n // Save bytes in the minified (but not gzipped) version:\n var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;\n\n // Create quick reference variables for speed access to core prototypes.\n var\n push = ArrayProto.push,\n slice = ArrayProto.slice,\n toString = ObjProto.toString,\n hasOwnProperty = ObjProto.hasOwnProperty;\n\n // All **ECMAScript 5** native function implementations that we hope to use\n // are declared here.\n var\n nativeIsArray = Array.isArray,\n nativeKeys = Object.keys,\n nativeBind = FuncProto.bind,\n nativeCreate = Object.create;\n\n // Naked function reference for surrogate-prototype-swapping.\n var Ctor = function(){};\n\n // Create a safe reference to the Underscore object for use below.\n var _ = function(obj) {\n if (obj instanceof _) return obj;\n if (!(this instanceof _)) return new _(obj);\n this._wrapped = obj;\n };\n\n // Export the Underscore object for **Node.js**, with\n // backwards-compatibility for the old `require()` API. If we're in\n // the browser, add `_` as a global object.\n if (typeof exports !== 'undefined') {\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = _;\n }\n exports._ = _;\n } else {\n root._ = _;\n }\n\n // Current version.\n _.VERSION = '1.8.3';\n\n // Internal function that returns an efficient (for current engines) version\n // of the passed-in callback, to be repeatedly applied in other Underscore\n // functions.\n var optimizeCb = function(func, context, argCount) {\n if (context === void 0) return func;\n switch (argCount == null ? 3 : argCount) {\n case 1: return function(value) {\n return func.call(context, value);\n };\n case 2: return function(value, other) {\n return func.call(context, value, other);\n };\n case 3: return function(value, index, collection) {\n return func.call(context, value, index, collection);\n };\n case 4: return function(accumulator, value, index, collection) {\n return func.call(context, accumulator, value, index, collection);\n };\n }\n return function() {\n return func.apply(context, arguments);\n };\n };\n\n // A mostly-internal function to generate callbacks that can be applied\n // to each element in a collection, returning the desired result — either\n // identity, an arbitrary callback, a property matcher, or a property accessor.\n var cb = function(value, context, argCount) {\n if (value == null) return _.identity;\n if (_.isFunction(value)) return optimizeCb(value, context, argCount);\n if (_.isObject(value)) return _.matcher(value);\n return _.property(value);\n };\n _.iteratee = function(value, context) {\n return cb(value, context, Infinity);\n };\n\n // An internal function for creating assigner functions.\n var createAssigner = function(keysFunc, undefinedOnly) {\n return function(obj) {\n var length = arguments.length;\n if (length < 2 || obj == null) return obj;\n for (var index = 1; index < length; index++) {\n var source = arguments[index],\n keys = keysFunc(source),\n l = keys.length;\n for (var i = 0; i < l; i++) {\n var key = keys[i];\n if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];\n }\n }\n return obj;\n };\n };\n\n // An internal function for creating a new object that inherits from another.\n var baseCreate = function(prototype) {\n if (!_.isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n };\n\n var property = function(key) {\n return function(obj) {\n return obj == null ? void 0 : obj[key];\n };\n };\n\n // Helper for collection methods to determine whether a collection\n // should be iterated as an array or as an object\n // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength\n // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094\n var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;\n var getLength = property('length');\n var isArrayLike = function(collection) {\n var length = getLength(collection);\n return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;\n };\n\n // Collection Functions\n // --------------------\n\n // The cornerstone, an `each` implementation, aka `forEach`.\n // Handles raw objects in addition to array-likes. Treats all\n // sparse array-likes as if they were dense.\n _.each = _.forEach = function(obj, iteratee, context) {\n iteratee = optimizeCb(iteratee, context);\n var i, length;\n if (isArrayLike(obj)) {\n for (i = 0, length = obj.length; i < length; i++) {\n iteratee(obj[i], i, obj);\n }\n } else {\n var keys = _.keys(obj);\n for (i = 0, length = keys.length; i < length; i++) {\n iteratee(obj[keys[i]], keys[i], obj);\n }\n }\n return obj;\n };\n\n // Return the results of applying the iteratee to each element.\n _.map = _.collect = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n results = Array(length);\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n results[index] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Create a reducing function iterating left or right.\n function createReduce(dir) {\n // Optimized iterator function as using arguments.length\n // in the main function will deoptimize the, see #1991.\n function iterator(obj, iteratee, memo, keys, index, length) {\n for (; index >= 0 && index < length; index += dir) {\n var currentKey = keys ? keys[index] : index;\n memo = iteratee(memo, obj[currentKey], currentKey, obj);\n }\n return memo;\n }\n\n return function(obj, iteratee, memo, context) {\n iteratee = optimizeCb(iteratee, context, 4);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length,\n index = dir > 0 ? 0 : length - 1;\n // Determine the initial value if none is provided.\n if (arguments.length < 3) {\n memo = obj[keys ? keys[index] : index];\n index += dir;\n }\n return iterator(obj, iteratee, memo, keys, index, length);\n };\n }\n\n // **Reduce** builds up a single result from a list of values, aka `inject`,\n // or `foldl`.\n _.reduce = _.foldl = _.inject = createReduce(1);\n\n // The right-associative version of reduce, also known as `foldr`.\n _.reduceRight = _.foldr = createReduce(-1);\n\n // Return the first value which passes a truth test. Aliased as `detect`.\n _.find = _.detect = function(obj, predicate, context) {\n var key;\n if (isArrayLike(obj)) {\n key = _.findIndex(obj, predicate, context);\n } else {\n key = _.findKey(obj, predicate, context);\n }\n if (key !== void 0 && key !== -1) return obj[key];\n };\n\n // Return all the elements that pass a truth test.\n // Aliased as `select`.\n _.filter = _.select = function(obj, predicate, context) {\n var results = [];\n predicate = cb(predicate, context);\n _.each(obj, function(value, index, list) {\n if (predicate(value, index, list)) results.push(value);\n });\n return results;\n };\n\n // Return all the elements for which a truth test fails.\n _.reject = function(obj, predicate, context) {\n return _.filter(obj, _.negate(cb(predicate)), context);\n };\n\n // Determine whether all of the elements match a truth test.\n // Aliased as `all`.\n _.every = _.all = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (!predicate(obj[currentKey], currentKey, obj)) return false;\n }\n return true;\n };\n\n // Determine if at least one element in the object matches a truth test.\n // Aliased as `any`.\n _.some = _.any = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = !isArrayLike(obj) && _.keys(obj),\n length = (keys || obj).length;\n for (var index = 0; index < length; index++) {\n var currentKey = keys ? keys[index] : index;\n if (predicate(obj[currentKey], currentKey, obj)) return true;\n }\n return false;\n };\n\n // Determine if the array or object contains a given item (using `===`).\n // Aliased as `includes` and `include`.\n _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n if (typeof fromIndex != 'number' || guard) fromIndex = 0;\n return _.indexOf(obj, item, fromIndex) >= 0;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n var isFunc = _.isFunction(method);\n return _.map(obj, function(value) {\n var func = isFunc ? method : value[method];\n return func == null ? func : func.apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, _.property(key));\n };\n\n // Convenience version of a common use case of `filter`: selecting only objects\n // containing specific `key:value` pairs.\n _.where = function(obj, attrs) {\n return _.filter(obj, _.matcher(attrs));\n };\n\n // Convenience version of a common use case of `find`: getting the first object\n // containing specific `key:value` pairs.\n _.findWhere = function(obj, attrs) {\n return _.find(obj, _.matcher(attrs));\n };\n\n // Return the maximum element (or element-based computation).\n _.max = function(obj, iteratee, context) {\n var result = -Infinity, lastComputed = -Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value > result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed > lastComputed || computed === -Infinity && result === -Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iteratee, context) {\n var result = Infinity, lastComputed = Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = isArrayLike(obj) ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value < result) {\n result = value;\n }\n }\n } else {\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed < lastComputed || computed === Infinity && result === Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Shuffle a collection, using the modern version of the\n // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).\n _.shuffle = function(obj) {\n var set = isArrayLike(obj) ? obj : _.values(obj);\n var length = set.length;\n var shuffled = Array(length);\n for (var index = 0, rand; index < length; index++) {\n rand = _.random(0, index);\n if (rand !== index) shuffled[index] = shuffled[rand];\n shuffled[rand] = set[index];\n }\n return shuffled;\n };\n\n // Sample **n** random values from a collection.\n // If **n** is not specified, returns a single random element.\n // The internal `guard` argument allows it to work with `map`.\n _.sample = function(obj, n, guard) {\n if (n == null || guard) {\n if (!isArrayLike(obj)) obj = _.values(obj);\n return obj[_.random(obj.length - 1)];\n }\n return _.shuffle(obj).slice(0, Math.max(0, n));\n };\n\n // Sort the object's values by a criterion produced by an iteratee.\n _.sortBy = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value: value,\n index: index,\n criteria: iteratee(value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria;\n var b = right.criteria;\n if (a !== b) {\n if (a > b || a === void 0) return 1;\n if (a < b || b === void 0) return -1;\n }\n return left.index - right.index;\n }), 'value');\n };\n\n // An internal function used for aggregate \"group by\" operations.\n var group = function(behavior) {\n return function(obj, iteratee, context) {\n var result = {};\n iteratee = cb(iteratee, context);\n _.each(obj, function(value, index) {\n var key = iteratee(value, index, obj);\n behavior(result, value, key);\n });\n return result;\n };\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key].push(value); else result[key] = [value];\n });\n\n // Indexes the object's values by a criterion, similar to `groupBy`, but for\n // when you know that your index values will be unique.\n _.indexBy = group(function(result, value, key) {\n result[key] = value;\n });\n\n // Counts instances of an object that group by a certain criterion. Pass\n // either a string attribute to count by, or a function that returns the\n // criterion.\n _.countBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key]++; else result[key] = 1;\n });\n\n // Safely create a real, live array from anything iterable.\n _.toArray = function(obj) {\n if (!obj) return [];\n if (_.isArray(obj)) return slice.call(obj);\n if (isArrayLike(obj)) return _.map(obj, _.identity);\n return _.values(obj);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n if (obj == null) return 0;\n return isArrayLike(obj) ? obj.length : _.keys(obj).length;\n };\n\n // Split a collection into two arrays: one whose elements all satisfy the given\n // predicate, and one whose elements all do not satisfy the predicate.\n _.partition = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var pass = [], fail = [];\n _.each(obj, function(value, key, obj) {\n (predicate(value, key, obj) ? pass : fail).push(value);\n });\n return [pass, fail];\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head` and `take`. The **guard** check\n // allows it to work with `_.map`.\n _.first = _.head = _.take = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[0];\n return _.initial(array, array.length - n);\n };\n\n // Returns everything but the last entry of the array. Especially useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array.\n _.last = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[array.length - 1];\n return _.rest(array, Math.max(0, array.length - n));\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.\n // Especially useful on the arguments object. Passing an **n** will return\n // the rest N values in the array.\n _.rest = _.tail = _.drop = function(array, n, guard) {\n return slice.call(array, n == null || guard ? 1 : n);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, _.identity);\n };\n\n // Internal implementation of a recursive `flatten` function.\n var flatten = function(input, shallow, strict, startIndex) {\n var output = [], idx = 0;\n for (var i = startIndex || 0, length = getLength(input); i < length; i++) {\n var value = input[i];\n if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {\n //flatten current level of array or arguments object\n if (!shallow) value = flatten(value, shallow, strict);\n var j = 0, len = value.length;\n output.length += len;\n while (j < len) {\n output[idx++] = value[j++];\n }\n } else if (!strict) {\n output[idx++] = value;\n }\n }\n return output;\n };\n\n // Flatten out an array, either recursively (by default), or just one level.\n _.flatten = function(array, shallow) {\n return flatten(array, shallow, false);\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iteratee, context) {\n if (!_.isBoolean(isSorted)) {\n context = iteratee;\n iteratee = isSorted;\n isSorted = false;\n }\n if (iteratee != null) iteratee = cb(iteratee, context);\n var result = [];\n var seen = [];\n for (var i = 0, length = getLength(array); i < length; i++) {\n var value = array[i],\n computed = iteratee ? iteratee(value, i, array) : value;\n if (isSorted) {\n if (!i || seen !== computed) result.push(value);\n seen = computed;\n } else if (iteratee) {\n if (!_.contains(seen, computed)) {\n seen.push(computed);\n result.push(value);\n }\n } else if (!_.contains(result, value)) {\n result.push(value);\n }\n }\n return result;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(flatten(arguments, true, true));\n };\n\n // Produce an array that contains every item shared between all the\n // passed-in arrays.\n _.intersection = function(array) {\n var result = [];\n var argsLength = arguments.length;\n for (var i = 0, length = getLength(array); i < length; i++) {\n var item = array[i];\n if (_.contains(result, item)) continue;\n for (var j = 1; j < argsLength; j++) {\n if (!_.contains(arguments[j], item)) break;\n }\n if (j === argsLength) result.push(item);\n }\n return result;\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = flatten(arguments, true, true, 1);\n return _.filter(array, function(value){\n return !_.contains(rest, value);\n });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function() {\n return _.unzip(arguments);\n };\n\n // Complement of _.zip. Unzip accepts an array of arrays and groups\n // each array's elements on shared indices\n _.unzip = function(array) {\n var length = array && _.max(array, getLength).length || 0;\n var result = Array(length);\n\n for (var index = 0; index < length; index++) {\n result[index] = _.pluck(array, index);\n }\n return result;\n };\n\n // Converts lists into objects. Pass either a single array of `[key, value]`\n // pairs, or two parallel arrays of the same length -- one of keys, and one of\n // the corresponding values.\n _.object = function(list, values) {\n var result = {};\n for (var i = 0, length = getLength(list); i < length; i++) {\n if (values) {\n result[list[i]] = values[i];\n } else {\n result[list[i][0]] = list[i][1];\n }\n }\n return result;\n };\n\n // Generator function to create the findIndex and findLastIndex functions\n function createPredicateIndexFinder(dir) {\n return function(array, predicate, context) {\n predicate = cb(predicate, context);\n var length = getLength(array);\n var index = dir > 0 ? 0 : length - 1;\n for (; index >= 0 && index < length; index += dir) {\n if (predicate(array[index], index, array)) return index;\n }\n return -1;\n };\n }\n\n // Returns the first index on an array-like that passes a predicate test\n _.findIndex = createPredicateIndexFinder(1);\n _.findLastIndex = createPredicateIndexFinder(-1);\n\n // Use a comparator function to figure out the smallest index at which\n // an object should be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iteratee, context) {\n iteratee = cb(iteratee, context, 1);\n var value = iteratee(obj);\n var low = 0, high = getLength(array);\n while (low < high) {\n var mid = Math.floor((low + high) / 2);\n if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;\n }\n return low;\n };\n\n // Generator function to create the indexOf and lastIndexOf functions\n function createIndexFinder(dir, predicateFind, sortedIndex) {\n return function(array, item, idx) {\n var i = 0, length = getLength(array);\n if (typeof idx == 'number') {\n if (dir > 0) {\n i = idx >= 0 ? idx : Math.max(idx + length, i);\n } else {\n length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;\n }\n } else if (sortedIndex && idx && length) {\n idx = sortedIndex(array, item);\n return array[idx] === item ? idx : -1;\n }\n if (item !== item) {\n idx = predicateFind(slice.call(array, i, length), _.isNaN);\n return idx >= 0 ? idx + i : -1;\n }\n for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {\n if (array[idx] === item) return idx;\n }\n return -1;\n };\n }\n\n // Return the position of the first occurrence of an item in an array,\n // or -1 if the item is not included in the array.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);\n _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (stop == null) {\n stop = start || 0;\n start = 0;\n }\n step = step || 1;\n\n var length = Math.max(Math.ceil((stop - start) / step), 0);\n var range = Array(length);\n\n for (var idx = 0; idx < length; idx++, start += step) {\n range[idx] = start;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Determines whether to execute a function as a constructor\n // or a normal function with the provided arguments\n var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {\n if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);\n var self = baseCreate(sourceFunc.prototype);\n var result = sourceFunc.apply(self, args);\n if (_.isObject(result)) return result;\n return self;\n };\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if\n // available.\n _.bind = function(func, context) {\n if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');\n var args = slice.call(arguments, 2);\n var bound = function() {\n return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));\n };\n return bound;\n };\n\n // Partially apply a function by creating a version that has had some of its\n // arguments pre-filled, without changing its dynamic `this` context. _ acts\n // as a placeholder, allowing any combination of arguments to be pre-filled.\n _.partial = function(func) {\n var boundArgs = slice.call(arguments, 1);\n var bound = function() {\n var position = 0, length = boundArgs.length;\n var args = Array(length);\n for (var i = 0; i < length; i++) {\n args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];\n }\n while (position < arguments.length) args.push(arguments[position++]);\n return executeBound(func, bound, this, this, args);\n };\n return bound;\n };\n\n // Bind a number of an object's methods to that object. Remaining arguments\n // are the method names to be bound. Useful for ensuring that all callbacks\n // defined on an object belong to it.\n _.bindAll = function(obj) {\n var i, length = arguments.length, key;\n if (length <= 1) throw new Error('bindAll must be passed function names');\n for (i = 1; i < length; i++) {\n key = arguments[i];\n obj[key] = _.bind(obj[key], obj);\n }\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memoize = function(key) {\n var cache = memoize.cache;\n var address = '' + (hasher ? hasher.apply(this, arguments) : key);\n if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);\n return cache[address];\n };\n memoize.cache = {};\n return memoize;\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){\n return func.apply(null, args);\n }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack has\n // cleared.\n _.defer = _.partial(_.delay, _, 1);\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time. Normally, the throttled function will run\n // as much as it can, without ever going more than once per `wait` duration;\n // but if you'd like to disable the execution on the leading edge, pass\n // `{leading: false}`. To disable execution on the trailing edge, ditto.\n _.throttle = function(func, wait, options) {\n var context, args, result;\n var timeout = null;\n var previous = 0;\n if (!options) options = {};\n var later = function() {\n previous = options.leading === false ? 0 : _.now();\n timeout = null;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n };\n return function() {\n var now = _.now();\n if (!previous && options.leading === false) previous = now;\n var remaining = wait - (now - previous);\n context = this;\n args = arguments;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n }\n previous = now;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(later, remaining);\n }\n return result;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being called for\n // N milliseconds. If `immediate` is passed, trigger the function on the\n // leading edge, instead of the trailing.\n _.debounce = function(func, wait, immediate) {\n var timeout, args, context, timestamp, result;\n\n var later = function() {\n var last = _.now() - timestamp;\n\n if (last < wait && last >= 0) {\n timeout = setTimeout(later, wait - last);\n } else {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n }\n }\n };\n\n return function() {\n context = this;\n args = arguments;\n timestamp = _.now();\n var callNow = immediate && !timeout;\n if (!timeout) timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n context = args = null;\n }\n\n return result;\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return _.partial(wrapper, func);\n };\n\n // Returns a negated version of the passed-in predicate.\n _.negate = function(predicate) {\n return function() {\n return !predicate.apply(this, arguments);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var args = arguments;\n var start = args.length - 1;\n return function() {\n var i = start;\n var result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n };\n\n // Returns a function that will only be executed on and after the Nth call.\n _.after = function(times, func) {\n return function() {\n if (--times < 1) {\n return func.apply(this, arguments);\n }\n };\n };\n\n // Returns a function that will only be executed up to (but not including) the Nth call.\n _.before = function(times, func) {\n var memo;\n return function() {\n if (--times > 0) {\n memo = func.apply(this, arguments);\n }\n if (times <= 1) func = null;\n return memo;\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = _.partial(_.before, 2);\n\n // Object Functions\n // ----------------\n\n // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.\n var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n function collectNonEnumProps(obj, keys) {\n var nonEnumIdx = nonEnumerableProps.length;\n var constructor = obj.constructor;\n var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;\n\n // Constructor is a special case.\n var prop = 'constructor';\n if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);\n\n while (nonEnumIdx--) {\n prop = nonEnumerableProps[nonEnumIdx];\n if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {\n keys.push(prop);\n }\n }\n }\n\n // Retrieve the names of an object's own properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = function(obj) {\n if (!_.isObject(obj)) return [];\n if (nativeKeys) return nativeKeys(obj);\n var keys = [];\n for (var key in obj) if (_.has(obj, key)) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve all the property names of an object.\n _.allKeys = function(obj) {\n if (!_.isObject(obj)) return [];\n var keys = [];\n for (var key in obj) keys.push(key);\n // Ahem, IE < 9.\n if (hasEnumBug) collectNonEnumProps(obj, keys);\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var values = Array(length);\n for (var i = 0; i < length; i++) {\n values[i] = obj[keys[i]];\n }\n return values;\n };\n\n // Returns the results of applying the iteratee to each element of the object\n // In contrast to _.map it returns an object\n _.mapObject = function(obj, iteratee, context) {\n iteratee = cb(iteratee, context);\n var keys = _.keys(obj),\n length = keys.length,\n results = {},\n currentKey;\n for (var index = 0; index < length; index++) {\n currentKey = keys[index];\n results[currentKey] = iteratee(obj[currentKey], currentKey, obj);\n }\n return results;\n };\n\n // Convert an object into a list of `[key, value]` pairs.\n _.pairs = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var pairs = Array(length);\n for (var i = 0; i < length; i++) {\n pairs[i] = [keys[i], obj[keys[i]]];\n }\n return pairs;\n };\n\n // Invert the keys and values of an object. The values must be serializable.\n _.invert = function(obj) {\n var result = {};\n var keys = _.keys(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n result[obj[keys[i]]] = keys[i];\n }\n return result;\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = createAssigner(_.allKeys);\n\n // Assigns a given object with all the own properties in the passed-in object(s)\n // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n _.extendOwn = _.assign = createAssigner(_.keys);\n\n // Returns the first key on an object that passes a predicate test\n _.findKey = function(obj, predicate, context) {\n predicate = cb(predicate, context);\n var keys = _.keys(obj), key;\n for (var i = 0, length = keys.length; i < length; i++) {\n key = keys[i];\n if (predicate(obj[key], key, obj)) return key;\n }\n };\n\n // Return a copy of the object only containing the whitelisted properties.\n _.pick = function(object, oiteratee, context) {\n var result = {}, obj = object, iteratee, keys;\n if (obj == null) return result;\n if (_.isFunction(oiteratee)) {\n keys = _.allKeys(obj);\n iteratee = optimizeCb(oiteratee, context);\n } else {\n keys = flatten(arguments, false, false, 1);\n iteratee = function(value, key, obj) { return key in obj; };\n obj = Object(obj);\n }\n for (var i = 0, length = keys.length; i < length; i++) {\n var key = keys[i];\n var value = obj[key];\n if (iteratee(value, key, obj)) result[key] = value;\n }\n return result;\n };\n\n // Return a copy of the object without the blacklisted properties.\n _.omit = function(obj, iteratee, context) {\n if (_.isFunction(iteratee)) {\n iteratee = _.negate(iteratee);\n } else {\n var keys = _.map(flatten(arguments, false, false, 1), String);\n iteratee = function(value, key) {\n return !_.contains(keys, key);\n };\n }\n return _.pick(obj, iteratee, context);\n };\n\n // Fill in a given object with default properties.\n _.defaults = createAssigner(_.allKeys, true);\n\n // Creates an object that inherits from the given prototype object.\n // If additional properties are provided then they will be added to the\n // created object.\n _.create = function(prototype, props) {\n var result = baseCreate(prototype);\n if (props) _.extendOwn(result, props);\n return result;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Returns whether an object has a given set of `key:value` pairs.\n _.isMatch = function(object, attrs) {\n var keys = _.keys(attrs), length = keys.length;\n if (object == null) return !length;\n var obj = Object(object);\n for (var i = 0; i < length; i++) {\n var key = keys[i];\n if (attrs[key] !== obj[key] || !(key in obj)) return false;\n }\n return true;\n };\n\n\n // Internal recursive comparison function for `isEqual`.\n var eq = function(a, b, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) return a !== 0 || 1 / a === 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwrap any wrapped objects.\n if (a instanceof _) a = a._wrapped;\n if (b instanceof _) b = b._wrapped;\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case '[object RegExp]':\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return '' + a === '' + b;\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN\n if (+a !== +a) return +b !== +b;\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case '[object Date]':\n case '[object Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n }\n\n var areArrays = className === '[object Array]';\n if (!areArrays) {\n if (typeof a != 'object' || typeof b != 'object') return false;\n\n // Objects with different constructors are not equivalent, but `Object`s or `Array`s\n // from different frames are.\n var aCtor = a.constructor, bCtor = b.constructor;\n if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&\n _.isFunction(bCtor) && bCtor instanceof bCtor)\n && ('constructor' in a && 'constructor' in b)) {\n return false;\n }\n }\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n\n // Initializing stack of traversed objects.\n // It's done here since we only need them for objects and arrays comparison.\n aStack = aStack || [];\n bStack = bStack || [];\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) return bStack[length] === b;\n }\n\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n\n // Recursively compare objects and arrays.\n if (areArrays) {\n // Compare array lengths to determine if a deep comparison is necessary.\n length = a.length;\n if (length !== b.length) return false;\n // Deep compare the contents, ignoring non-numeric properties.\n while (length--) {\n if (!eq(a[length], b[length], aStack, bStack)) return false;\n }\n } else {\n // Deep compare objects.\n var keys = _.keys(a), key;\n length = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n if (_.keys(b).length !== length) return false;\n while (length--) {\n // Deep compare each member\n key = keys[length];\n if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return true;\n };\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (obj == null) return true;\n if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;\n return _.keys(obj).length === 0;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj.nodeType === 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) === '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n var type = typeof obj;\n return type === 'function' || type === 'object' && !!obj;\n };\n\n // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.\n _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {\n _['is' + name] = function(obj) {\n return toString.call(obj) === '[object ' + name + ']';\n };\n });\n\n // Define a fallback version of the method in browsers (ahem, IE < 9), where\n // there isn't any inspectable \"Arguments\" type.\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return _.has(obj, 'callee');\n };\n }\n\n // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,\n // IE 11 (#1621), and in Safari 8 (#1929).\n if (typeof /./ != 'function' && typeof Int8Array != 'object') {\n _.isFunction = function(obj) {\n return typeof obj == 'function' || false;\n };\n }\n\n // Is a given object a finite number?\n _.isFinite = function(obj) {\n return isFinite(obj) && !isNaN(parseFloat(obj));\n };\n\n // Is the given value `NaN`? (NaN is the only number which does not equal itself).\n _.isNaN = function(obj) {\n return _.isNumber(obj) && obj !== +obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) === '[object Boolean]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Shortcut function for checking if an object has a given property directly\n // on itself (in other words, not on a prototype).\n _.has = function(obj, key) {\n return obj != null && hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning the `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iteratees.\n _.identity = function(value) {\n return value;\n };\n\n // Predicate-generating functions. Often useful outside of Underscore.\n _.constant = function(value) {\n return function() {\n return value;\n };\n };\n\n _.noop = function(){};\n\n _.property = property;\n\n // Generates a function for a given object that returns a given property.\n _.propertyOf = function(obj) {\n return obj == null ? function(){} : function(key) {\n return obj[key];\n };\n };\n\n // Returns a predicate for checking whether an object has a given set of\n // `key:value` pairs.\n _.matcher = _.matches = function(attrs) {\n attrs = _.extendOwn({}, attrs);\n return function(obj) {\n return _.isMatch(obj, attrs);\n };\n };\n\n // Run a function **n** times.\n _.times = function(n, iteratee, context) {\n var accum = Array(Math.max(0, n));\n iteratee = optimizeCb(iteratee, context, 1);\n for (var i = 0; i < n; i++) accum[i] = iteratee(i);\n return accum;\n };\n\n // Return a random integer between min and max (inclusive).\n _.random = function(min, max) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n };\n\n // A (possibly faster) way to get the current timestamp as an integer.\n _.now = Date.now || function() {\n return new Date().getTime();\n };\n\n // List of HTML entities for escaping.\n var escapeMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`'\n };\n var unescapeMap = _.invert(escapeMap);\n\n // Functions for escaping and unescaping strings to/from HTML interpolation.\n var createEscaper = function(map) {\n var escaper = function(match) {\n return map[match];\n };\n // Regexes for identifying a key that needs to be escaped\n var source = '(?:' + _.keys(map).join('|') + ')';\n var testRegexp = RegExp(source);\n var replaceRegexp = RegExp(source, 'g');\n return function(string) {\n string = string == null ? '' : '' + string;\n return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;\n };\n };\n _.escape = createEscaper(escapeMap);\n _.unescape = createEscaper(unescapeMap);\n\n // If the value of the named `property` is a function then invoke it with the\n // `object` as context; otherwise, return it.\n _.result = function(object, property, fallback) {\n var value = object == null ? void 0 : object[property];\n if (value === void 0) {\n value = fallback;\n }\n return _.isFunction(value) ? value.call(object) : value;\n };\n\n // Generate a unique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = ++idCounter + '';\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /(.)^/;\n\n // Certain characters need to be escaped so that they can be put into a\n // string literal.\n var escapes = {\n \"'\": \"'\",\n '\\\\': '\\\\',\n '\\r': 'r',\n '\\n': 'n',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n var escaper = /\\\\|'|\\r|\\n|\\u2028|\\u2029/g;\n\n var escapeChar = function(match) {\n return '\\\\' + escapes[match];\n };\n\n // JavaScript micro-templating, similar to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n // NB: `oldSettings` only exists for backwards compatibility.\n _.template = function(text, settings, oldSettings) {\n if (!settings && oldSettings) settings = oldSettings;\n settings = _.defaults({}, settings, _.templateSettings);\n\n // Combine delimiters into one regular expression via alternation.\n var matcher = RegExp([\n (settings.escape || noMatch).source,\n (settings.interpolate || noMatch).source,\n (settings.evaluate || noMatch).source\n ].join('|') + '|$', 'g');\n\n // Compile the template source, escaping string literals appropriately.\n var index = 0;\n var source = \"__p+='\";\n text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {\n source += text.slice(index, offset).replace(escaper, escapeChar);\n index = offset + match.length;\n\n if (escape) {\n source += \"'+\\n((__t=(\" + escape + \"))==null?'':_.escape(__t))+\\n'\";\n } else if (interpolate) {\n source += \"'+\\n((__t=(\" + interpolate + \"))==null?'':__t)+\\n'\";\n } else if (evaluate) {\n source += \"';\\n\" + evaluate + \"\\n__p+='\";\n }\n\n // Adobe VMs need the match returned to produce the correct offest.\n return match;\n });\n source += \"';\\n\";\n\n // If a variable is not specified, place data values in local scope.\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = \"var __t,__p='',__j=Array.prototype.join,\" +\n \"print=function(){__p+=__j.call(arguments,'');};\\n\" +\n source + 'return __p;\\n';\n\n try {\n var render = new Function(settings.variable || 'obj', '_', source);\n } catch (e) {\n e.source = source;\n throw e;\n }\n\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n // Provide the compiled source as a convenience for precompilation.\n var argument = settings.variable || 'obj';\n template.source = 'function(' + argument + '){\\n' + source + '}';\n\n return template;\n };\n\n // Add a \"chain\" function. Start chaining a wrapped Underscore object.\n _.chain = function(obj) {\n var instance = _(obj);\n instance._chain = true;\n return instance;\n };\n\n // OOP\n // ---------------\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n\n // Helper function to continue chaining intermediate results.\n var result = function(instance, obj) {\n return instance._chain ? _(obj).chain() : obj;\n };\n\n // Add your own custom functions to the Underscore object.\n _.mixin = function(obj) {\n _.each(_.functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return result(this, func.apply(_, args));\n };\n });\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n var obj = this._wrapped;\n method.apply(obj, arguments);\n if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];\n return result(this, obj);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n _.each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n return result(this, method.apply(this._wrapped, arguments));\n };\n });\n\n // Extracts the result from a wrapped and chained object.\n _.prototype.value = function() {\n return this._wrapped;\n };\n\n // Provide unwrapping proxy for some methods used in engine operations\n // such as arithmetic and JSON stringification.\n _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;\n\n _.prototype.toString = function() {\n return '' + this._wrapped;\n };\n\n // AMD registration happens at the end for compatibility with AMD loaders\n // that may not enforce next-turn semantics on modules. Even though general\n // practice for AMD registration is to be anonymous, underscore registers\n // as a named module because, like jQuery, it is a base library that is\n // popular enough to be bundled in a third party lib, but not be part of\n // an AMD load request. Those cases could generate an error when an\n // anonymous define() is called outside of a loader request.\n if (typeof define === 'function' && define.amd) {\n define('underscore', [], function() {\n return _;\n });\n }\n}.call(this));\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/underscore/underscore.js\n// module id = 0\n// module chunks = 0","var _ = require('underscore');\nvar Promise = require('es6-promise').Promise;\n\nPromise._continueWhile = function(predicate, asyncFunction) {\n if (predicate()) {\n return asyncFunction().then(function() {\n return Promise._continueWhile(predicate, asyncFunction);\n });\n }\n return Promise.resolve();\n};\n\nmodule.exports = Promise;\n\n\n\n// WEBPACK FOOTER //\n// ./src/promise.js","const request = require('superagent');\nconst debug = require('debug')('leancloud:request');\nconst md5 = require('md5');\nconst Promise = require('./promise');\nconst Cache = require('./cache');\nconst AVError = require('./error');\nconst AV = require('./av');\nconst _ = require('underscore');\nconst {\n getSessionToken,\n} = require('./utils');\n\nlet getServerURLPromise;\n\n// 服务器请求的节点 host\nconst API_HOST = {\n cn: 'https://api.leancloud.cn',\n us: 'https://us-api.leancloud.cn',\n};\n\n// 计算 X-LC-Sign 的签名方法\nconst sign = (key, isMasterKey) => {\n const now = new Date().getTime();\n const signature = md5(now + key);\n if (isMasterKey) {\n return `${signature},${now},master`;\n }\n return `${signature},${now}`;\n};\n\nlet requestsCount = 0;\n\nconst ajax = (method, resourceUrl, data, headers = {}, onprogress) => {\n const count = requestsCount++;\n\n debug(`request(${count})`, method, resourceUrl, data, headers);\n\n return new Promise((resolve, reject) => {\n const req = request(method, resourceUrl)\n .set(headers)\n .send(data);\n if (onprogress) {\n req.on('progress', onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(`response(${count})`, res.status, res.body || res.text, res.header);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n return resolve(res.body);\n });\n });\n};\n\nconst setAppKey = (headers, signKey) => {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.applicationKey);\n } else {\n headers['X-LC-Key'] = AV.applicationKey;\n }\n};\n\nconst setHeaders = (authOptions = {}, signKey) => {\n const headers = {\n 'X-LC-Id': AV.applicationId,\n 'Content-Type': 'application/json;charset=UTF-8',\n };\n let useMasterKey = false;\n if (typeof authOptions.useMasterKey === 'boolean') {\n useMasterKey = authOptions.useMasterKey;\n } else if (typeof AV._useMasterKey === 'boolean') {\n useMasterKey = AV._useMasterKey;\n }\n if (useMasterKey) {\n if (AV.masterKey) {\n if (signKey) {\n headers['X-LC-Sign'] = sign(AV.masterKey, true);\n } else {\n headers['X-LC-Key'] = `${AV.masterKey},master`;\n }\n } else {\n console.warn('masterKey is not set, fall back to use appKey');\n setAppKey(headers, signKey);\n }\n } else {\n setAppKey(headers, signKey);\n }\n if (AV.hookKey) {\n headers['X-LC-Hook-Key'] = AV.hookKey;\n }\n if (AV._config.applicationProduction !== null) {\n headers['X-LC-Prod'] = String(AV._config.applicationProduction);\n }\n headers[!process.env.CLIENT_PLATFORM ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent;\n\n return Promise.resolve().then(() => {\n // Pass the session token\n const sessionToken = getSessionToken(authOptions);\n if (sessionToken) {\n headers['X-LC-Session'] = sessionToken;\n } else if (!AV._config.disableCurrentUser) {\n return AV.User.currentAsync().then((currentUser) => {\n if (currentUser && currentUser._sessionToken) {\n headers['X-LC-Session'] = currentUser._sessionToken;\n }\n return headers;\n });\n }\n return headers;\n });\n};\n\nconst createApiUrl = (route, className, objectId, method, dataObject) => {\n // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉\n if (AV.serverURL) {\n AV._config.APIServerURL = AV.serverURL;\n console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.');\n }\n\n let apiURL = AV._config.APIServerURL || API_HOST.cn;\n\n if (apiURL.charAt(apiURL.length - 1) !== '/') {\n apiURL += '/';\n }\n apiURL += `1.1/${route}`;\n if (className) {\n apiURL += `/${className}`;\n }\n if (objectId) {\n apiURL += `/${objectId}`;\n }\n if ((route === 'users' || route === 'classes') && dataObject) {\n apiURL += '?';\n if (dataObject._fetchWhenSave) {\n delete dataObject._fetchWhenSave;\n apiURL += '&new=true';\n }\n if (dataObject._where) {\n apiURL += `&where=${encodeURIComponent(JSON.stringify(dataObject._where))}`;\n delete dataObject._where;\n }\n }\n\n if (method.toLowerCase() === 'get') {\n if (apiURL.indexOf('?') === -1) {\n apiURL += '?';\n }\n for (const k in dataObject) {\n if (typeof dataObject[k] === 'object') {\n dataObject[k] = JSON.stringify(dataObject[k]);\n }\n apiURL += `&${k}=${encodeURIComponent(dataObject[k])}`;\n }\n }\n\n return apiURL;\n};\n\nconst cacheServerURL = (serverURL, ttl) => {\n if (typeof ttl !== 'number') {\n ttl = 3600;\n }\n return Cache.setAsync('APIServerURL', serverURL, ttl * 1000);\n};\n\n// handle AV._request Error\nconst handleError = (error) => {\n return new Promise((resolve, reject) => {\n /**\n When API request need to redirect to the right location,\n can't use browser redirect by http status 307, as the reason of CORS,\n so API server response http status 410 and the param \"location\" for this case.\n */\n if (error.statusCode === 410) {\n cacheServerURL(error.response.api_server, error.response.ttl).then(() => {\n resolve(error.response.location);\n }).catch(reject);\n } else {\n let errorJSON = {\n code: error.code || -1,\n error: error.message || error.responseText\n };\n if (error.response && error.response.code) {\n errorJSON = error.response;\n } else if (error.responseText) {\n try {\n errorJSON = JSON.parse(error.responseText);\n } catch (e) {\n // If we fail to parse the error text, that's okay.\n }\n }\n\n // Transform the error into an instance of AVError by trying to parse\n // the error string as JSON.\n reject(new AVError(errorJSON.code, errorJSON.error));\n }\n });\n};\n\nconst setServerUrl = (serverURL) => {\n AV._config.APIServerURL = `https://${serverURL}`;\n\n // 根据新 URL 重新设置区域\n const newRegion = _.findKey(API_HOST, item => item === AV._config.APIServerURL);\n if (newRegion) {\n AV._config.region = newRegion;\n }\n};\n\nconst refreshServerUrlByRouter = () => {\n const url = `https://app-router.leancloud.cn/1/route?appId=${AV.applicationId}`;\n return ajax('get', url).then(servers => {\n if (servers.api_server) {\n setServerUrl(servers.api_server);\n return cacheServerURL(servers.api_server, servers.ttl);\n }\n }, error => {\n // bypass all non-4XX errors\n if (error.statusCode >= 400 && error.statusCode < 500) {\n throw error;\n }\n });\n};\n\nconst setServerUrlByRegion = (region = 'cn') => {\n getServerURLPromise = new Promise((resolve, reject) => {\n // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router\n if (AV._config.APIServerURL) {\n resolve();\n return;\n }\n // if not china server region, do not use router\n if (region === 'cn') {\n return Cache.getAsync('APIServerURL').then((serverURL) => {\n if (serverURL) {\n setServerUrl(serverURL);\n } else {\n return refreshServerUrlByRouter();\n }\n }).then(() => {\n resolve();\n }).catch((error) => {\n reject(error);\n });\n } else {\n AV._config.region = region;\n AV._config.APIServerURL = API_HOST[region];\n resolve();\n }\n });\n};\n\n/**\n * route is classes, users, login, etc.\n * objectId is null if there is no associated objectId.\n * method is the http method for the REST API.\n * dataObject is the payload as an object, or null if there is none.\n * @ignore\n */\nconst AVRequest = (route, className, objectId, method, dataObject = {}, authOptions) => {\n if (!AV.applicationId) {\n throw new Error('You must specify your applicationId using AV.init()');\n }\n\n if (!AV.applicationKey && !AV.masterKey) {\n throw new Error('You must specify a AppKey using AV.init()');\n }\n\n if (!getServerURLPromise) {\n return Promise.reject(new Error('Not initialized'));\n }\n return getServerURLPromise.then(() => {\n const apiURL = createApiUrl(route, className, objectId, method, dataObject);\n return setHeaders(authOptions, route !== 'bigquery').then(\n headers => ajax(method, apiURL, dataObject, headers)\n .then(\n null,\n res => handleError(res)\n .then(location => ajax(method, location, dataObject, headers))\n )\n );\n });\n};\n\nmodule.exports = {\n ajax,\n request: AVRequest,\n setServerUrlByRegion,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/request.js","const _ = require('underscore');\n\n/**\n * @class AV.Error\n */\n\nfunction AVError(code, message) {\n const error = new Error(message);\n error.code = code;\n return error;\n}\n\n_.extend(AVError, /** @lends AV.Error */ {\n /**\n * Error code indicating some error other than those enumerated here.\n * @constant\n */\n OTHER_CAUSE: -1,\n\n /**\n * Error code indicating that something has gone wrong with the server.\n * If you get this error code, it is AV's fault. Contact us at\n * https://avoscloud.com/help\n * @constant\n */\n INTERNAL_SERVER_ERROR: 1,\n\n /**\n * Error code indicating the connection to the AV servers failed.\n * @constant\n */\n CONNECTION_FAILED: 100,\n\n /**\n * Error code indicating the specified object doesn't exist.\n * @constant\n */\n OBJECT_NOT_FOUND: 101,\n\n /**\n * Error code indicating you tried to query with a datatype that doesn't\n * support it, like exact matching an array or object.\n * @constant\n */\n INVALID_QUERY: 102,\n\n /**\n * Error code indicating a missing or invalid classname. Classnames are\n * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the\n * only valid characters.\n * @constant\n */\n INVALID_CLASS_NAME: 103,\n\n /**\n * Error code indicating an unspecified object id.\n * @constant\n */\n MISSING_OBJECT_ID: 104,\n\n /**\n * Error code indicating an invalid key name. Keys are case-sensitive. They\n * must start with a letter, and a-zA-Z0-9_ are the only valid characters.\n * @constant\n */\n INVALID_KEY_NAME: 105,\n\n /**\n * Error code indicating a malformed pointer. You should not see this unless\n * you have been mucking about changing internal AV code.\n * @constant\n */\n INVALID_POINTER: 106,\n\n /**\n * Error code indicating that badly formed JSON was received upstream. This\n * either indicates you have done something unusual with modifying how\n * things encode to JSON, or the network is failing badly.\n * @constant\n */\n INVALID_JSON: 107,\n\n /**\n * Error code indicating that the feature you tried to access is only\n * available internally for testing purposes.\n * @constant\n */\n COMMAND_UNAVAILABLE: 108,\n\n /**\n * You must call AV.initialize before using the AV library.\n * @constant\n */\n NOT_INITIALIZED: 109,\n\n /**\n * Error code indicating that a field was set to an inconsistent type.\n * @constant\n */\n INCORRECT_TYPE: 111,\n\n /**\n * Error code indicating an invalid channel name. A channel name is either\n * an empty string (the broadcast channel) or contains only a-zA-Z0-9_\n * characters.\n * @constant\n */\n INVALID_CHANNEL_NAME: 112,\n\n /**\n * Error code indicating that push is misconfigured.\n * @constant\n */\n PUSH_MISCONFIGURED: 115,\n\n /**\n * Error code indicating that the object is too large.\n * @constant\n */\n OBJECT_TOO_LARGE: 116,\n\n /**\n * Error code indicating that the operation isn't allowed for clients.\n * @constant\n */\n OPERATION_FORBIDDEN: 119,\n\n /**\n * Error code indicating the result was not found in the cache.\n * @constant\n */\n CACHE_MISS: 120,\n\n /**\n * Error code indicating that an invalid key was used in a nested\n * JSONObject.\n * @constant\n */\n INVALID_NESTED_KEY: 121,\n\n /**\n * Error code indicating that an invalid filename was used for AVFile.\n * A valid file name contains only a-zA-Z0-9_. characters and is between 1\n * and 128 characters.\n * @constant\n */\n INVALID_FILE_NAME: 122,\n\n /**\n * Error code indicating an invalid ACL was provided.\n * @constant\n */\n INVALID_ACL: 123,\n\n /**\n * Error code indicating that the request timed out on the server. Typically\n * this indicates that the request is too expensive to run.\n * @constant\n */\n TIMEOUT: 124,\n\n /**\n * Error code indicating that the email address was invalid.\n * @constant\n */\n INVALID_EMAIL_ADDRESS: 125,\n\n /**\n * Error code indicating a missing content type.\n * @constant\n */\n MISSING_CONTENT_TYPE: 126,\n\n /**\n * Error code indicating a missing content length.\n * @constant\n */\n MISSING_CONTENT_LENGTH: 127,\n\n /**\n * Error code indicating an invalid content length.\n * @constant\n */\n INVALID_CONTENT_LENGTH: 128,\n\n /**\n * Error code indicating a file that was too large.\n * @constant\n */\n FILE_TOO_LARGE: 129,\n\n /**\n * Error code indicating an error saving a file.\n * @constant\n */\n FILE_SAVE_ERROR: 130,\n\n /**\n * Error code indicating an error deleting a file.\n * @constant\n */\n FILE_DELETE_ERROR: 153,\n\n /**\n * Error code indicating that a unique field was given a value that is\n * already taken.\n * @constant\n */\n DUPLICATE_VALUE: 137,\n\n /**\n * Error code indicating that a role's name is invalid.\n * @constant\n */\n INVALID_ROLE_NAME: 139,\n\n /**\n * Error code indicating that an application quota was exceeded. Upgrade to\n * resolve.\n * @constant\n */\n EXCEEDED_QUOTA: 140,\n\n /**\n * Error code indicating that a Cloud Code script failed.\n * @constant\n */\n SCRIPT_FAILED: 141,\n\n /**\n * Error code indicating that a Cloud Code validation failed.\n * @constant\n */\n VALIDATION_ERROR: 142,\n\n /**\n * Error code indicating that invalid image data was provided.\n * @constant\n */\n INVALID_IMAGE_DATA: 150,\n\n /**\n * Error code indicating an unsaved file.\n * @constant\n */\n UNSAVED_FILE_ERROR: 151,\n\n /**\n * Error code indicating an invalid push time.\n */\n INVALID_PUSH_TIME_ERROR: 152,\n\n /**\n * Error code indicating that the username is missing or empty.\n * @constant\n */\n USERNAME_MISSING: 200,\n\n /**\n * Error code indicating that the password is missing or empty.\n * @constant\n */\n PASSWORD_MISSING: 201,\n\n /**\n * Error code indicating that the username has already been taken.\n * @constant\n */\n USERNAME_TAKEN: 202,\n\n /**\n * Error code indicating that the email has already been taken.\n * @constant\n */\n EMAIL_TAKEN: 203,\n\n /**\n * Error code indicating that the email is missing, but must be specified.\n * @constant\n */\n EMAIL_MISSING: 204,\n\n /**\n * Error code indicating that a user with the specified email was not found.\n * @constant\n */\n EMAIL_NOT_FOUND: 205,\n\n /**\n * Error code indicating that a user object without a valid session could\n * not be altered.\n * @constant\n */\n SESSION_MISSING: 206,\n\n /**\n * Error code indicating that a user can only be created through signup.\n * @constant\n */\n MUST_CREATE_USER_THROUGH_SIGNUP: 207,\n\n /**\n * Error code indicating that an an account being linked is already linked\n * to another user.\n * @constant\n */\n ACCOUNT_ALREADY_LINKED: 208,\n\n /**\n * Error code indicating that a user cannot be linked to an account because\n * that account's id could not be found.\n * @constant\n */\n LINKED_ID_MISSING: 250,\n\n /**\n * Error code indicating that a user with a linked (e.g. Facebook) account\n * has an invalid session.\n * @constant\n */\n INVALID_LINKED_SESSION: 251,\n\n /**\n * Error code indicating that a service being linked (e.g. Facebook or\n * Twitter) is unsupported.\n * @constant\n */\n UNSUPPORTED_SERVICE: 252,\n /**\n * Error code indicating a real error code is unavailable because\n * we had to use an XDomainRequest object to allow CORS requests in\n * Internet Explorer, which strips the body from HTTP responses that have\n * a non-2XX status code.\n * @constant\n */\n X_DOMAIN_REQUEST: 602,\n});\n\nmodule.exports = AVError;\n\n\n\n// WEBPACK FOOTER //\n// ./src/error.js","const _ = require('underscore');\n\n// Helper function to check null or undefined.\nconst isNullOrUndefined = (x) => _.isNull(x) || _.isUndefined(x);\n\nconst ensureArray = target => {\n if (_.isArray(target)) {\n return target;\n }\n if (target === undefined || target === null) {\n return [];\n }\n return [target];\n};\n\nconst getSessionToken = (authOptions) => {\n if (authOptions.sessionToken) {\n return authOptions.sessionToken;\n }\n if (\n authOptions.user && typeof authOptions.user.getSessionToken === 'function'\n ) {\n return authOptions.user.getSessionToken();\n }\n};\n\nconst tap = interceptor => value => ((interceptor(value), value));\n\nmodule.exports = {\n isNullOrUndefined,\n ensureArray,\n getSessionToken,\n tap,\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/index.js","/**\n * This is the web browser implementation of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = require('./debug');\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = 'undefined' != typeof chrome\n && 'undefined' != typeof chrome.storage\n ? chrome.storage.local\n : localstorage();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n 'lightseagreen',\n 'forestgreen',\n 'goldenrod',\n 'dodgerblue',\n 'darkorchid',\n 'crimson'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') {\n return true;\n }\n\n // is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) ||\n // is firebug? http://stackoverflow.com/a/398120/376773\n (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||\n // is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n // double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nexports.formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (err) {\n return '[UnexpectedJSONParseError]: ' + err.message;\n }\n};\n\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n var useColors = this.useColors;\n\n args[0] = (useColors ? '%c' : '')\n + this.namespace\n + (useColors ? ' %c' : ' ')\n + args[0]\n + (useColors ? '%c ' : ' ')\n + '+' + exports.humanize(this.diff);\n\n if (!useColors) return;\n\n var c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit')\n\n // the final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n var index = 0;\n var lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, function(match) {\n if ('%%' === match) return;\n index++;\n if ('%c' === match) {\n // we only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n\n args.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.log()` when available.\n * No-op when `console.log` is not a \"function\".\n *\n * @api public\n */\n\nfunction log() {\n // this hackery is required for IE8/9, where\n // the `console.log` function doesn't have 'apply'\n return 'object' === typeof console\n && console.log\n && Function.prototype.apply.call(console.log, console, arguments);\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\n\nfunction save(namespaces) {\n try {\n if (null == namespaces) {\n exports.storage.removeItem('debug');\n } else {\n exports.storage.debug = namespaces;\n }\n } catch(e) {}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n var r;\n try {\n r = exports.storage.debug;\n } catch(e) {}\n\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof process !== 'undefined' && 'env' in process) {\n r = process.env.DEBUG;\n }\n\n return r;\n}\n\n/**\n * Enable namespaces listed in `localStorage.debug` initially.\n */\n\nexports.enable(load());\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n try {\n return window.localStorage;\n } catch (e) {}\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/browser.js\n// module id = 5\n// module chunks = 0","const _ = require('underscore');\nconst userAgent = require('./ua');\nconst {\n isNullOrUndefined,\n} = require('./utils');\n\nconst AV = global.AV || {};\n\n// All internal configuration items\nAV._config = AV._config || {};\nconst AVConfig = AV._config;\n\n_.extend(AVConfig, {\n\n // 服务器节点地区,默认中国大陆\n region: 'cn',\n\n // 服务器的 URL,默认初始化时被设置为大陆节点地址\n APIServerURL: AVConfig.APIServerURL || '',\n\n // 禁用 currentUser,通常用于多用户环境\n disableCurrentUser: false,\n\n // Internal config can modifie the UserAgent\n userAgent,\n\n // set production environment or test environment\n // 1: production environment, 0: test environment, null: default environment\n applicationProduction: null,\n});\n\n/**\n * Contains all AV API classes and functions.\n * @namespace AV\n */\n\n// Helpers\n// -------\n\n// Shared empty constructor function to aid in prototype-chain creation.\nvar EmptyConstructor = function() {};\n\n// Helper function to correctly set up the prototype chain, for subclasses.\n// Similar to `goog.inherits`, but uses a hash of prototype properties and\n// class properties to be extended.\nvar inherits = function(parent, protoProps, staticProps) {\n var child;\n\n // The constructor function for the new subclass is either defined by you\n // (the \"constructor\" property in your `extend` definition), or defaulted\n // by us to simply call the parent's constructor.\n if (protoProps && protoProps.hasOwnProperty('constructor')) {\n child = protoProps.constructor;\n } else {\n /** @ignore */\n child = function(){ parent.apply(this, arguments); };\n }\n\n // Inherit class (static) properties from parent.\n _.extend(child, parent);\n\n // Set the prototype chain to inherit from `parent`, without calling\n // `parent`'s constructor function.\n EmptyConstructor.prototype = parent.prototype;\n child.prototype = new EmptyConstructor();\n\n // Add prototype properties (instance properties) to the subclass,\n // if supplied.\n if (protoProps) {\n _.extend(child.prototype, protoProps);\n }\n\n // Add static properties to the constructor function, if supplied.\n if (staticProps) {\n _.extend(child, staticProps);\n }\n\n // Correctly set child's `prototype.constructor`.\n child.prototype.constructor = child;\n\n // Set a convenience property in case the parent's prototype is\n // needed later.\n child.__super__ = parent.prototype;\n\n return child;\n};\n\n/**\n * Call this method to set production environment variable.\n * @function AV.setProduction\n * @param {Boolean} production True is production environment,and\n * it's true by default.\n */\nAV.setProduction = (production) => {\n if (!isNullOrUndefined(production)) {\n AVConfig.applicationProduction = production ? 1 : 0;\n } else {\n // change to default value\n AVConfig.applicationProduction = null;\n }\n};\n\n/**\n * Returns prefix for localStorage keys used by this instance of AV.\n * @param {String} path The relative suffix to append to it.\n * null or undefined is treated as the empty string.\n * @return {String} The full key name.\n * @private\n */\nAV._getAVPath = function(path) {\n if (!AV.applicationId) {\n throw new Error(\"You need to call AV.initialize before using AV.\");\n }\n if (!path) {\n path = \"\";\n }\n if (!_.isString(path)) {\n throw new Error(\"Tried to get a localStorage path that wasn't a String.\");\n }\n if (path[0] === \"/\") {\n path = path.substring(1);\n }\n return \"AV/\" + AV.applicationId + \"/\" + path;\n};\n\n/**\n * Returns the unique string for this app on this machine.\n * Gets reset when localStorage is cleared.\n * @private\n */\nAV._installationId = null;\nAV._getInstallationId = function() {\n // See if it's cached in RAM.\n if (AV._installationId) {\n return AV.Promise.resolve(AV._installationId);\n }\n\n // Try to get it from localStorage.\n var path = AV._getAVPath(\"installationId\");\n return AV.localStorage.getItemAsync(path).then(function(_installationId){\n AV._installationId = _installationId;\n if (!AV._installationId) {\n // It wasn't in localStorage, so create a new one.\n var hexOctet = function() {\n return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);\n };\n AV._installationId = (\n hexOctet() + hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + \"-\" +\n hexOctet() + hexOctet() + hexOctet());\n return AV.localStorage.setItemAsync(path, AV._installationId);\n }\n else {\n return _installationId;\n }\n });\n};\n\nAV._parseDate = function(iso8601) {\n var regexp = new RegExp(\n \"^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})\" + \"T\" +\n \"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\" +\n \"(.([0-9]+))?\" + \"Z$\");\n var match = regexp.exec(iso8601);\n if (!match) {\n return null;\n }\n\n var year = match[1] || 0;\n var month = (match[2] || 1) - 1;\n var day = match[3] || 0;\n var hour = match[4] || 0;\n var minute = match[5] || 0;\n var second = match[6] || 0;\n var milli = match[8] || 0;\n\n return new Date(Date.UTC(year, month, day, hour, minute, second, milli));\n};\n\n// A self-propagating extend function.\nAV._extend = function(protoProps, classProps) {\n var child = inherits(this, protoProps, classProps);\n child.extend = this.extend;\n return child;\n};\n\n// Helper function to get a value from a Backbone object as a property\n// or as a function.\nAV._getValue = function(object, prop) {\n if (!(object && object[prop])) {\n return null;\n }\n return _.isFunction(object[prop]) ? object[prop]() : object[prop];\n};\n\n/**\n * Converts a value in a AV Object into the appropriate representation.\n * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object)\n * if seenObjects is falsey. Otherwise any AV.Objects not in\n * seenObjects will be fully embedded rather than encoded\n * as a pointer. This array will be used to prevent going into an infinite\n * loop because we have circular references. If \n * is set, then none of the AV Objects that are serialized can be dirty.\n * @private\n */\nAV._encode = function(value, seenObjects, disallowObjects) {\n if (value instanceof AV.Object) {\n if (disallowObjects) {\n throw new Error(\"AV.Objects not allowed here\");\n }\n if (!seenObjects || _.include(seenObjects, value) || !value._hasData) {\n return value._toPointer();\n }\n if (!value.dirty()) {\n seenObjects = seenObjects.concat(value);\n return AV._encode(value._toFullJSON(seenObjects),\n seenObjects,\n disallowObjects);\n }\n throw new Error(\"Tried to save an object with a pointer to a new, unsaved object.\");\n }\n if (value instanceof AV.ACL) {\n return value.toJSON();\n }\n if (_.isDate(value)) {\n return { \"__type\": \"Date\", \"iso\": value.toJSON() };\n }\n if (value instanceof AV.GeoPoint) {\n return value.toJSON();\n }\n if (_.isArray(value)) {\n return _.map(value, function(x) {\n return AV._encode(x, seenObjects, disallowObjects);\n });\n }\n if (_.isRegExp(value)) {\n return value.source;\n }\n if (value instanceof AV.Relation) {\n return value.toJSON();\n }\n if (value instanceof AV.Op) {\n return value.toJSON();\n }\n if (value instanceof AV.File) {\n if (!value.url() && !value.id) {\n throw new Error(\"Tried to save an object containing an unsaved file.\");\n }\n return value._toFullJSON();\n }\n if (_.isObject(value)) {\n return _.mapObject(value, (v, k) => AV._encode(v, seenObjects, disallowObjects));\n }\n return value;\n};\n\n/**\n * The inverse function of AV._encode.\n * @private\n */\nAV._decode = function(value, key) {\n if (!_.isObject(value) || _.isDate(value)) {\n return value;\n }\n if (_.isArray(value)) {\n return _.map(value, v => AV._decode(v));\n }\n if (value instanceof AV.Object) {\n return value;\n }\n if (value instanceof AV.File) {\n return value;\n }\n if (value instanceof AV.Op) {\n return value;\n }\n if (value instanceof AV.GeoPoint) {\n return value;\n }\n if (value instanceof AV.ACL) {\n return value;\n }\n if (key === 'ACL') {\n return new AV.ACL(value);\n }\n if (value.__op) {\n return AV.Op._decode(value);\n }\n var className;\n if (value.__type === \"Pointer\") {\n className = value.className;\n var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n if(Object.keys(value).length > 3) {\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n pointer._finishFetch(v, true);\n }else{\n pointer._finishFetch({ objectId: value.objectId }, false);\n }\n return pointer;\n }\n if (value.__type === \"Object\") {\n // It's an Object included in a query result.\n className = value.className;\n const v = _.clone(value);\n delete v.__type;\n delete v.className;\n var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n object._finishFetch(v, true);\n return object;\n }\n if (value.__type === \"Date\") {\n return AV._parseDate(value.iso);\n }\n if (value.__type === \"GeoPoint\") {\n return new AV.GeoPoint({\n latitude: value.latitude,\n longitude: value.longitude\n });\n }\n if (value.__type === \"Relation\") {\n if (!key) throw new Error('key missing decoding a Relation');\n var relation = new AV.Relation(null, key);\n relation.targetClassName = value.className;\n return relation;\n }\n if (value.__type === 'File') {\n var file = new AV.File(value.name);\n const v = _.clone(value);\n delete v.__type;\n file._finishFetch(v);\n return file;\n }\n return _.mapObject(value, AV._decode);\n};\n\nAV._encodeObjectOrArray = function(value) {\n var encodeAVObject = function(object) {\n if (object && object._toFullJSON){\n object = object._toFullJSON([]);\n }\n\n return _.mapObject(object, function(value) {\n return AV._encode(value, []);\n });\n };\n\n if (_.isArray(value)) {\n return value.map(function(object) {\n return encodeAVObject(object);\n });\n } else {\n return encodeAVObject(value);\n }\n};\n\nAV._arrayEach = _.each;\n\n/**\n * Does a deep traversal of every item in object, calling func on every one.\n * @param {Object} object The object or array to traverse deeply.\n * @param {Function} func The function to call for every item. It will\n * be passed the item as an argument. If it returns a truthy value, that\n * value will replace the item in its parent container.\n * @returns {} the result of calling func on the top-level object itself.\n * @private\n */\nAV._traverse = function(object, func, seen) {\n if (object instanceof AV.Object) {\n seen = seen || [];\n if (_.indexOf(seen, object) >= 0) {\n // We've already visited this object in this call.\n return;\n }\n seen.push(object);\n AV._traverse(object.attributes, func, seen);\n return func(object);\n }\n if (object instanceof AV.Relation || object instanceof AV.File) {\n // Nothing needs to be done, but we don't want to recurse into the\n // object's parent infinitely, so we catch this case.\n return func(object);\n }\n if (_.isArray(object)) {\n _.each(object, function(child, index) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[index] = newChild;\n }\n });\n return func(object);\n }\n if (_.isObject(object)) {\n AV._each(object, function(child, key) {\n var newChild = AV._traverse(child, func, seen);\n if (newChild) {\n object[key] = newChild;\n }\n });\n return func(object);\n }\n return func(object);\n};\n\n/**\n * This is like _.each, except:\n * * it doesn't work for so-called array-like objects,\n * * it does work for dictionaries with a \"length\" attribute.\n * @private\n */\nAV._objectEach = AV._each = function(obj, callback) {\n if (_.isObject(obj)) {\n _.each(_.keys(obj), function(key) {\n callback(obj[key], key);\n });\n } else {\n _.each(obj, callback);\n }\n};\n\nmodule.exports = AV;\n\n\n\n// WEBPACK FOOTER //\n// ./src/av.js","/**\n * Root reference for iframes.\n */\n\nvar root;\nif (typeof window !== 'undefined') { // Browser window\n root = window;\n} else if (typeof self !== 'undefined') { // Web Worker\n root = self;\n} else { // Other environments\n console.warn(\"Using browser-only version of superagent in non-browser environment\");\n root = this;\n}\n\nvar Emitter = require('component-emitter');\nvar RequestBase = require('./request-base');\nvar isObject = require('./is-object');\nvar isFunction = require('./is-function');\nvar ResponseBase = require('./response-base');\nvar shouldRetry = require('./should-retry');\n\n/**\n * Noop.\n */\n\nfunction noop(){};\n\n/**\n * Expose `request`.\n */\n\nvar request = exports = module.exports = function(method, url) {\n // callback\n if ('function' == typeof url) {\n return new exports.Request('GET', method).end(url);\n }\n\n // url first\n if (1 == arguments.length) {\n return new exports.Request('GET', method);\n }\n\n return new exports.Request(method, url);\n}\n\nexports.Request = Request;\n\n/**\n * Determine XHR.\n */\n\nrequest.getXHR = function () {\n if (root.XMLHttpRequest\n && (!root.location || 'file:' != root.location.protocol\n || !root.ActiveXObject)) {\n return new XMLHttpRequest;\n } else {\n try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}\n try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}\n }\n throw Error(\"Browser-only verison of superagent could not find XHR\");\n};\n\n/**\n * Removes leading and trailing whitespace, added to support IE.\n *\n * @param {String} s\n * @return {String}\n * @api private\n */\n\nvar trim = ''.trim\n ? function(s) { return s.trim(); }\n : function(s) { return s.replace(/(^\\s*|\\s*$)/g, ''); };\n\n/**\n * Serialize the given `obj`.\n *\n * @param {Object} obj\n * @return {String}\n * @api private\n */\n\nfunction serialize(obj) {\n if (!isObject(obj)) return obj;\n var pairs = [];\n for (var key in obj) {\n pushEncodedKeyValuePair(pairs, key, obj[key]);\n }\n return pairs.join('&');\n}\n\n/**\n * Helps 'serialize' with serializing arrays.\n * Mutates the pairs array.\n *\n * @param {Array} pairs\n * @param {String} key\n * @param {Mixed} val\n */\n\nfunction pushEncodedKeyValuePair(pairs, key, val) {\n if (val != null) {\n if (Array.isArray(val)) {\n val.forEach(function(v) {\n pushEncodedKeyValuePair(pairs, key, v);\n });\n } else if (isObject(val)) {\n for(var subkey in val) {\n pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);\n }\n } else {\n pairs.push(encodeURIComponent(key)\n + '=' + encodeURIComponent(val));\n }\n } else if (val === null) {\n pairs.push(encodeURIComponent(key));\n }\n}\n\n/**\n * Expose serialization method.\n */\n\n request.serializeObject = serialize;\n\n /**\n * Parse the given x-www-form-urlencoded `str`.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseString(str) {\n var obj = {};\n var pairs = str.split('&');\n var pair;\n var pos;\n\n for (var i = 0, len = pairs.length; i < len; ++i) {\n pair = pairs[i];\n pos = pair.indexOf('=');\n if (pos == -1) {\n obj[decodeURIComponent(pair)] = '';\n } else {\n obj[decodeURIComponent(pair.slice(0, pos))] =\n decodeURIComponent(pair.slice(pos + 1));\n }\n }\n\n return obj;\n}\n\n/**\n * Expose parser.\n */\n\nrequest.parseString = parseString;\n\n/**\n * Default MIME type map.\n *\n * superagent.types.xml = 'application/xml';\n *\n */\n\nrequest.types = {\n html: 'text/html',\n json: 'application/json',\n xml: 'application/xml',\n urlencoded: 'application/x-www-form-urlencoded',\n 'form': 'application/x-www-form-urlencoded',\n 'form-data': 'application/x-www-form-urlencoded'\n};\n\n/**\n * Default serialization map.\n *\n * superagent.serialize['application/xml'] = function(obj){\n * return 'generated xml here';\n * };\n *\n */\n\n request.serialize = {\n 'application/x-www-form-urlencoded': serialize,\n 'application/json': JSON.stringify\n };\n\n /**\n * Default parsers.\n *\n * superagent.parse['application/xml'] = function(str){\n * return { object parsed from str };\n * };\n *\n */\n\nrequest.parse = {\n 'application/x-www-form-urlencoded': parseString,\n 'application/json': JSON.parse\n};\n\n/**\n * Parse the given header `str` into\n * an object containing the mapped fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nfunction parseHeader(str) {\n var lines = str.split(/\\r?\\n/);\n var fields = {};\n var index;\n var line;\n var field;\n var val;\n\n lines.pop(); // trailing CRLF\n\n for (var i = 0, len = lines.length; i < len; ++i) {\n line = lines[i];\n index = line.indexOf(':');\n field = line.slice(0, index).toLowerCase();\n val = trim(line.slice(index + 1));\n fields[field] = val;\n }\n\n return fields;\n}\n\n/**\n * Check if `mime` is json or has +json structured syntax suffix.\n *\n * @param {String} mime\n * @return {Boolean}\n * @api private\n */\n\nfunction isJSON(mime) {\n return /[\\/+]json\\b/.test(mime);\n}\n\n/**\n * Initialize a new `Response` with the given `xhr`.\n *\n * - set flags (.ok, .error, etc)\n * - parse header\n *\n * Examples:\n *\n * Aliasing `superagent` as `request` is nice:\n *\n * request = superagent;\n *\n * We can use the promise-like API, or pass callbacks:\n *\n * request.get('/').end(function(res){});\n * request.get('/', function(res){});\n *\n * Sending data can be chained:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' })\n * .end(function(res){});\n *\n * Or passed to `.send()`:\n *\n * request\n * .post('/user')\n * .send({ name: 'tj' }, function(res){});\n *\n * Or passed to `.post()`:\n *\n * request\n * .post('/user', { name: 'tj' })\n * .end(function(res){});\n *\n * Or further reduced to a single call for simple cases:\n *\n * request\n * .post('/user', { name: 'tj' }, function(res){});\n *\n * @param {XMLHTTPRequest} xhr\n * @param {Object} options\n * @api private\n */\n\nfunction Response(req) {\n this.req = req;\n this.xhr = this.req.xhr;\n // responseText is accessible only if responseType is '' or 'text' and on older browsers\n this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')\n ? this.xhr.responseText\n : null;\n this.statusText = this.req.xhr.statusText;\n var status = this.xhr.status;\n // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request\n if (status === 1223) {\n status = 204;\n }\n this._setStatusProperties(status);\n this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());\n // getAllResponseHeaders sometimes falsely returns \"\" for CORS requests, but\n // getResponseHeader still works. so we get content-type even if getting\n // other headers fails.\n this.header['content-type'] = this.xhr.getResponseHeader('content-type');\n this._setHeaderProperties(this.header);\n\n if (null === this.text && req._responseType) {\n this.body = this.xhr.response;\n } else {\n this.body = this.req.method != 'HEAD'\n ? this._parseBody(this.text ? this.text : this.xhr.response)\n : null;\n }\n}\n\nResponseBase(Response.prototype);\n\n/**\n * Parse the given body `str`.\n *\n * Used for auto-parsing of bodies. Parsers\n * are defined on the `superagent.parse` object.\n *\n * @param {String} str\n * @return {Mixed}\n * @api private\n */\n\nResponse.prototype._parseBody = function(str){\n var parse = request.parse[this.type];\n if(this.req._parser) {\n return this.req._parser(this, str);\n }\n if (!parse && isJSON(this.type)) {\n parse = request.parse['application/json'];\n }\n return parse && str && (str.length || str instanceof Object)\n ? parse(str)\n : null;\n};\n\n/**\n * Return an `Error` representative of this response.\n *\n * @return {Error}\n * @api public\n */\n\nResponse.prototype.toError = function(){\n var req = this.req;\n var method = req.method;\n var url = req.url;\n\n var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';\n var err = new Error(msg);\n err.status = this.status;\n err.method = method;\n err.url = url;\n\n return err;\n};\n\n/**\n * Expose `Response`.\n */\n\nrequest.Response = Response;\n\n/**\n * Initialize a new `Request` with the given `method` and `url`.\n *\n * @param {String} method\n * @param {String} url\n * @api public\n */\n\nfunction Request(method, url) {\n var self = this;\n this._query = this._query || [];\n this.method = method;\n this.url = url;\n this.header = {}; // preserves header name case\n this._header = {}; // coerces header names to lowercase\n this.on('end', function(){\n var err = null;\n var res = null;\n\n try {\n res = new Response(self);\n } catch(e) {\n err = new Error('Parser is unable to parse the response');\n err.parse = true;\n err.original = e;\n // issue #675: return the raw response if the response parsing fails\n if (self.xhr) {\n // ie9 doesn't have 'response' property\n err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;\n // issue #876: return the http status code if the response parsing fails\n err.status = self.xhr.status ? self.xhr.status : null;\n err.statusCode = err.status; // backwards-compat only\n } else {\n err.rawResponse = null;\n err.status = null;\n }\n\n return self.callback(err);\n }\n\n self.emit('response', res);\n\n var new_err;\n try {\n if (!self._isResponseOK(res)) {\n new_err = new Error(res.statusText || 'Unsuccessful HTTP response');\n new_err.original = err;\n new_err.response = res;\n new_err.status = res.status;\n }\n } catch(e) {\n new_err = e; // #985 touching res may cause INVALID_STATE_ERR on old Android\n }\n\n // #1000 don't catch errors from the callback to avoid double calling it\n if (new_err) {\n self.callback(new_err, res);\n } else {\n self.callback(null, res);\n }\n });\n}\n\n/**\n * Mixin `Emitter` and `RequestBase`.\n */\n\nEmitter(Request.prototype);\nRequestBase(Request.prototype);\n\n/**\n * Set Content-Type to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.xml = 'application/xml';\n *\n * request.post('/')\n * .type('xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * request.post('/')\n * .type('application/xml')\n * .send(xmlstring)\n * .end(callback);\n *\n * @param {String} type\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.type = function(type){\n this.set('Content-Type', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Accept to `type`, mapping values from `request.types`.\n *\n * Examples:\n *\n * superagent.types.json = 'application/json';\n *\n * request.get('/agent')\n * .accept('json')\n * .end(callback);\n *\n * request.get('/agent')\n * .accept('application/json')\n * .end(callback);\n *\n * @param {String} accept\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.accept = function(type){\n this.set('Accept', request.types[type] || type);\n return this;\n};\n\n/**\n * Set Authorization field value with `user` and `pass`.\n *\n * @param {String} user\n * @param {String} [pass] optional in case of using 'bearer' as type\n * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.auth = function(user, pass, options){\n if (typeof pass === 'object' && pass !== null) { // pass is optional and can substitute for options\n options = pass;\n }\n if (!options) {\n options = {\n type: 'function' === typeof btoa ? 'basic' : 'auto',\n }\n }\n\n switch (options.type) {\n case 'basic':\n this.set('Authorization', 'Basic ' + btoa(user + ':' + pass));\n break;\n\n case 'auto':\n this.username = user;\n this.password = pass;\n break;\n \n case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })\n this.set('Authorization', 'Bearer ' + user);\n break; \n }\n return this;\n};\n\n/**\n * Add query-string `val`.\n *\n * Examples:\n *\n * request.get('/shoes')\n * .query('size=10')\n * .query({ color: 'blue' })\n *\n * @param {Object|String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.query = function(val){\n if ('string' != typeof val) val = serialize(val);\n if (val) this._query.push(val);\n return this;\n};\n\n/**\n * Queue the given `file` as an attachment to the specified `field`,\n * with optional `options` (or filename).\n *\n * ``` js\n * request.post('/upload')\n * .attach('content', new Blob(['hey!'], { type: \"text/html\"}))\n * .end(callback);\n * ```\n *\n * @param {String} field\n * @param {Blob|File} file\n * @param {String|Object} options\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.attach = function(field, file, options){\n if (file) {\n if (this._data) {\n throw Error(\"superagent can't mix .send() and .attach()\");\n }\n\n this._getFormData().append(field, file, options || file.name);\n }\n return this;\n};\n\nRequest.prototype._getFormData = function(){\n if (!this._formData) {\n this._formData = new root.FormData();\n }\n return this._formData;\n};\n\n/**\n * Invoke the callback with `err` and `res`\n * and handle arity check.\n *\n * @param {Error} err\n * @param {Response} res\n * @api private\n */\n\nRequest.prototype.callback = function(err, res){\n // console.log(this._retries, this._maxRetries)\n if (this._maxRetries && this._retries++ < this._maxRetries && shouldRetry(err, res)) {\n return this._retry();\n }\n\n var fn = this._callback;\n this.clearTimeout();\n\n if (err) {\n if (this._maxRetries) err.retries = this._retries - 1;\n this.emit('error', err);\n }\n\n fn(err, res);\n};\n\n/**\n * Invoke callback with x-domain error.\n *\n * @api private\n */\n\nRequest.prototype.crossDomainError = function(){\n var err = new Error('Request has been terminated\\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');\n err.crossDomain = true;\n\n err.status = this.status;\n err.method = this.method;\n err.url = this.url;\n\n this.callback(err);\n};\n\n// This only warns, because the request is still likely to work\nRequest.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){\n console.warn(\"This is not supported in browser version of superagent\");\n return this;\n};\n\n// This throws, because it can't send/receive data as expected\nRequest.prototype.pipe = Request.prototype.write = function(){\n throw Error(\"Streaming is not supported in browser version of superagent\");\n};\n\n/**\n * Compose querystring to append to req.url\n *\n * @api private\n */\n\nRequest.prototype._appendQueryString = function(){\n var query = this._query.join('&');\n if (query) {\n this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;\n }\n\n if (this._sort) {\n var index = this.url.indexOf('?');\n if (index >= 0) {\n var queryArr = this.url.substring(index + 1).split('&');\n if (isFunction(this._sort)) {\n queryArr.sort(this._sort);\n } else {\n queryArr.sort();\n }\n this.url = this.url.substring(0, index) + '?' + queryArr.join('&');\n }\n }\n};\n\n/**\n * Check if `obj` is a host object,\n * we don't want to serialize these :)\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\nRequest.prototype._isHost = function _isHost(obj) {\n // Native objects stringify to [object File], [object Blob], [object FormData], etc.\n return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';\n}\n\n/**\n * Initiate request, invoking callback `fn(res)`\n * with an instanceof `Response`.\n *\n * @param {Function} fn\n * @return {Request} for chaining\n * @api public\n */\n\nRequest.prototype.end = function(fn){\n if (this._endCalled) {\n console.warn(\"Warning: .end() was called twice. This is not supported in superagent\");\n }\n this._endCalled = true;\n\n // store callback\n this._callback = fn || noop;\n\n // querystring\n this._appendQueryString();\n\n return this._end();\n};\n\nRequest.prototype._end = function() {\n var self = this;\n var xhr = this.xhr = request.getXHR();\n var data = this._formData || this._data;\n\n this._setTimeouts();\n\n // state change\n xhr.onreadystatechange = function(){\n var readyState = xhr.readyState;\n if (readyState >= 2 && self._responseTimeoutTimer) {\n clearTimeout(self._responseTimeoutTimer);\n }\n if (4 != readyState) {\n return;\n }\n\n // In IE9, reads to any property (e.g. status) off of an aborted XHR will\n // result in the error \"Could not complete the operation due to error c00c023f\"\n var status;\n try { status = xhr.status } catch(e) { status = 0; }\n\n if (!status) {\n if (self.timedout || self._aborted) return;\n return self.crossDomainError();\n }\n self.emit('end');\n };\n\n // progress\n var handleProgress = function(direction, e) {\n if (e.total > 0) {\n e.percent = e.loaded / e.total * 100;\n }\n e.direction = direction;\n self.emit('progress', e);\n }\n if (this.hasListeners('progress')) {\n try {\n xhr.onprogress = handleProgress.bind(null, 'download');\n if (xhr.upload) {\n xhr.upload.onprogress = handleProgress.bind(null, 'upload');\n }\n } catch(e) {\n // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.\n // Reported here:\n // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context\n }\n }\n\n // initiate request\n try {\n if (this.username && this.password) {\n xhr.open(this.method, this.url, true, this.username, this.password);\n } else {\n xhr.open(this.method, this.url, true);\n }\n } catch (err) {\n // see #1149\n return this.callback(err);\n }\n\n // CORS\n if (this._withCredentials) xhr.withCredentials = true;\n\n // body\n if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {\n // serialize stuff\n var contentType = this._header['content-type'];\n var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];\n if (!serialize && isJSON(contentType)) {\n serialize = request.serialize['application/json'];\n }\n if (serialize) data = serialize(data);\n }\n\n // set header fields\n for (var field in this.header) {\n if (null == this.header[field]) continue;\n\n if (this.header.hasOwnProperty(field))\n xhr.setRequestHeader(field, this.header[field]);\n }\n\n if (this._responseType) {\n xhr.responseType = this._responseType;\n }\n\n // send stuff\n this.emit('request', this);\n\n // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)\n // We need null here if data is undefined\n xhr.send(typeof data !== 'undefined' ? data : null);\n return this;\n};\n\n/**\n * GET `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.get = function(url, data, fn){\n var req = request('GET', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.query(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * HEAD `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.head = function(url, data, fn){\n var req = request('HEAD', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * OPTIONS query to `url` with optional callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.options = function(url, data, fn){\n var req = request('OPTIONS', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * DELETE `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nfunction del(url, data, fn){\n var req = request('DELETE', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\nrequest['del'] = del;\nrequest['delete'] = del;\n\n/**\n * PATCH `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.patch = function(url, data, fn){\n var req = request('PATCH', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * POST `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed} [data]\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.post = function(url, data, fn){\n var req = request('POST', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n/**\n * PUT `url` with optional `data` and callback `fn(res)`.\n *\n * @param {String} url\n * @param {Mixed|Function} [data] or fn\n * @param {Function} [fn]\n * @return {Request}\n * @api public\n */\n\nrequest.put = function(url, data, fn){\n var req = request('PUT', url);\n if ('function' == typeof data) fn = data, data = null;\n if (data) req.send(data);\n if (fn) req.end(fn);\n return req;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/client.js\n// module id = 7\n// module chunks = 0","/**\n * Check if `obj` is an object.\n *\n * @param {Object} obj\n * @return {Boolean}\n * @api private\n */\n\nfunction isObject(obj) {\n return null !== obj && 'object' === typeof obj;\n}\n\nmodule.exports = isObject;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-object.js\n// module id = 8\n// module chunks = 0","var g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/global.js\n// module id = 9\n// module chunks = 0","const storage = require('./localstorage');\nconst AV = require('./av');\n\nconst removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage);\n\nconst getCacheData = (cacheData, key) => {\n try {\n cacheData = JSON.parse(cacheData);\n } catch (e) {\n return null;\n }\n if (cacheData) {\n const expired = cacheData.expiredAt && cacheData.expiredAt < Date.now();\n if (!expired) {\n return cacheData.value;\n }\n return removeAsync(key).then(() => null);\n }\n return null;\n};\n\nexports.getAsync = (key) => {\n key = `${AV.applicationId}/${key}`;\n return storage.getItemAsync(key)\n .then(cache => getCacheData(cache, key));\n};\n\nexports.setAsync = (key, value, ttl) => {\n const cache = { value };\n if (typeof ttl === 'number') {\n cache.expiredAt = Date.now() + ttl;\n }\n return storage.setItemAsync(\n `${AV.applicationId}/${key}`,\n JSON.stringify(cache)\n );\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cache.js","var _ = require('underscore');\nvar Promise = require('./promise');\nvar localStorage = require('./utils/localstorage');\n\nvar syncApiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nif (!localStorage.async) {\n // wrap sync apis with async ones.\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] === 'function') {\n localStorage[apiName + 'Async'] = function() {\n return Promise.resolve(localStorage[apiName].apply(localStorage, arguments));\n };\n }\n });\n} else {\n _(syncApiNames).each(function(apiName) {\n if (typeof localStorage[apiName] !== 'function') {\n localStorage[apiName] = function() {\n const error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.');\n error.code = 'SYNC_API_NOT_AVAILABLE';\n throw error;\n };\n }\n });\n}\n\nmodule.exports = localStorage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/localstorage.js","module.exports = '2.1.4';\n\n\n\n// WEBPACK FOOTER //\n// ./src/version.js","var charenc = {\n // UTF-8 encoding\n utf8: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));\n }\n },\n\n // Binary encoding\n bin: {\n // Convert a string to a byte array\n stringToBytes: function(str) {\n for (var bytes = [], i = 0; i < str.length; i++)\n bytes.push(str.charCodeAt(i) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a string\n bytesToString: function(bytes) {\n for (var str = [], i = 0; i < bytes.length; i++)\n str.push(String.fromCharCode(bytes[i]));\n return str.join('');\n }\n }\n};\n\nmodule.exports = charenc;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/charenc/charenc.js\n// module id = 13\n// module chunks = 0","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var PUBLIC_KEY = \"*\";\n\n /**\n * Creates a new ACL.\n * If no argument is given, the ACL has no permissions for anyone.\n * If the argument is a AV.User, the ACL will have read and write\n * permission for only that user.\n * If the argument is any other JSON object, that object will be interpretted\n * as a serialized ACL created with toJSON().\n * @see AV.Object#setACL\n * @class\n *\n *

An ACL, or Access Control List can be added to any\n * AV.Object to restrict access to only a subset of users\n * of your application.

\n */\n AV.ACL = function(arg1) {\n var self = this;\n self.permissionsById = {};\n if (_.isObject(arg1)) {\n if (arg1 instanceof AV.User) {\n self.setReadAccess(arg1, true);\n self.setWriteAccess(arg1, true);\n } else {\n if (_.isFunction(arg1)) {\n throw new Error('AV.ACL() called with a function. Did you forget ()?');\n }\n AV._objectEach(arg1, function(accessList, userId) {\n if (!_.isString(userId)) {\n throw new Error('Tried to create an ACL with an invalid userId.');\n }\n self.permissionsById[userId] = {};\n AV._objectEach(accessList, function(allowed, permission) {\n if (permission !== \"read\" && permission !== \"write\") {\n throw new Error('Tried to create an ACL with an invalid permission type.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('Tried to create an ACL with an invalid permission value.');\n }\n self.permissionsById[userId][permission] = allowed;\n });\n });\n }\n }\n };\n\n /**\n * Returns a JSON-encoded version of the ACL.\n * @return {Object}\n */\n AV.ACL.prototype.toJSON = function() {\n return _.clone(this.permissionsById);\n };\n\n AV.ACL.prototype._setAccess = function(accessType, userId, allowed) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n if (!_.isString(userId)) {\n throw new Error('userId must be a string.');\n }\n if (!_.isBoolean(allowed)) {\n throw new Error('allowed must be either true or false.');\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n if (!allowed) {\n // The user already doesn't have this permission, so no action needed.\n return;\n } else {\n permissions = {};\n this.permissionsById[userId] = permissions;\n }\n }\n\n if (allowed) {\n this.permissionsById[userId][accessType] = true;\n } else {\n delete permissions[accessType];\n if (_.isEmpty(permissions)) {\n delete this.permissionsById[userId];\n }\n }\n };\n\n AV.ACL.prototype._getAccess = function(accessType, userId) {\n if (userId instanceof AV.User) {\n userId = userId.id;\n } else if (userId instanceof AV.Role) {\n userId = \"role:\" + userId.getName();\n }\n var permissions = this.permissionsById[userId];\n if (!permissions) {\n return false;\n }\n return permissions[accessType] ? true : false;\n };\n\n /**\n * Set whether the given user is allowed to read this object.\n * @param userId An instance of AV.User or its objectId.\n * @param {Boolean} allowed Whether that user should have read access.\n */\n AV.ACL.prototype.setReadAccess = function(userId, allowed) {\n this._setAccess(\"read\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to read this object.\n * Even if this returns false, the user may still be able to access it if\n * getPublicReadAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getReadAccess = function(userId) {\n return this._getAccess(\"read\", userId);\n };\n\n /**\n * Set whether the given user id is allowed to write this object.\n * @param userId An instance of AV.User or its objectId, or a AV.Role..\n * @param {Boolean} allowed Whether that user should have write access.\n */\n AV.ACL.prototype.setWriteAccess = function(userId, allowed) {\n this._setAccess(\"write\", userId, allowed);\n };\n\n /**\n * Get whether the given user id is *explicitly* allowed to write this object.\n * Even if this returns false, the user may still be able to write it if\n * getPublicWriteAccess returns true or a role that the user belongs to has\n * write access.\n * @param userId An instance of AV.User or its objectId, or a AV.Role.\n * @return {Boolean}\n */\n AV.ACL.prototype.getWriteAccess = function(userId) {\n return this._getAccess(\"write\", userId);\n };\n\n /**\n * Set whether the public is allowed to read this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicReadAccess = function(allowed) {\n this.setReadAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to read this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicReadAccess = function() {\n return this.getReadAccess(PUBLIC_KEY);\n };\n\n /**\n * Set whether the public is allowed to write this object.\n * @param {Boolean} allowed\n */\n AV.ACL.prototype.setPublicWriteAccess = function(allowed) {\n this.setWriteAccess(PUBLIC_KEY, allowed);\n };\n\n /**\n * Get whether the public is allowed to write this object.\n * @return {Boolean}\n */\n AV.ACL.prototype.getPublicWriteAccess = function() {\n return this.getWriteAccess(PUBLIC_KEY);\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to read this object. Even if this returns false, the role may\n * still be able to write it if a parent role has read access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has read access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleReadAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getReadAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Get whether users belonging to the given role are allowed\n * to write this object. Even if this returns false, the role may\n * still be able to write it if a parent role has write access.\n *\n * @param role The name of the role, or a AV.Role object.\n * @return {Boolean} true if the role has write access. false otherwise.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.getRoleWriteAccess = function(role) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n return this.getWriteAccess(\"role:\" + role);\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to read this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can read this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleReadAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setReadAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n /**\n * Set whether users belonging to the given role are allowed\n * to write this object.\n *\n * @param role The name of the role, or a AV.Role object.\n * @param {Boolean} allowed Whether the given role can write this object.\n * @throws {String} If role is neither a AV.Role nor a String.\n */\n AV.ACL.prototype.setRoleWriteAccess = function(role, allowed) {\n if (role instanceof AV.Role) {\n // Normalize to the String name\n role = role.getName();\n }\n if (_.isString(role)) {\n this.setWriteAccess(\"role:\" + role, allowed);\n return;\n }\n throw new Error('role must be a AV.Role or a String');\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/acl.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * Contains functions for calling and declaring\n *

\n * Some functions are only available from Cloud Code.\n *

\n *\n * @namespace\n */\n AV.Cloud = AV.Cloud || {};\n\n _.extend(AV.Cloud, /** @lends AV.Cloud */ {\n /**\n * Makes a call to a cloud function.\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n run: function(name, data, options) {\n var request = AVRequest('functions', name, null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response\n * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object}\n * @param {String} name The function name.\n * @param {Object} data The parameters to send to the cloud function.\n * @param {AuthOptions} options\n * @return {Promise} A promise that will be resolved with the result of the function.\n */\n rpc: function(name, data, options) {\n if (_.isArray(data)) {\n return Promise.reject(new Error('Can\\'t pass Array as the param of rpc function in JavaScript SDK.'));\n }\n\n return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function(resp) {\n return AV._decode(resp).result;\n });\n },\n\n /**\n * Make a call to request server date time.\n * @return {Promise.} A promise that will be resolved with the result\n * of the function.\n * @since 0.5.9\n */\n getServerDate: function() {\n var request = AVRequest(\"date\", null, null, 'GET');\n\n return request.then(function(resp) {\n return AV._decode(resp);\n });\n },\n\n /**\n * Makes a call to request a sms code for operation verification.\n * @param {Object} data The mobile phone number string or a JSON\n * object that contains mobilePhoneNumber,template,op,ttl,name etc.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n requestSmsCode: function(data){\n if(_.isString(data)) {\n data = { mobilePhoneNumber: data };\n }\n if(!data.mobilePhoneNumber) {\n throw new Error('Missing mobilePhoneNumber.');\n }\n var request = AVRequest(\"requestSmsCode\", null, null, 'POST',\n data);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode\n * @param {String} code The sms code sent by AV.Cloud.requestSmsCode\n * @param {phone} phone The mobile phoner number(optional).\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifySmsCode: function(code, phone){\n if(!code)\n throw new Error('Missing sms code.');\n var params = {};\n if(_.isString(phone)) {\n params['mobilePhoneNumber'] = phone;\n }\n\n var request = AVRequest(\"verifySmsCode\", code, null, 'POST',\n params);\n return request;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/cloudfunction.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n var eventSplitter = /\\s+/;\n var slice = Array.prototype.slice;\n\n /**\n * @class\n *\n *

AV.Events is a fork of Backbone's Events module, provided for your\n * convenience.

\n *\n *

A module that can be mixed in to any object in order to provide\n * it with custom events. You may bind callback functions to an event\n * with `on`, or remove these functions with `off`.\n * Triggering an event fires all callbacks in the order that `on` was\n * called.\n *\n * @private\n * @example\n * var object = {};\n * _.extend(object, AV.Events);\n * object.on('expand', function(){ alert('expanded'); });\n * object.trigger('expand');

\n *\n */\n AV.Events = {\n /**\n * Bind one or more space separated events, `events`, to a `callback`\n * function. Passing `\"all\"` will bind the callback to all events fired.\n */\n on: function(events, callback, context) {\n\n var calls, event, node, tail, list;\n if (!callback) {\n return this;\n }\n events = events.split(eventSplitter);\n calls = this._callbacks || (this._callbacks = {});\n\n // Create an immutable callback list, allowing traversal during\n // modification. The tail is an empty object that will always be used\n // as the next node.\n event = events.shift();\n while (event) {\n list = calls[event];\n node = list ? list.tail : {};\n node.next = tail = {};\n node.context = context;\n node.callback = callback;\n calls[event] = {tail: tail, next: list ? list.next : node};\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Remove one or many callbacks. If `context` is null, removes all callbacks\n * with that function. If `callback` is null, removes all callbacks for the\n * event. If `events` is null, removes all bound callbacks for all events.\n */\n off: function(events, callback, context) {\n var event, calls, node, tail, cb, ctx;\n\n // No events, or removing *all* events.\n if (!(calls = this._callbacks)) {\n return;\n }\n if (!(events || callback || context)) {\n delete this._callbacks;\n return this;\n }\n\n // Loop through the listed events and contexts, splicing them out of the\n // linked list of callbacks if appropriate.\n events = events ? events.split(eventSplitter) : _.keys(calls);\n event = events.shift();\n while (event) {\n node = calls[event];\n delete calls[event];\n if (!node || !(callback || context)) {\n continue;\n }\n // Create a new list, omitting the indicated callbacks.\n tail = node.tail;\n node = node.next;\n while (node !== tail) {\n cb = node.callback;\n ctx = node.context;\n if ((callback && cb !== callback) || (context && ctx !== context)) {\n this.on(event, cb, ctx);\n }\n node = node.next;\n }\n event = events.shift();\n }\n\n return this;\n },\n\n /**\n * Trigger one or many events, firing all bound callbacks. Callbacks are\n * passed the same arguments as `trigger` is, apart from the event name\n * (unless you're listening on `\"all\"`, which will cause your callback to\n * receive the true name of the event as the first argument).\n */\n trigger: function(events) {\n var event, node, calls, tail, args, all, rest;\n if (!(calls = this._callbacks)) {\n return this;\n }\n all = calls.all;\n events = events.split(eventSplitter);\n rest = slice.call(arguments, 1);\n\n // For each event, walk through the linked list of callbacks twice,\n // first to trigger the event, then to trigger any `\"all\"` callbacks.\n event = events.shift();\n while (event) {\n node = calls[event];\n if (node) {\n tail = node.tail;\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, rest);\n }\n }\n node = all;\n if (node) {\n tail = node.tail;\n args = [event].concat(rest);\n while ((node = node.next) !== tail) {\n node.callback.apply(node.context || this, args);\n }\n }\n event = events.shift();\n }\n\n return this;\n }\n };\n\n /**\n * @function\n */\n AV.Events.bind = AV.Events.on;\n\n /**\n * @function\n */\n AV.Events.unbind = AV.Events.off;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/event.js","const _ = require('underscore');\nconst cos = require('./uploader/cos');\nconst qiniu = require('./uploader/qiniu');\nconst s3 = require('./uploader/s3');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\nconst { tap } = require('./utils');\nconst debug = require('debug')('leancloud:file');\nconst parseBase64 = require('./utils/parse-base64');\n\nmodule.exports = function(AV) {\n\n // 挂载一些配置\n let avConfig = AV._config;\n\n const hexOctet = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);\n\n // port from browserify path module\n // since react-native packager won't shim node modules.\n const extname = (path) => {\n return path.match(/^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/)[4];\n };\n\n const b64Digit = (number) => {\n if (number < 26) {\n return String.fromCharCode(65 + number);\n }\n if (number < 52) {\n return String.fromCharCode(97 + (number - 26));\n }\n if (number < 62) {\n return String.fromCharCode(48 + (number - 52));\n }\n if (number === 62) {\n return '+';\n }\n if (number === 63) {\n return '/';\n }\n throw new Error('Tried to encode large digit ' + number + ' in base64.');\n };\n\n var encodeBase64 = function(array) {\n var chunks = [];\n chunks.length = Math.ceil(array.length / 3);\n _.times(chunks.length, function(i) {\n var b1 = array[i * 3];\n var b2 = array[i * 3 + 1] || 0;\n var b3 = array[i * 3 + 2] || 0;\n\n var has2 = (i * 3 + 1) < array.length;\n var has3 = (i * 3 + 2) < array.length;\n\n chunks[i] = [\n b64Digit((b1 >> 2) & 0x3F),\n b64Digit(((b1 << 4) & 0x30) | ((b2 >> 4) & 0x0F)),\n has2 ? b64Digit(((b2 << 2) & 0x3C) | ((b3 >> 6) & 0x03)) : \"=\",\n has3 ? b64Digit(b3 & 0x3F) : \"=\"\n ].join(\"\");\n });\n return chunks.join(\"\");\n };\n\n /**\n * An AV.File is a local representation of a file that is saved to the AV\n * cloud.\n * @param name {String} The file's name. This will change to a unique value\n * once the file has finished saving.\n * @param data {Array} The data for the file, as either:\n * 1. an Array of byte value Numbers, or\n * 2. an Object like { base64: \"...\" } with a base64-encoded String.\n * 3. a File object selected with a file upload control. (3) only works\n * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.\n * 4.a Buffer object in Node.js runtime.\n *\n * For example:
\n   * var fileUploadControl = $(\"#profilePhotoFileUpload\")[0];\n   * if (fileUploadControl.files.length > 0) {\n   *   var file = fileUploadControl.files[0];\n   *   var name = \"photo.jpg\";\n   *   var file = new AV.File(name, file);\n   *   file.save().then(function() {\n   *     // The file has been saved to AV.\n   *   }, function(error) {\n   *     // The file either could not be read, or could not be saved to AV.\n   *   });\n   * }
\n *\n * @class\n * @param [mimeType] {String} Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n */\n AV.File = function(name, data, mimeType) {\n\n this.attributes = {\n name,\n url: '',\n metaData: {},\n // 用来存储转换后要上传的 base64 String\n base64: '',\n };\n\n if (_.isString(data)) {\n throw new TypeError(\"Creating an AV.File from a String is not yet supported.\");\n }\n if (_.isArray(data)) {\n this.attributes.metaData.size = data.length;\n data = { base64: encodeBase64(data) };\n }\n\n this._extName = '';\n this._data = data;\n\n let owner;\n if (data && data.owner) {\n owner = data.owner;\n } else if (!AV._config.disableCurrentUser) {\n try {\n owner = AV.User.current();\n } catch (error) {\n if ('SYNC_API_NOT_AVAILABLE' === error.code) {\n console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().');\n } else {\n throw error;\n }\n }\n }\n \n this.attributes.metaData.owner = owner ? owner.id : 'unknown';\n\n this.set('mime_type', mimeType);\n };\n\n /**\n * Creates a fresh AV.File object with exists url for saving to AVOS Cloud.\n * @param {String} name the file name\n * @param {String} url the file url.\n * @param {Object} [metaData] the file metadata object.\n * @param {String} [type] Content-Type header to use for the file. If\n * this is omitted, the content type will be inferred from the name's\n * extension.\n * @return {AV.File} the file object\n */\n AV.File.withURL = function(name, url, metaData, type) {\n if (!name || !url){\n throw new Error(\"Please provide file name and url\");\n }\n var file = new AV.File(name, null, type);\n //copy metaData properties to file.\n if (metaData){\n for(var prop in metaData){\n if (!file.attributes.metaData[prop])\n file.attributes.metaData[prop] = metaData[prop];\n }\n }\n file.attributes.url = url;\n //Mark the file is from external source.\n file.attributes.metaData.__source = 'external';\n return file;\n };\n\n /**\n * Creates a file object with exists objectId.\n * @param {String} objectId The objectId string\n * @return {AV.File} the file object\n */\n AV.File.createWithoutData = function(objectId) {\n var file = new AV.File();\n file.id = objectId;\n return file;\n };\n\n AV.File.prototype = {\n className: '_File',\n\n _toFullJSON(seenObjects) {\n var json = _.clone(this.attributes);\n AV._objectEach(json, function(val, key) {\n json[key] = AV._encode(val, seenObjects);\n });\n AV._objectEach(this._operations, function(val, key) {\n json[key] = val;\n });\n\n if (_.has(this, \"id\")) {\n json.objectId = this.id;\n }\n _(['createdAt', 'updatedAt']).each((key) => {\n if (_.has(this, key)) {\n const val = this[key];\n json[key] = _.isDate(val) ? val.toJSON() : val;\n }\n });\n json.__type = \"File\";\n return json;\n },\n\n toJSON() {\n const json = this._toFullJSON();\n // add id and keep __type for backward compatible\n if (_.has(this, 'id')) {\n json.id = this.id;\n }\n return json;\n },\n\n /**\n * Returns the ACL for this file.\n * @returns {AV.ACL} An instance of AV.ACL.\n */\n getACL: function() {\n return this._acl;\n },\n\n /**\n * Sets the ACL to be used for this file.\n * @param {AV.ACL} acl An instance of AV.ACL.\n */\n setACL: function(acl) {\n if (!(acl instanceof AV.ACL)) {\n return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.');\n }\n this._acl = acl;\n },\n\n /**\n * Gets the name of the file. Before save is called, this is the filename\n * given by the user. After save is called, that name gets prefixed with a\n * unique identifier.\n */\n name: function() {\n return this.get('name');\n },\n\n /**\n * Gets the url of the file. It is only available after you save the file or\n * after you get the file from a AV.Object.\n * @return {String}\n */\n url: function() {\n return this.get('url');\n },\n\n /**\n * Gets the attributs of the file object.\n * @param {String} The attribute name which want to get.\n * @returns {Any}\n */\n get: function(attrName) {\n switch (attrName) {\n case 'objectId':\n return this.id;\n case 'url':\n case 'name':\n case 'mime_type':\n case 'metaData':\n case 'createdAt':\n case 'updatedAt':\n return this.attributes[attrName];\n default:\n return this.attributes.metaData[attrName];\n }\n },\n\n /**\n * Set the metaData of the file object.\n * @param {Object} Object is an key value Object for setting metaData.\n * @param {String} attr is an optional metadata key.\n * @param {Object} value is an optional metadata value.\n * @returns {String|Number|Array|Object}\n */\n set: function(...args) {\n const set = (attrName, value) => {\n switch (attrName) {\n case 'name':\n case 'url':\n case 'mime_type':\n case 'base64':\n case 'metaData':\n this.attributes[attrName] = value;\n break;\n default:\n // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面\n this.attributes.metaData[attrName] = value;\n break;\n }\n };\n\n switch (args.length) {\n case 1:\n // 传入一个 Object\n for (var k in args[0]) {\n set(k, args[0][k]);\n }\n break;\n case 2:\n set(args[0], args[1]);\n break;\n }\n },\n\n /**\n *

Returns the file's metadata JSON object if no arguments is given.Returns the\n * metadata value if a key is given.Set metadata value if key and value are both given.

\n *

\n    *  var metadata = file.metaData(); //Get metadata JSON object.\n    *  var size = file.metaData('size');  // Get the size metadata value.\n    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.\n    *

\n * @return {Object} The file's metadata JSON object.\n * @param {String} attr an optional metadata key.\n * @param {Object} value an optional metadata value.\n **/\n metaData: function(attr, value) {\n if (attr && value) {\n this.attributes.metaData[attr] = value;\n return this;\n } else if (attr && !value) {\n return this.attributes.metaData[attr];\n } else {\n return this.attributes.metaData;\n }\n },\n\n /**\n * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。\n * @return {String} 缩略图URL\n * @param {Number} width 宽度,单位:像素\n * @param {Number} heigth 高度,单位:像素\n * @param {Number} quality 质量,1-100的数字,默认100\n * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。\n * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。\n */\n\n thumbnailURL: function(width, height, quality, scaleToFit, fmt) {\n const url = this.attributes.url;\n if (!url) {\n throw new Error('Invalid url.');\n }\n if (!width || !height || width <= 0 || height <= 0 ) {\n throw new Error('Invalid width or height value.');\n }\n quality = quality || 100;\n scaleToFit = !scaleToFit ? true : scaleToFit;\n if (quality <= 0 || quality > 100) {\n throw new Error('Invalid quality value.');\n }\n fmt = fmt || 'png';\n const mode = scaleToFit ? 2: 1;\n return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt;\n },\n\n /**\n * Returns the file's size.\n * @return {Number} The file's size in bytes.\n **/\n size: function() {\n return this.metaData().size;\n },\n\n /**\n * Returns the file's owner.\n * @return {String} The file's owner id.\n */\n ownerId: function() {\n return this.metaData().owner;\n },\n\n /**\n * Destroy the file.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n if (!this.id) {\n return Promise.reject(new Error('The file id is not eixsts.'));\n }\n var request = AVRequest(\"files\", null, this.id, 'DELETE', null, options);\n return request;\n },\n\n /**\n * Request Qiniu upload token\n * @param {string} type\n * @return {Promise} Resolved with the response\n * @private\n */\n _fileToken(type, route = 'fileTokens') {\n let name = this.attributes.name;\n\n let extName = extname(name);\n if (!extName && this._extName) {\n name += this._extName;\n extName = this._extName;\n }\n // Create 16-bits uuid as qiniu key.\n const key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName;\n const data = {\n key,\n name,\n ACL: this._acl,\n mime_type: type,\n metaData: this.attributes.metaData,\n };\n this._qiniu_key = key;\n return AVRequest(route, null, null, 'POST', data);\n },\n\n /**\n * @callback UploadProgressCallback\n * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes\n */\n /**\n * Saves the file to the AV cloud.\n * @param {Object} [options]\n * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。\n * @return {Promise} Promise that is resolved when the save finishes.\n */\n save(options) {\n if (this.id) {\n throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.');\n }\n if (!this._previousSave) {\n if (this._data) {\n let mimeType = this.get('mime_type');\n this._previousSave = this._fileToken(mimeType).then(uploadInfo => {\n if (uploadInfo.mime_type) {\n mimeType = uploadInfo.mime_type;\n this.set('mime_type', mimeType);\n }\n this._token = uploadInfo.token;\n return Promise.resolve().then(() => {\n const data = this._data;\n if (data && data.base64) {\n return parseBase64(data.base64, mimeType);\n }\n if (data && data.blob) {\n if (!data.blob.type && mimeType) {\n data.blob.type = mimeType;\n }\n if (!data.blob.name) {\n data.blob.name = this.get('name');\n }\n if (process.env.CLIENT_PLATFORM === 'ReactNative' || process.env.CLIENT_PLATFORM === 'Weapp') {\n this._extName = extname(data.blob.uri);\n }\n return data.blob;\n }\n if (typeof File !== \"undefined\" && data instanceof File) {\n if (data.size) {\n this.attributes.metaData.size = data.size;\n }\n if (data.name) {\n this._extName = extname(data.name);\n }\n return data;\n }\n if (typeof Buffer !== \"undefined\" && Buffer.isBuffer(data)) {\n this.attributes.metaData.size = data.length;\n return data;\n }\n throw new TypeError('malformed file data');\n }).then(data => {\n let uploadPromise;\n switch (uploadInfo.provider) {\n case 's3':\n uploadPromise = s3(uploadInfo, data, this, options);\n break;\n case 'qcloud':\n uploadPromise = cos(uploadInfo, data, this, options);\n break;\n case 'qiniu':\n default:\n uploadPromise = qiniu(uploadInfo, data, this, options);\n break;\n }\n return uploadPromise.then(\n tap(() => this._callback(true)),\n (error) => {\n this._callback(false);\n throw error;\n }\n );\n });\n });\n } else if (this.attributes.url && this.attributes.metaData.__source === 'external') {\n // external link file.\n const data = {\n name: this.attributes.name,\n ACL: this._acl,\n metaData: this.attributes.metaData,\n mime_type: this.mimeType,\n url: this.attributes.url,\n };\n this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then((response) => {\n this.attributes.name = response.name;\n this.attributes.url = response.url;\n this.id = response.objectId;\n if (response.size) {\n this.attributes.metaData.size = response.size;\n }\n return this;\n });\n }\n }\n return this._previousSave;\n },\n\n _callback(success) {\n AVRequest('fileCallback', null, null, 'post', {\n token: this._token,\n result: success,\n }).catch(debug);\n delete this._token;\n delete this._data;\n },\n\n /**\n * fetch the file from server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option.\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(options) {\n var options = null;\n\n var request = AVRequest('files', null, this.id, 'GET', options);\n return request.then(this._finishFetch.bind(this));\n },\n _finishFetch: function(response) {\n var value = AV.Object.prototype.parse(response);\n value.attributes = {\n name: value.name,\n url: value.url,\n mime_type: value.mime_type,\n bucket: value.bucket,\n };\n value.attributes.metaData = value.metaData || {};\n value.id = value.objectId;\n // clean\n delete value.objectId;\n delete value.metaData;\n delete value.url;\n delete value.name;\n delete value.mime_type;\n delete value.bucket;\n _.extend(this, value);\n return this;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/file.js","var _ = require('underscore');\n\n/*global navigator: false */\nmodule.exports = function(AV) {\n /**\n * Creates a new GeoPoint with any of the following forms:
\n * @example\n * new GeoPoint(otherGeoPoint)\n * new GeoPoint(30, 30)\n * new GeoPoint([30, 30])\n * new GeoPoint({latitude: 30, longitude: 30})\n * new GeoPoint() // defaults to (0, 0)\n * @class\n *\n *

Represents a latitude / longitude point that may be associated\n * with a key in a AVObject or used as a reference point for geo queries.\n * This allows proximity-based queries on the key.

\n *\n *

Only one key in a class may contain a GeoPoint.

\n *\n *

Example:

\n   *   var point = new AV.GeoPoint(30.0, -20.0);\n   *   var object = new AV.Object(\"PlaceObject\");\n   *   object.set(\"location\", point);\n   *   object.save();

\n */\n AV.GeoPoint = function(arg1, arg2) {\n if (_.isArray(arg1)) {\n AV.GeoPoint._validate(arg1[0], arg1[1]);\n this.latitude = arg1[0];\n this.longitude = arg1[1];\n } else if (_.isObject(arg1)) {\n AV.GeoPoint._validate(arg1.latitude, arg1.longitude);\n this.latitude = arg1.latitude;\n this.longitude = arg1.longitude;\n } else if (_.isNumber(arg1) && _.isNumber(arg2)) {\n AV.GeoPoint._validate(arg1, arg2);\n this.latitude = arg1;\n this.longitude = arg2;\n } else {\n this.latitude = 0;\n this.longitude = 0;\n }\n\n // Add properties so that anyone using Webkit or Mozilla will get an error\n // if they try to set values that are out of bounds.\n var self = this;\n if (this.__defineGetter__ && this.__defineSetter__) {\n // Use _latitude and _longitude to actually store the values, and add\n // getters and setters for latitude and longitude.\n this._latitude = this.latitude;\n this._longitude = this.longitude;\n this.__defineGetter__(\"latitude\", function() {\n return self._latitude;\n });\n this.__defineGetter__(\"longitude\", function() {\n return self._longitude;\n });\n this.__defineSetter__(\"latitude\", function(val) {\n AV.GeoPoint._validate(val, self.longitude);\n self._latitude = val;\n });\n this.__defineSetter__(\"longitude\", function(val) {\n AV.GeoPoint._validate(self.latitude, val);\n self._longitude = val;\n });\n }\n };\n\n /**\n * @lends AV.GeoPoint.prototype\n * @property {float} latitude North-south portion of the coordinate, in range\n * [-90, 90]. Throws an exception if set out of range in a modern browser.\n * @property {float} longitude East-west portion of the coordinate, in range\n * [-180, 180]. Throws if set out of range in a modern browser.\n */\n\n /**\n * Throws an exception if the given lat-long is out of bounds.\n * @private\n */\n AV.GeoPoint._validate = function(latitude, longitude) {\n if (latitude < -90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" < -90.0.\");\n }\n if (latitude > 90.0) {\n throw new Error(\"AV.GeoPoint latitude \" + latitude + \" > 90.0.\");\n }\n if (longitude < -180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" < -180.0.\");\n }\n if (longitude > 180.0) {\n throw new Error(\"AV.GeoPoint longitude \" + longitude + \" > 180.0.\");\n }\n };\n\n /**\n * Creates a GeoPoint with the user's current location, if available.\n * @return {Promise.}\n */\n AV.GeoPoint.current = () => new AV.Promise((resolve, reject) => {\n navigator.geolocation.getCurrentPosition(function(location) {\n resolve(new AV.GeoPoint({\n latitude: location.coords.latitude,\n longitude: location.coords.longitude\n }));\n }, reject);\n });\n\n AV.GeoPoint.prototype = {\n /**\n * Returns a JSON representation of the GeoPoint, suitable for AV.\n * @return {Object}\n */\n toJSON: function() {\n AV.GeoPoint._validate(this.latitude, this.longitude);\n return {\n \"__type\": \"GeoPoint\",\n latitude: this.latitude,\n longitude: this.longitude\n };\n },\n\n /**\n * Returns the distance from this GeoPoint to another in radians.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n radiansTo: function(point) {\n var d2r = Math.PI / 180.0;\n var lat1rad = this.latitude * d2r;\n var long1rad = this.longitude * d2r;\n var lat2rad = point.latitude * d2r;\n var long2rad = point.longitude * d2r;\n var deltaLat = lat1rad - lat2rad;\n var deltaLong = long1rad - long2rad;\n var sinDeltaLatDiv2 = Math.sin(deltaLat / 2);\n var sinDeltaLongDiv2 = Math.sin(deltaLong / 2);\n // Square of half the straight line chord distance between both points.\n var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) +\n (Math.cos(lat1rad) * Math.cos(lat2rad) *\n sinDeltaLongDiv2 * sinDeltaLongDiv2));\n a = Math.min(1.0, a);\n return 2 * Math.asin(Math.sqrt(a));\n },\n\n /**\n * Returns the distance from this GeoPoint to another in kilometers.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n kilometersTo: function(point) {\n return this.radiansTo(point) * 6371.0;\n },\n\n /**\n * Returns the distance from this GeoPoint to another in miles.\n * @param {AV.GeoPoint} point the other AV.GeoPoint.\n * @return {Number}\n */\n milesTo: function(point) {\n return this.radiansTo(point) * 3958.8;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/geopoint.js","const AV = require('./av');\nconst request = require('./request');\n\nconst initialize = (appId, appKey, masterKey, hookKey) => {\n if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) {\n console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.');\n }\n AV.applicationId = appId;\n AV.applicationKey = appKey;\n AV.masterKey = masterKey;\n if (!process.env.CLIENT_PLATFORM) {\n AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY;\n }\n AV._useMasterKey = false;\n};\n\nconst masterKeyWarn = () => {\n console.warn('MasterKey is not supposed to be used in browser.');\n};\n\n/**\n * Call this method first to set up your authentication tokens for AV.\n * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .\n * @function AV.init\n * @param {Object} options\n * @param {String} options.appId application id\n * @param {String} options.appKey application key\n * @param {String} options.masterKey application master key\n*/\n\nAV.init = (...args) => {\n if (args.length === 1) {\n const options = args[0];\n if (typeof options === 'object') {\n if (process.env.CLIENT_PLATFORM && options.masterKey) {\n masterKeyWarn();\n }\n initialize(options.appId, options.appKey, options.masterKey, options.hookKey);\n request.setServerUrlByRegion(options.region);\n } else {\n throw new Error('AV.init(): Parameter is not correct.');\n }\n } else {\n // 兼容旧版本的初始化方法\n if (process.env.CLIENT_PLATFORM && args[3]) {\n masterKeyWarn();\n }\n initialize(...args);\n request.setServerUrlByRegion('cn');\n }\n};\n\n// If we're running in node.js, allow using the master key.\nif (!process.env.CLIENT_PLATFORM) {\n AV.Cloud = AV.Cloud || {};\n /**\n * Switches the LeanCloud SDK to using the Master key. The Master key grants\n * priveleged access to the data in LeanCloud and can be used to bypass ACLs and\n * other restrictions that are applied to the client SDKs.\n *

Available in Cloud Code and Node.js only.\n *

\n */\n AV.Cloud.useMasterKey = function() {\n AV._useMasterKey = true;\n };\n}\n\n// 兼容老版本的初始化方法\nAV.initialize = AV.init;\n\n\n\n// WEBPACK FOOTER //\n// ./src/init.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * 包含了使用了 LeanCloud\n * 离线数据分析功能的函数。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @namespace\n */\n AV.Insight = AV.Insight || {};\n\n _.extend(AV.Insight, /** @lends AV.Insight */ {\n\n /**\n * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用\n * AV.Insight.JobQuery 查询任务状态和结果。\n * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
\n     *                   { \"sql\" : \"select count(*) as c,gender from _User group by gender\",\n     *                     \"saveAs\": {\n     *                         \"className\" : \"UserGender\",\n     *                         \"limit\": 1\n     *                      }\n     *                   }\n     *                  
\n * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n startJob: function(jobConfig, options) {\n if(!jobConfig || !jobConfig.sql) {\n throw new Error('Please provide the sql to run the job.');\n }\n var data = {\n jobConfig: jobConfig,\n appId: AV.applicationId\n };\n var request = AVRequest(\"bigquery\", 'jobs', null, 'POST',\n AV._encode(data, null, true), options);\n\n return request.then(function(resp) {\n return AV._decode(resp).id;\n });\n },\n\n /**\n * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。\n *

\n * 仅在云引擎运行环境下有效。\n *

\n * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成\n * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息,\n * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。\n *\n */\n on: function(event, cb) {\n }\n });\n\n /**\n * 创建一个对象,用于查询 Insight 任务状态和结果。\n * @class\n * @param {String} id 任务 id\n * @since 0.5.5\n */\n AV.Insight.JobQuery = function(id, className) {\n if(!id) {\n throw new Error('Please provide the job id.');\n }\n this.id = id;\n this.className = className;\n this._skip = 0;\n this._limit = 100;\n };\n\n AV.Insight.JobQuery.prototype = {\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n this._limit = n;\n return this;\n },\n\n /**\n * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数,\n * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间\n * startTime、endTime 等信息。\n *\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n *\n */\n find: function(options) {\n var params = {\n skip: this._skip,\n limit: this._limit\n };\n\n var request = AVRequest(\"bigquery\", 'jobs', this.id, \"GET\",\n params, options);\n var self = this;\n return request.then(function(response) {\n if(response.error) {\n return AV.Promise.reject(new AVError(response.code, response.error));\n }\n return AV.Promise.resolve(response);\n });\n }\n\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/insight.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst utils = require('./utils');\n\nconst RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt'];\nconst checkReservedKey = key => {\n if (RESERVED_KEYS.indexOf(key) !== -1) {\n throw new Error(`key[${key}] is reserved`);\n }\n};\n\n// AV.Object is analogous to the Java AVObject.\n// It also implements the same interface as a Backbone model.\n\nmodule.exports = function(AV) {\n /**\n * Creates a new model with defined attributes. A client id (cid) is\n * automatically generated and assigned for you.\n *\n *

You won't normally call this method directly. It is recommended that\n * you use a subclass of AV.Object instead, created by calling\n * extend.

\n *\n *

However, if you don't want to use a subclass, or aren't sure which\n * subclass is appropriate, you can use this form:

\n   *     var object = new AV.Object(\"ClassName\");\n   * 
\n * That is basically equivalent to:
\n   *     var MyClass = AV.Object.extend(\"ClassName\");\n   *     var object = new MyClass();\n   * 

\n *\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @see AV.Object.extend\n *\n * @class\n *\n *

The fundamental unit of AV data, which implements the Backbone Model\n * interface.

\n */\n AV.Object = function(attributes, options) {\n // Allow new AV.Object(\"ClassName\") as a shortcut to _create.\n if (_.isString(attributes)) {\n return AV.Object._create.apply(this, arguments);\n }\n\n attributes = attributes || {};\n if (options && options.parse) {\n attributes = this.parse(attributes);\n attributes = this._mergeMagicFields(attributes);\n }\n var defaults = AV._getValue(this, 'defaults');\n if (defaults) {\n attributes = _.extend({}, defaults, attributes);\n }\n if (options && options.collection) {\n this.collection = options.collection;\n }\n\n this._serverData = {}; // The last known data for this object from cloud.\n this._opSetQueue = [{}]; // List of sets of changes to the data.\n this._flags = {};\n this.attributes = {}; // The best estimate of this's current data.\n\n this._hashedJSON = {}; // Hash of values of containers at last save.\n this._escapedAttributes = {};\n this.cid = _.uniqueId('c');\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this.set(attributes, { silent: true });\n this.changed = {};\n this._silent = {};\n this._pending = {};\n this._hasData = true;\n this._previousAttributes = _.clone(this.attributes);\n this.initialize.apply(this, arguments);\n };\n\n /**\n * @lends AV.Object.prototype\n * @property {String} id The objectId of the AV Object.\n */\n\n /**\n * Saves the given list of AV.Object.\n * If any error is encountered, stops and calls the error handler.\n *\n *
\n   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {\n   *     // All the objects were saved.\n   *   }, function(error) {\n   *     // An error occurred while saving one of the objects.\n   *   });\n   *\n   * @param {Array} list A list of AV.Object.\n   */\n  AV.Object.saveAll = function(list, options) {\n    return AV.Object._deepSaveAsync(list, null, options);\n  };\n\n  /**\n   * Fetch the given list of AV.Object.\n   *\n   * @param {AV.Object[]} objects A list of AV.Object\n   * @param {AuthOptions} options\n   * @return {Promise.} The given list of AV.Object, updated\n   */\n\n  AV.Object.fetchAll = (objects, options) =>\n    AV.Promise.resolve().then(() =>\n      AVRequest('batch', null, null, 'POST', {\n        requests: _.map(objects, object => {\n          if (!object.className) throw new Error('object must have className to fetch');\n          if (!object.id) throw new Error('object must have id to fetch');\n          if (object.dirty()) throw new Error('object is modified but not saved');\n          return {\n            method: 'GET',\n            path: `/1.1/classes/${object.className}/${object.id}`,\n          };\n        }),\n      }, options)\n    ).then(function(response) {\n      _.forEach(objects, function(object, i) {\n        if (response[i].success) {\n          object._finishFetch(\n            object.parse(response[i].success));\n        } else {\n          const error = new Error(response[i].error.error);\n          error.code = response[i].error.code;\n          throw error;\n        }\n      });\n      return objects;\n    });\n\n  // Attach all inheritable methods to the AV.Object prototype.\n  _.extend(AV.Object.prototype, AV.Events,\n           /** @lends AV.Object.prototype */ {\n    _fetchWhenSave: false,\n\n    /**\n     * Initialize is an empty function by default. Override it with your own\n     * initialization logic.\n     */\n    initialize: function(){},\n\n   /**\n     * Set whether to enable fetchWhenSave option when updating object.\n     * When set true, SDK would fetch the latest object after saving.\n     * Default is false.\n     *\n     * @deprecated use AV.Object#save with options.fetchWhenSave instead\n     * @param {boolean} enable  true to enable fetchWhenSave option.\n     */\n    fetchWhenSave: function(enable){\n      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');\n      if (!_.isBoolean(enable)) {\n        throw new Error('Expect boolean value for fetchWhenSave');\n      }\n      this._fetchWhenSave = enable;\n    },\n\n   /**\n    * Returns the object's objectId.\n    * @return {String} the objectId.\n    */\n    getObjectId: function() {\n      return this.id;\n    },\n\n   /**\n    * Returns the object's createdAt attribute.\n    * @return {Date}\n    */\n    getCreatedAt: function() {\n      return this.createdAt || this.get('createdAt');\n    },\n\n   /**\n    * Returns the object's updatedAt attribute.\n    * @return {Date}\n    */\n    getUpdatedAt: function() {\n      return this.updatedAt || this.get('updatedAt');\n    },\n\n    /**\n     * Returns a JSON version of the object suitable for saving to AV.\n     * @return {Object}\n     */\n    toJSON: function() {\n      var json = this._toFullJSON();\n      AV._arrayEach([\"__type\", \"className\"],\n                       function(key) { delete json[key]; });\n      return json;\n    },\n\n    _toFullJSON: function(seenObjects) {\n      var json = _.clone(this.attributes);\n      AV._objectEach(json, function(val, key) {\n        json[key] = AV._encode(val, seenObjects);\n      });\n      AV._objectEach(this._operations, function(val, key) {\n        json[key] = val;\n      });\n\n      if (_.has(this, \"id\")) {\n        json.objectId = this.id;\n      }\n      _(['createdAt', 'updatedAt']).each((key) => {\n        if (_.has(this, key)) {\n          const val = this[key];\n          json[key] = _.isDate(val) ? val.toJSON() : val;\n        }\n      });\n      json.__type = \"Object\";\n      json.className = this.className;\n      return json;\n    },\n\n    /**\n     * Updates _hashedJSON to reflect the current state of this object.\n     * Adds any changed hash values to the set of pending changes.\n     * @private\n     */\n    _refreshCache: function() {\n      var self = this;\n      if (self._refreshingCache) {\n        return;\n      }\n      self._refreshingCache = true;\n      AV._objectEach(this.attributes, function(value, key) {\n        if (value instanceof AV.Object) {\n          value._refreshCache();\n        } else if (_.isObject(value)) {\n          if (self._resetCacheForKey(key)) {\n            self.set(key, new AV.Op.Set(value), { silent: true });\n          }\n        }\n      });\n      delete self._refreshingCache;\n    },\n\n    /**\n     * Returns true if this object has been modified since its last\n     * save/refresh.  If an attribute is specified, it returns true only if that\n     * particular attribute has been modified since the last save/refresh.\n     * @param {String} attr An attribute name (optional).\n     * @return {Boolean}\n     */\n    dirty: function(attr) {\n      this._refreshCache();\n\n      var currentChanges = _.last(this._opSetQueue);\n\n      if (attr) {\n        return (currentChanges[attr] ? true : false);\n      }\n      if (!this.id) {\n        return true;\n      }\n      if (_.keys(currentChanges).length > 0) {\n        return true;\n      }\n      return false;\n    },\n\n    /**\n     * Gets a Pointer referencing this Object.\n     * @private\n     */\n    _toPointer: function() {\n      // if (!this.id) {\n      //   throw new Error(\"Can't serialize an unsaved AV.Object\");\n      // }\n      return { __type: \"Pointer\",\n               className: this.className,\n               objectId: this.id };\n    },\n\n    /**\n     * Gets the value of an attribute.\n     * @param {String} attr The string name of an attribute.\n     */\n    get: function(attr) {\n      switch (attr) {\n        case 'objectId':\n          return this.id;\n        case 'createdAt':\n        case 'updatedAt':\n          return this[attr];\n        default:\n          return this.attributes[attr];\n      }\n    },\n\n    /**\n     * Gets a relation on the given class for the attribute.\n     * @param {String} attr The attribute to get the relation for.\n     * @return {AV.Relation}\n     */\n    relation: function(attr) {\n      var value = this.get(attr);\n      if (value) {\n        if (!(value instanceof AV.Relation)) {\n          throw new Error(\"Called relation() on non-relation field \" + attr);\n        }\n        value._ensureParentAndKey(this, attr);\n        return value;\n      } else {\n        return new AV.Relation(this, attr);\n      }\n    },\n\n    /**\n     * Gets the HTML-escaped value of an attribute.\n     */\n    escape: function(attr) {\n      var html = this._escapedAttributes[attr];\n      if (html) {\n        return html;\n      }\n      var val = this.attributes[attr];\n      var escaped;\n      if (utils.isNullOrUndefined(val)) {\n        escaped = '';\n      } else {\n        escaped = _.escape(val.toString());\n      }\n      this._escapedAttributes[attr] = escaped;\n      return escaped;\n    },\n\n    /**\n     * Returns true if the attribute contains a value that is not\n     * null or undefined.\n     * @param {String} attr The string name of the attribute.\n     * @return {Boolean}\n     */\n    has: function(attr) {\n      return !utils.isNullOrUndefined(this.attributes[attr]);\n    },\n\n    /**\n     * Pulls \"special\" fields like objectId, createdAt, etc. out of attrs\n     * and puts them on \"this\" directly.  Removes them from attrs.\n     * @param attrs - A dictionary with the data for this AV.Object.\n     * @private\n     */\n    _mergeMagicFields: function(attrs) {\n      // Check for changes of magic fields.\n      var model = this;\n      var specialFields = [\"objectId\", \"createdAt\", \"updatedAt\"];\n      AV._arrayEach(specialFields, function(attr) {\n        if (attrs[attr]) {\n          if (attr === \"objectId\") {\n            model.id = attrs[attr];\n          } else if ((attr === \"createdAt\" || attr === \"updatedAt\") &&\n                     !_.isDate(attrs[attr])) {\n            model[attr] = AV._parseDate(attrs[attr]);\n          } else { \n            model[attr] = attrs[attr]; \n          }\n          delete attrs[attr];\n        }\n      });\n      return attrs;\n    },\n\n    /**\n     * Returns the json to be sent to the server.\n     * @private\n     */\n    _startSave: function() {\n      this._opSetQueue.push({});\n    },\n\n    /**\n     * Called when a save fails because of an error. Any changes that were part\n     * of the save need to be merged with changes made after the save. This\n     * might throw an exception is you do conflicting operations. For example,\n     * if you do:\n     *   object.set(\"foo\", \"bar\");\n     *   object.set(\"invalid field name\", \"baz\");\n     *   object.save();\n     *   object.increment(\"foo\");\n     * then this will throw when the save fails and the client tries to merge\n     * \"bar\" with the +1.\n     * @private\n     */\n    _cancelSave: function() {\n      var self = this;\n      var failedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      var nextChanges = _.first(this._opSetQueue);\n      AV._objectEach(failedChanges, function(op, key) {\n        var op1 = failedChanges[key];\n        var op2 = nextChanges[key];\n        if (op1 && op2) {\n          nextChanges[key] = op2._mergeWithPrevious(op1);\n        } else if (op1) {\n          nextChanges[key] = op1;\n        }\n      });\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a save completes successfully. This merges the changes that\n     * were saved into the known server data, and overrides it with any data\n     * sent directly from the server.\n     * @private\n     */\n    _finishSave: function(serverData) {\n      // Grab a copy of any object referenced by this object. These instances\n      // may have already been fetched, and we don't want to lose their data.\n      // Note that doing it like this means we will unify separate copies of the\n      // same object, but that's a risk we have to take.\n      var fetchedObjects = {};\n      AV._traverse(this.attributes, function(object) {\n        if (object instanceof AV.Object && object.id && object._hasData) {\n          fetchedObjects[object.id] = object;\n        }\n      });\n\n      var savedChanges = _.first(this._opSetQueue);\n      this._opSetQueue = _.rest(this._opSetQueue);\n      this._applyOpSet(savedChanges, this._serverData);\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n\n        // Look for any objects that might have become unfetched and fix them\n        // by replacing their values with the previously observed values.\n        var fetched = AV._traverse(self._serverData[key], function(object) {\n          if (object instanceof AV.Object && fetchedObjects[object.id]) {\n            return fetchedObjects[object.id];\n          }\n        });\n        if (fetched) {\n          self._serverData[key] = fetched;\n        }\n      });\n      this._rebuildAllEstimatedData();\n      this._saving = this._saving - 1;\n    },\n\n    /**\n     * Called when a fetch or login is complete to set the known server data to\n     * the given object.\n     * @private\n     */\n    _finishFetch: function(serverData, hasData) {\n      // Clear out any changes the user might have made previously.\n      this._opSetQueue = [{}];\n\n      // Bring in all the new server data.\n      this._mergeMagicFields(serverData);\n      var self = this;\n      AV._objectEach(serverData, function(value, key) {\n        self._serverData[key] = AV._decode(value, key);\n      });\n\n      // Refresh the attributes.\n      this._rebuildAllEstimatedData();\n\n      // Clear out the cache of mutable containers.\n      this._refreshCache();\n      this._opSetQueue = [{}];\n\n      this._hasData = hasData;\n    },\n\n    /**\n     * Applies the set of AV.Op in opSet to the object target.\n     * @private\n     */\n    _applyOpSet: function(opSet, target) {\n      var self = this;\n      AV._objectEach(opSet, function(change, key) {\n        target[key] = change._estimate(target[key], self, key);\n        if (target[key] === AV.Op._UNSET) {\n          delete target[key];\n        }\n      });\n    },\n\n    /**\n     * Replaces the cached value for key with the current value.\n     * Returns true if the new value is different than the old value.\n     * @private\n     */\n    _resetCacheForKey: function(key) {\n      var value = this.attributes[key];\n      if (_.isObject(value) &&\n          !(value instanceof AV.Object) &&\n          !(value instanceof AV.File)) {\n\n        value = value.toJSON ? value.toJSON() : value;\n        var json = JSON.stringify(value);\n        if (this._hashedJSON[key] !== json) {\n          var wasSet = !! this._hashedJSON[key];\n          this._hashedJSON[key] = json;\n          return wasSet;\n        }\n      }\n      return false;\n    },\n\n    /**\n     * Populates attributes[key] by starting with the last known data from the\n     * server, and applying all of the local changes that have been made to that\n     * key since then.\n     * @private\n     */\n    _rebuildEstimatedDataForKey: function(key) {\n      var self = this;\n      delete this.attributes[key];\n      if (this._serverData[key]) {\n        this.attributes[key] = this._serverData[key];\n      }\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        var op = opSet[key];\n        if (op) {\n          self.attributes[key] = op._estimate(self.attributes[key], self, key);\n          if (self.attributes[key] === AV.Op._UNSET) {\n            delete self.attributes[key];\n          } else {\n            self._resetCacheForKey(key);\n          }\n        }\n      });\n    },\n\n    /**\n     * Populates attributes by starting with the last known data from the\n     * server, and applying all of the local changes that have been made since\n     * then.\n     * @private\n     */\n    _rebuildAllEstimatedData: function() {\n      var self = this;\n\n      var previousAttributes = _.clone(this.attributes);\n\n      this.attributes = _.clone(this._serverData);\n      AV._arrayEach(this._opSetQueue, function(opSet) {\n        self._applyOpSet(opSet, self.attributes);\n        AV._objectEach(opSet, function(op, key) {\n          self._resetCacheForKey(key);\n        });\n      });\n\n      // Trigger change events for anything that changed because of the fetch.\n      AV._objectEach(previousAttributes, function(oldValue, key) {\n        if (self.attributes[key] !== oldValue) {\n          self.trigger('change:' + key, self, self.attributes[key], {});\n        }\n      });\n      AV._objectEach(this.attributes, function(newValue, key) {\n        if (!_.has(previousAttributes, key)) {\n          self.trigger('change:' + key, self, newValue, {});\n        }\n      });\n    },\n\n    /**\n     * Sets a hash of model attributes on the object, firing\n     * \"change\" unless you choose to silence it.\n     *\n     * 

You can call it with an object containing keys and values, or with one\n * key and value. For example:

\n     *   gameTurn.set({\n     *     player: player1,\n     *     diceRoll: 2\n     *   }, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"currentPlayer\", player2, {\n     *     error: function(gameTurnAgain, error) {\n     *       // The set failed validation.\n     *     }\n     *   });\n     *\n     *   game.set(\"finished\", true);

\n *\n * @param {String} key The key to set.\n * @param {Any} value The value to give it.\n * @param {Object} [options]\n * @param {Boolean} [options.silent]\n * @return {AV.Object} self if succeeded, throws if the value is not valid.\n * @see AV.Object#validate\n */\n set: function(key, value, options) {\n var attrs;\n if (_.isObject(key) || utils.isNullOrUndefined(key)) {\n attrs = _.mapObject(key, function(v, k) {\n checkReservedKey(k);\n return AV._decode(v, k);\n });\n options = value;\n } else {\n attrs = {};\n checkReservedKey(key);\n attrs[key] = AV._decode(value, key);\n }\n\n // Extract attributes and options.\n options = options || {};\n if (!attrs) {\n return this;\n }\n if (attrs instanceof AV.Object) {\n attrs = attrs.attributes;\n }\n\n // If the unset option is used, every attribute should be a Unset.\n if (options.unset) {\n AV._objectEach(attrs, function(unused_value, key) {\n attrs[key] = new AV.Op.Unset();\n });\n }\n\n // Apply all the attributes to get the estimated values.\n var dataToValidate = _.clone(attrs);\n var self = this;\n AV._objectEach(dataToValidate, function(value, key) {\n if (value instanceof AV.Op) {\n dataToValidate[key] = value._estimate(self.attributes[key],\n self, key);\n if (dataToValidate[key] === AV.Op._UNSET) {\n delete dataToValidate[key];\n }\n }\n });\n\n // Run validation.\n this._validate(attrs, options);\n\n options.changes = {};\n var escaped = this._escapedAttributes;\n var prev = this._previousAttributes || {};\n\n // Update attributes.\n AV._arrayEach(_.keys(attrs), function(attr) {\n var val = attrs[attr];\n\n // If this is a relation object we need to set the parent correctly,\n // since the location where it was parsed does not have access to\n // this object.\n if (val instanceof AV.Relation) {\n val.parent = self;\n }\n\n if (!(val instanceof AV.Op)) {\n val = new AV.Op.Set(val);\n }\n\n // See if this change will actually have any effect.\n var isRealChange = true;\n if (val instanceof AV.Op.Set &&\n _.isEqual(self.attributes[attr], val.value)) {\n isRealChange = false;\n }\n\n if (isRealChange) {\n delete escaped[attr];\n if (options.silent) {\n self._silent[attr] = true;\n } else {\n options.changes[attr] = true;\n }\n }\n\n var currentChanges = _.last(self._opSetQueue);\n currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]);\n self._rebuildEstimatedDataForKey(attr);\n\n if (isRealChange) {\n self.changed[attr] = self.attributes[attr];\n if (!options.silent) {\n self._pending[attr] = true;\n }\n } else {\n delete self.changed[attr];\n delete self._pending[attr];\n }\n });\n\n if (!options.silent) {\n this.change(options);\n }\n return this;\n },\n\n /**\n * Remove an attribute from the model, firing \"change\" unless\n * you choose to silence it. This is a noop if the attribute doesn't\n * exist.\n */\n unset: function(attr, options) {\n options = options || {};\n options.unset = true;\n return this.set(attr, null, options);\n },\n\n /**\n * Atomically increments the value of the given attribute the next time the\n * object is saved. If no amount is specified, 1 is used by default.\n *\n * @param attr {String} The key.\n * @param amount {Number} The amount to increment by.\n */\n increment: function(attr, amount) {\n if (_.isUndefined(amount) || _.isNull(amount)) {\n amount = 1;\n }\n return this.set(attr, new AV.Op.Increment(amount));\n },\n\n /**\n * Atomically add an object to the end of the array associated with a given\n * key.\n * @param attr {String} The key.\n * @param item {} The item to add.\n */\n add: function(attr, item) {\n return this.set(attr, new AV.Op.Add(utils.ensureArray(item)));\n },\n\n /**\n * Atomically add an object to the array associated with a given key, only\n * if it is not already present in the array. The position of the insert is\n * not guaranteed.\n *\n * @param attr {String} The key.\n * @param item {} The object to add.\n */\n addUnique: function(attr, item) {\n return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item)));\n },\n\n /**\n * Atomically remove all instances of an object from the array associated\n * with a given key.\n *\n * @param attr {String} The key.\n * @param item {} The object to remove.\n */\n remove: function(attr, item) {\n return this.set(attr, new AV.Op.Remove(utils.ensureArray(item)));\n },\n\n /**\n * Returns an instance of a subclass of AV.Op describing what kind of\n * modification has been performed on this field since the last time it was\n * saved. For example, after calling object.increment(\"x\"), calling\n * object.op(\"x\") would return an instance of AV.Op.Increment.\n *\n * @param attr {String} The key.\n * @returns {AV.Op} The operation, or undefined if none.\n */\n op: function(attr) {\n return _.last(this._opSetQueue)[attr];\n },\n\n /**\n * Clear all attributes on the model, firing \"change\" unless\n * you choose to silence it.\n */\n clear: function(options) {\n options = options || {};\n options.unset = true;\n var keysToClear = _.extend(this.attributes, this._operations);\n return this.set(keysToClear, options);\n },\n\n /**\n * Returns a JSON-encoded set of operations to be sent with the next save\n * request.\n * @private\n */\n _getSaveJSON: function() {\n var json = _.clone(_.first(this._opSetQueue));\n AV._objectEach(json, function(op, key) {\n json[key] = op.toJSON();\n });\n return json;\n },\n\n /**\n * Returns true if this object can be serialized for saving.\n * @private\n */\n _canBeSerialized: function() {\n return AV.Object._canBeSerializedAsValue(this.attributes);\n },\n\n /**\n * Fetch the model from the server. If the server's representation of the\n * model differs from its current attributes, they will be overriden,\n * triggering a \"change\" event.\n * @param {Object} fetchOptions Optional options to set 'keys' and\n * 'include' option.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the fetch\n * completes.\n */\n fetch: function(fetchOptions = {}, options) {\n if (_.isArray(fetchOptions.keys)) {\n fetchOptions.keys = fetchOptions.keys.join(',');\n }\n if (_.isArray(fetchOptions.include)) {\n fetchOptions.include = fetchOptions.include.join(',');\n }\n\n var self = this;\n var request = AVRequest('classes', this.className, this.id, 'GET',\n fetchOptions, options);\n return request.then(function(response) {\n self._finishFetch(self.parse(response), true);\n return self;\n });\n },\n\n /**\n * Set a hash of model attributes, and save the model to the server.\n * updatedAt will be updated when the request returns.\n * You can either call it as:
\n     *   object.save();
\n * or
\n     *   object.save(null, options);
\n * or
\n     *   object.save(attrs, options);
\n * or
\n     *   object.save(key, value, options);
\n *\n * For example,
\n     *   gameTurn.save({\n     *     player: \"Jake Cutter\",\n     *     diceRoll: 2\n     *   }).then(function(gameTurnAgain) {\n     *     // The save was successful.\n     *   }, function(error) {\n     *     // The save failed.  Error is an instance of AVError.\n     *   });
\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded\n * @param {AV.Query} options.query Save object only when it matches the query\n * @return {AV.Promise} A promise that is fulfilled when the save\n * completes.\n * @see AVError\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n\n options = _.clone(options) || {};\n if (options.wait) {\n current = _.clone(this.attributes);\n }\n\n var setOptions = _.clone(options) || {};\n if (setOptions.wait) {\n setOptions.silent = true;\n }\n if (attrs) {\n this.set(attrs, setOptions);\n }\n\n var model = this;\n\n // If there is any unsaved child, save it first.\n model._refreshCache();\n\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(model.attributes,\n unsavedChildren,\n unsavedFiles);\n if (unsavedChildren.length + unsavedFiles.length > 0) {\n return AV.Object._deepSaveAsync(this.attributes, model, options).then(function() {\n return model.save(null, options);\n });\n }\n\n this._startSave();\n this._saving = (this._saving || 0) + 1;\n\n this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve();\n this._allPreviousSaves = this._allPreviousSaves.catch(e => {}).then(function() {\n var method = model.id ? 'PUT' : 'POST';\n\n var json = model._getSaveJSON();\n\n if(model._fetchWhenSave){\n //Sepcial-case fetchWhenSave when updating object.\n json._fetchWhenSave = true;\n }\n\n if (options.fetchWhenSave) {\n json._fetchWhenSave = true;\n }\n if (options.query) {\n var queryJSON;\n if (typeof options.query.toJSON === 'function') {\n queryJSON = options.query.toJSON();\n if (queryJSON) {\n json._where = queryJSON.where;\n }\n }\n if (!json._where) {\n var error = new Error('options.query is not an AV.Query');\n throw error;\n }\n }\n\n _.extend(json, model._flags);\n\n var route = \"classes\";\n var className = model.className;\n if (model.className === \"_User\" && !model.id) {\n // Special-case user sign-up.\n route = \"users\";\n className = null;\n }\n //hook makeRequest in options.\n var makeRequest = options._makeRequest || AVRequest;\n var request = makeRequest(route, className, model.id, method, json, options);\n\n request = request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n if (options.wait) {\n serverAttrs = _.extend(attrs || {}, serverAttrs);\n }\n model._finishSave(serverAttrs);\n if (options.wait) {\n model.set(current, setOptions);\n }\n return model;\n\n }, function(error) {\n model._cancelSave();\n throw error;\n });\n\n return request;\n });\n return this._allPreviousSaves;\n },\n\n /**\n * Destroy this model on the server if it was already persisted.\n * Optimistically removes the model from its collection, if it has one.\n * @param {AuthOptions} options AuthOptions plus:\n * @param {Boolean} [options.wait] wait for the server to respond\n * before removal.\n *\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options) {\n options = options || {};\n var model = this;\n\n var triggerDestroy = function() {\n model.trigger('destroy', model, model.collection, options);\n };\n\n if (!this.id) {\n return triggerDestroy();\n }\n\n if (!options.wait) {\n triggerDestroy();\n }\n\n var request =\n AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options);\n return request.then(function() {\n if (options.wait) {\n triggerDestroy();\n }\n return model;\n });\n },\n\n /**\n * Converts a response into the hash of attributes to be set on the model.\n * @ignore\n */\n parse: function(resp) {\n var output = _.clone(resp);\n _([\"createdAt\", \"updatedAt\"]).each(function(key) {\n if (output[key]) {\n output[key] = AV._parseDate(output[key]);\n }\n });\n if (!output.updatedAt) {\n output.updatedAt = output.createdAt;\n }\n return output;\n },\n\n /**\n * Creates a new model with identical attributes to this one.\n * @return {AV.Object}\n */\n clone: function() {\n return new this.constructor(this.attributes);\n },\n\n /**\n * Returns true if this object has never been saved to AV.\n * @return {Boolean}\n */\n isNew: function() {\n return !this.id;\n },\n\n /**\n * Call this method to manually fire a `\"change\"` event for this model and\n * a `\"change:attribute\"` event for each changed attribute.\n * Calling this will cause all objects observing the model to update.\n */\n change: function(options) {\n options = options || {};\n var changing = this._changing;\n this._changing = true;\n\n // Silent changes become pending changes.\n var self = this;\n AV._objectEach(this._silent, function(attr) {\n self._pending[attr] = true;\n });\n\n // Silent changes are triggered.\n var changes = _.extend({}, options.changes, this._silent);\n this._silent = {};\n AV._objectEach(changes, function(unused_value, attr) {\n self.trigger('change:' + attr, self, self.get(attr), options);\n });\n if (changing) {\n return this;\n }\n\n // This is to get around lint not letting us make a function in a loop.\n var deleteChanged = function(value, attr) {\n if (!self._pending[attr] && !self._silent[attr]) {\n delete self.changed[attr];\n }\n };\n\n // Continue firing `\"change\"` events while there are pending changes.\n while (!_.isEmpty(this._pending)) {\n this._pending = {};\n this.trigger('change', this, options);\n // Pending and silent changes still remain.\n AV._objectEach(this.changed, deleteChanged);\n self._previousAttributes = _.clone(this.attributes);\n }\n\n this._changing = false;\n return this;\n },\n\n /**\n * Determine if the model has changed since the last \"change\"\n * event. If you specify an attribute name, determine if that attribute\n * has changed.\n * @param {String} attr Optional attribute name\n * @return {Boolean}\n */\n hasChanged: function(attr) {\n if (!arguments.length) {\n return !_.isEmpty(this.changed);\n }\n return this.changed && _.has(this.changed, attr);\n },\n\n /**\n * Returns an object containing all the attributes that have changed, or\n * false if there are no changed attributes. Useful for determining what\n * parts of a view need to be updated and/or what attributes need to be\n * persisted to the server. Unset attributes will be set to undefined.\n * You can also pass an attributes object to diff against the model,\n * determining if there *would be* a change.\n */\n changedAttributes: function(diff) {\n if (!diff) {\n return this.hasChanged() ? _.clone(this.changed) : false;\n }\n var changed = {};\n var old = this._previousAttributes;\n AV._objectEach(diff, function(diffVal, attr) {\n if (!_.isEqual(old[attr], diffVal)) {\n changed[attr] = diffVal;\n }\n });\n return changed;\n },\n\n /**\n * Gets the previous value of an attribute, recorded at the time the last\n * \"change\" event was fired.\n * @param {String} attr Name of the attribute to get.\n */\n previous: function(attr) {\n if (!arguments.length || !this._previousAttributes) {\n return null;\n }\n return this._previousAttributes[attr];\n },\n\n /**\n * Gets all of the attributes of the model at the time of the previous\n * \"change\" event.\n * @return {Object}\n */\n previousAttributes: function() {\n return _.clone(this._previousAttributes);\n },\n\n /**\n * Checks if the model is currently in a valid state. It's only possible to\n * get into an *invalid* state if you're using silent changes.\n * @return {Boolean}\n */\n isValid: function() {\n try {\n this.validate(this.attributes);\n } catch (error) {\n return false;\n }\n return true;\n },\n\n /**\n * You should not call this function directly unless you subclass\n * AV.Object, in which case you can override this method\n * to provide additional validation on set and\n * save. Your implementation should throw an Error if\n * the attrs is invalid\n *\n * @param {Object} attrs The current data to validate.\n * @see AV.Object#set\n */\n validate: function(attrs) {\n if (_.has(attrs, \"ACL\") && !(attrs.ACL instanceof AV.ACL)) {\n throw new AVError(AVError.OTHER_CAUSE,\n \"ACL must be a AV.ACL.\");\n }\n },\n\n /**\n * Run validation against a set of incoming attributes, returning `true`\n * if all is well. If a specific `error` callback has been passed,\n * call that instead of firing the general `\"error\"` event.\n * @private\n */\n _validate: function(attrs, options) {\n if (options.silent || !this.validate) {\n return;\n }\n attrs = _.extend({}, this.attributes, attrs);\n this.validate(attrs);\n },\n\n /**\n * Returns the ACL for this object.\n * @returns {AV.ACL} An instance of AV.ACL.\n * @see AV.Object#get\n */\n getACL: function() {\n return this.get(\"ACL\");\n },\n\n /**\n * Sets the ACL to be used for this object.\n * @param {AV.ACL} acl An instance of AV.ACL.\n * @param {Object} options Optional Backbone-like options object to be\n * passed in to set.\n * @return {Boolean} Whether the set passed validation.\n * @see AV.Object#set\n */\n setACL: function(acl, options) {\n return this.set(\"ACL\", acl, options);\n },\n\n disableBeforeHook: function() {\n this.ignoreHook('beforeSave');\n this.ignoreHook('beforeUpdate');\n this.ignoreHook('beforeDelete');\n },\n\n disableAfterHook: function() {\n this.ignoreHook('afterSave');\n this.ignoreHook('afterUpdate');\n this.ignoreHook('afterDelete');\n },\n\n ignoreHook: function(hookName) {\n if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) {\n console.trace('Unsupported hookName: ' + hookName);\n }\n\n if (!AV.hookKey) {\n console.trace('ignoreHook required hookKey');\n }\n\n if (!this._flags.__ignore_hooks) {\n this._flags.__ignore_hooks = [];\n }\n\n this._flags.__ignore_hooks.push(hookName);\n }\n });\n\n /**\n * Creates an instance of a subclass of AV.Object for the give classname\n * and id.\n * @param {String} className The name of the AV class backing this model.\n * @param {String} id The object id of this model.\n * @return {AV.Object} A new subclass instance of AV.Object.\n */\n AV.Object.createWithoutData = function(className, id, hasData){\n var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/ true);\n result.id = id;\n result._hasData = hasData;\n return result;\n };\n /**\n * Delete objects in batch.\n * @param {AV.Object[]} objects The AV.Object array to be deleted.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n AV.Object.destroyAll = function(objects, options = {}){\n if (!objects || objects.length === 0){\n\t\t return AV.Promise.resolve();\n }\n const objectsByClassNameAndFlags = _.groupBy(objects, object => JSON.stringify({\n className: object.className,\n flags: object._flags\n }));\n const body = {\n requests: _.map(objectsByClassNameAndFlags, objects => {\n const ids = _.map(objects, 'id').join(',');\n return {\n method: 'DELETE',\n path: `/1.1/classes/${objects[0].className}/${ids}`,\n body: objects[0]._flags\n }\n })\n };\n return AVRequest('batch', null, null, 'POST', body, options);\n };\n\n /**\n * Returns the appropriate subclass for making new instances of the given\n * className string.\n * @private\n */\n AV.Object._getSubclass = function(className) {\n if (!_.isString(className)) {\n throw new Error('AV.Object._getSubclass requires a string argument.');\n }\n var ObjectClass = AV.Object._classMap[className];\n if (!ObjectClass) {\n ObjectClass = AV.Object.extend(className);\n AV.Object._classMap[className] = ObjectClass;\n }\n return ObjectClass;\n };\n\n /**\n * Creates an instance of a subclass of AV.Object for the given classname.\n * @private\n */\n AV.Object._create = function(className, attributes, options, noDefaultACL) {\n var ObjectClass = AV.Object._getSubclass(className);\n return new ObjectClass(attributes, options, noDefaultACL);\n };\n\n // Set up a map of className to class so that we can create new instances of\n // AV Objects from JSON automatically.\n AV.Object._classMap = {};\n\n AV.Object._extend = AV._extend;\n\n /**\n * Creates a new model with defined attributes,\n * It's the same with\n *
\n   *   new AV.Object(attributes, options);\n   *  
\n * @param {Object} attributes The initial set of data to store in the object.\n * @param {Object} options A set of Backbone-like options for creating the\n * object. The only option currently supported is \"collection\".\n * @return {AV.Object}\n * @since v0.4.4\n * @see AV.Object\n * @see AV.Object.extend\n */\n AV.Object['new'] = function(attributes, options){\n return new AV.Object(attributes, options);\n };\n\n /**\n * Creates a new subclass of AV.Object for the given AV class name.\n *\n *

Every extension of a AV class will inherit from the most recent\n * previous extension of that class. When a AV.Object is automatically\n * created by parsing JSON, it will use the most recent extension of that\n * class.

\n *\n *

You should call either:

\n   *     var MyClass = AV.Object.extend(\"MyClass\", {\n   *         Instance properties\n   *     }, {\n   *         Class properties\n   *     });
\n * or, for Backbone compatibility:
\n   *     var MyClass = AV.Object.extend({\n   *         className: \"MyClass\",\n   *         Other instance properties\n   *     }, {\n   *         Class properties\n   *     });

\n *\n * @param {String} className The name of the AV class backing this model.\n * @param {Object} protoProps Instance properties to add to instances of the\n * class returned from this method.\n * @param {Object} classProps Class properties to add the class returned from\n * this method.\n * @return {Class} A new subclass of AV.Object.\n */\n AV.Object.extend = function(className, protoProps, classProps) {\n // Handle the case with only two args.\n if (!_.isString(className)) {\n if (className && _.has(className, \"className\")) {\n return AV.Object.extend(className.className, className, protoProps);\n } else {\n throw new Error(\n \"AV.Object.extend's first argument should be the className.\");\n }\n }\n\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n className = \"_User\";\n }\n\n var NewClassObject = null;\n if (_.has(AV.Object._classMap, className)) {\n var OldClassObject = AV.Object._classMap[className];\n // This new subclass has been told to extend both from \"this\" and from\n // OldClassObject. This is multiple inheritance, which isn't supported.\n // For now, let's just pick one.\n if (protoProps || classProps) {\n NewClassObject = OldClassObject._extend(protoProps, classProps);\n } else {\n return OldClassObject;\n }\n } else {\n protoProps = protoProps || {};\n protoProps._className = className;\n NewClassObject = this._extend(protoProps, classProps);\n }\n // Extending a subclass should reuse the classname automatically.\n NewClassObject.extend = function(arg0) {\n if (_.isString(arg0) || (arg0 && _.has(arg0, \"className\"))) {\n return AV.Object.extend.apply(NewClassObject, arguments);\n }\n var newArguments = [className].concat(_.toArray(arguments));\n return AV.Object.extend.apply(NewClassObject, newArguments);\n };\n NewClassObject['new'] = function(attributes, options){\n return new NewClassObject(attributes, options);\n };\n AV.Object._classMap[className] = NewClassObject;\n return NewClassObject;\n };\n\n // ES6 class syntax support\n Object.defineProperty(AV.Object.prototype, 'className', {\n get: function(){\n const className = this._className || this.constructor._LCClassName || this.constructor.name;\n // If someone tries to subclass \"User\", coerce it to the right type.\n if (className === \"User\") {\n return \"_User\";\n }\n return className;\n },\n });\n\n /**\n * Register a class.\n * If a subclass of AV.Object is defined with your own implement\n * rather then AV.Object.extend, the subclass must be registered.\n * @param {Function} klass A subclass of AV.Object\n * @param {String} [name] Specify the name of the class. Useful when the class might be uglified.\n * @example\n * class Person extend AV.Object {}\n * AV.Object.register(Person);\n */\n AV.Object.register = (klass, name) => {\n if (!(klass.prototype instanceof AV.Object)) {\n throw new Error('registered class is not a subclass of AV.Object');\n }\n const className = name || klass.name;\n if (!className.length) {\n throw new Error('registered class must be named');\n }\n if (name) {\n klass._LCClassName = name;\n }\n AV.Object._classMap[className] = klass;\n };\n\n AV.Object._findUnsavedChildren = function(object, children, files) {\n AV._traverse(object, function(object) {\n if (object instanceof AV.Object) {\n object._refreshCache();\n if (object.dirty()) {\n children.push(object);\n }\n return;\n }\n\n if (object instanceof AV.File) {\n if (!object.url() && !object.id) {\n files.push(object);\n }\n return;\n }\n });\n };\n\n AV.Object._canBeSerializedAsValue = function(object) {\n var canBeSerializedAsValue = true;\n\n if (object instanceof AV.Object || object instanceof AV.File) {\n canBeSerializedAsValue = !!object.id;\n\n } else if (_.isArray(object)) {\n AV._arrayEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n\n } else if (_.isObject(object)) {\n AV._objectEach(object, function(child) {\n if (!AV.Object._canBeSerializedAsValue(child)) {\n canBeSerializedAsValue = false;\n }\n });\n }\n\n return canBeSerializedAsValue;\n };\n\n AV.Object._deepSaveAsync = function(object, model, options) {\n var unsavedChildren = [];\n var unsavedFiles = [];\n AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles);\n if(model) {\n unsavedChildren = _.filter(unsavedChildren, function(object) {\n return object != model;\n });\n }\n\n var promise = AV.Promise.resolve();\n _.each(unsavedFiles, function(file) {\n promise = promise.then(function() {\n return file.save();\n });\n });\n\n var objects = _.uniq(unsavedChildren);\n var remaining = _.uniq(objects);\n\n return promise.then(function() {\n return AV.Promise._continueWhile(function() {\n return remaining.length > 0;\n }, function() {\n\n // Gather up all the objects that can be saved in this batch.\n var batch = [];\n var newRemaining = [];\n AV._arrayEach(remaining, function(object) {\n // Limit batches to 20 objects.\n if (batch.length > 20) {\n newRemaining.push(object);\n return;\n }\n\n if (object._canBeSerialized()) {\n batch.push(object);\n } else {\n newRemaining.push(object);\n }\n });\n remaining = newRemaining;\n\n // If we can't save any objects, there must be a circular reference.\n if (batch.length === 0) {\n return AV.Promise.reject(\n new AVError(AVError.OTHER_CAUSE,\n \"Tried to save a batch with a cycle.\"));\n }\n\n // Reserve a spot in every object's save queue.\n var readyToStart = AV.Promise.resolve(_.map(batch, function(object) {\n return object._allPreviousSaves || AV.Promise.resolve();\n }));\n\n // Save a single batch, whether previous saves succeeded or failed.\n const bathSavePromise = readyToStart.then(() =>\n AVRequest(\"batch\", null, null, \"POST\", {\n requests: _.map(batch, function(object) {\n var json = object._getSaveJSON();\n _.extend(json, object._flags);\n var method = \"POST\";\n\n var path = \"/1.1/classes/\" + object.className;\n if (object.id) {\n path = path + \"/\" + object.id;\n method = \"PUT\";\n }\n\n object._startSave();\n\n return {\n method: method,\n path: path,\n body: json\n };\n })\n\n }, options).then(function(response) {\n var error;\n AV._arrayEach(batch, function(object, i) {\n if (response[i].success) {\n object._finishSave(\n object.parse(response[i].success));\n } else {\n error = error || response[i].error;\n object._cancelSave();\n }\n });\n if (error) {\n return AV.Promise.reject(\n new AVError(error.code, error.error));\n }\n\n })\n );\n AV._arrayEach(batch, function(object) {\n object._allPreviousSaves = bathSavePromise;\n });\n return bathSavePromise;\n });\n }).then(function() {\n return object;\n });\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/object.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n\n /**\n * @private\n * @class\n * A AV.Op is an atomic operation that can be applied to a field in a\n * AV.Object. For example, calling object.set(\"foo\", \"bar\")\n * is an example of a AV.Op.Set. Calling object.unset(\"foo\")\n * is a AV.Op.Unset. These operations are stored in a AV.Object and\n * sent to the server as part of object.save() operations.\n * Instances of AV.Op should be immutable.\n *\n * You should not create subclasses of AV.Op or instantiate AV.Op\n * directly.\n */\n AV.Op = function() {\n this._initialize.apply(this, arguments);\n };\n\n AV.Op.prototype = {\n _initialize: function() {}\n };\n\n _.extend(AV.Op, {\n /**\n * To create a new Op, call AV.Op._extend();\n * @private\n */\n _extend: AV._extend,\n\n // A map of __op string to decoder function.\n _opDecoderMap: {},\n\n /**\n * Registers a function to convert a json object with an __op field into an\n * instance of a subclass of AV.Op.\n * @private\n */\n _registerDecoder: function(opName, decoder) {\n AV.Op._opDecoderMap[opName] = decoder;\n },\n\n /**\n * Converts a json object into an instance of a subclass of AV.Op.\n * @private\n */\n _decode: function(json) {\n var decoder = AV.Op._opDecoderMap[json.__op];\n if (decoder) {\n return decoder(json);\n } else {\n return undefined;\n }\n }\n });\n\n /*\n * Add a handler for Batch ops.\n */\n AV.Op._registerDecoder(\"Batch\", function(json) {\n var op = null;\n AV._arrayEach(json.ops, function(nextOp) {\n nextOp = AV.Op._decode(nextOp);\n op = nextOp._mergeWithPrevious(op);\n });\n return op;\n });\n\n /**\n * @private\n * @class\n * A Set operation indicates that either the field was changed using\n * AV.Object.set, or it is a mutable container that was detected as being\n * changed.\n */\n AV.Op.Set = AV.Op._extend(/** @lends AV.Op.Set.prototype */ {\n _initialize: function(value) {\n this._value = value;\n },\n\n /**\n * Returns the new value of this field after the set.\n */\n value: function() {\n return this._value;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return AV._encode(this.value());\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return this.value();\n }\n });\n\n /**\n * A sentinel value that is returned by AV.Op.Unset._estimate to\n * indicate the field should be deleted. Basically, if you find _UNSET as a\n * value in your object, you should remove that key.\n */\n AV.Op._UNSET = {};\n\n /**\n * @private\n * @class\n * An Unset operation indicates that this field has been deleted from the\n * object.\n */\n AV.Op.Unset = AV.Op._extend(/** @lends AV.Op.Unset.prototype */ {\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Delete\" };\n },\n\n _mergeWithPrevious: function(previous) {\n return this;\n },\n\n _estimate: function(oldValue) {\n return AV.Op._UNSET;\n }\n });\n\n AV.Op._registerDecoder(\"Delete\", function(json) {\n return new AV.Op.Unset();\n });\n\n /**\n * @private\n * @class\n * An Increment is an atomic operation where the numeric value for the field\n * will be increased by a given amount.\n */\n AV.Op.Increment = AV.Op._extend(\n /** @lends AV.Op.Increment.prototype */ {\n\n _initialize: function(amount) {\n this._amount = amount;\n },\n\n /**\n * Returns the amount to increment by.\n * @return {Number} the amount to increment by.\n */\n amount: function() {\n return this._amount;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Increment\", amount: this._amount };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.amount());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(previous.value() + this.amount());\n } else if (previous instanceof AV.Op.Increment) {\n return new AV.Op.Increment(this.amount() + previous.amount());\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return this.amount();\n }\n return oldValue + this.amount();\n }\n });\n\n AV.Op._registerDecoder(\"Increment\", function(json) {\n return new AV.Op.Increment(json.amount);\n });\n\n /**\n * @private\n * @class\n * Add is an atomic operation where the given objects will be appended to the\n * array that is stored in this field.\n */\n AV.Op.Add = AV.Op._extend(/** @lends AV.Op.Add.prototype */ {\n _initialize: function(objects) {\n this._objects = objects;\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Add\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Add) {\n return new AV.Op.Add(previous.objects().concat(this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n return oldValue.concat(this.objects());\n }\n }\n });\n\n AV.Op._registerDecoder(\"Add\", function(json) {\n return new AV.Op.Add(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * AddUnique is an atomic operation where the given items will be appended to\n * the array that is stored in this field only if they were not already\n * present in the array.\n */\n AV.Op.AddUnique = AV.Op._extend(\n /** @lends AV.Op.AddUnique.prototype */ {\n\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be added to the array.\n * @return {Array} The objects to be added to the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"AddUnique\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return new AV.Op.Set(this.objects());\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.AddUnique) {\n return new AV.Op.AddUnique(this._estimate(previous.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return _.clone(this.objects());\n } else {\n // We can't just take the _.uniq(_.union(...)) of oldValue and\n // this.objects, because the uniqueness may not apply to oldValue\n // (especially if the oldValue was set via .set())\n var newValue = _.clone(oldValue);\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n var matchingObj = _.find(newValue, function(anObj) {\n return (anObj instanceof AV.Object) && (anObj.id === obj.id);\n });\n if (!matchingObj) {\n newValue.push(obj);\n } else {\n var index = _.indexOf(newValue, matchingObj);\n newValue[index] = obj;\n }\n } else if (!_.contains(newValue, obj)) {\n newValue.push(obj);\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddUnique\", function(json) {\n return new AV.Op.AddUnique(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * Remove is an atomic operation where the given objects will be removed from\n * the array that is stored in this field.\n */\n AV.Op.Remove = AV.Op._extend(/** @lends AV.Op.Remove.prototype */ {\n _initialize: function(objects) {\n this._objects = _.uniq(objects);\n },\n\n /**\n * Returns the objects to be removed from the array.\n * @return {Array} The objects to be removed from the array.\n */\n objects: function() {\n return this._objects;\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n return { __op: \"Remove\", objects: AV._encode(this.objects()) };\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n return previous;\n } else if (previous instanceof AV.Op.Set) {\n return new AV.Op.Set(this._estimate(previous.value()));\n } else if (previous instanceof AV.Op.Remove) {\n return new AV.Op.Remove(_.union(previous.objects(), this.objects()));\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue) {\n if (!oldValue) {\n return [];\n } else {\n var newValue = _.difference(oldValue, this.objects());\n // If there are saved AV Objects being removed, also remove them.\n AV._arrayEach(this.objects(), function(obj) {\n if (obj instanceof AV.Object && obj.id) {\n newValue = _.reject(newValue, function(other) {\n return (other instanceof AV.Object) && (other.id === obj.id);\n });\n }\n });\n return newValue;\n }\n }\n });\n\n AV.Op._registerDecoder(\"Remove\", function(json) {\n return new AV.Op.Remove(AV._decode(json.objects));\n });\n\n /**\n * @private\n * @class\n * A Relation operation indicates that the field is an instance of\n * AV.Relation, and objects are being added to, or removed from, that\n * relation.\n */\n AV.Op.Relation = AV.Op._extend(\n /** @lends AV.Op.Relation.prototype */ {\n\n _initialize: function(adds, removes) {\n this._targetClassName = null;\n\n var self = this;\n\n var pointerToId = function(object) {\n if (object instanceof AV.Object) {\n if (!object.id) {\n throw new Error('You can\\'t add an unsaved AV.Object to a relation.');\n }\n if (!self._targetClassName) {\n self._targetClassName = object.className;\n }\n if (self._targetClassName !== object.className) {\n throw new Error(\"Tried to create a AV.Relation with 2 different types: \" +\n self._targetClassName + \" and \" + object.className + \".\");\n }\n return object.id;\n }\n return object;\n };\n\n this.relationsToAdd = _.uniq(_.map(adds, pointerToId));\n this.relationsToRemove = _.uniq(_.map(removes, pointerToId));\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being added to the\n * relation.\n * @return {Array}\n */\n added: function() {\n var self = this;\n return _.map(this.relationsToAdd, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns an array of unfetched AV.Object that are being removed from\n * the relation.\n * @return {Array}\n */\n removed: function() {\n var self = this;\n return _.map(this.relationsToRemove, function(objectId) {\n var object = AV.Object._create(self._targetClassName);\n object.id = objectId;\n return object;\n });\n },\n\n /**\n * Returns a JSON version of the operation suitable for sending to AV.\n * @return {Object}\n */\n toJSON: function() {\n var adds = null;\n var removes = null;\n var self = this;\n var idToPointer = function(id) {\n return { __type: 'Pointer',\n className: self._targetClassName,\n objectId: id };\n };\n var pointers = null;\n if (this.relationsToAdd.length > 0) {\n pointers = _.map(this.relationsToAdd, idToPointer);\n adds = { \"__op\": \"AddRelation\", \"objects\": pointers };\n }\n\n if (this.relationsToRemove.length > 0) {\n pointers = _.map(this.relationsToRemove, idToPointer);\n removes = { \"__op\": \"RemoveRelation\", \"objects\": pointers };\n }\n\n if (adds && removes) {\n return { \"__op\": \"Batch\", \"ops\": [adds, removes]};\n }\n\n return adds || removes || {};\n },\n\n _mergeWithPrevious: function(previous) {\n if (!previous) {\n return this;\n } else if (previous instanceof AV.Op.Unset) {\n throw new Error('You can\\'t modify a relation after deleting it.');\n } else if (previous instanceof AV.Op.Relation) {\n if (previous._targetClassName &&\n previous._targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be of class \" + previous._targetClassName +\n \", but \" + this._targetClassName + \" was passed in.\");\n }\n var newAdd = _.union(_.difference(previous.relationsToAdd,\n this.relationsToRemove),\n this.relationsToAdd);\n var newRemove = _.union(_.difference(previous.relationsToRemove,\n this.relationsToAdd),\n this.relationsToRemove);\n\n var newRelation = new AV.Op.Relation(newAdd, newRemove);\n newRelation._targetClassName = this._targetClassName;\n return newRelation;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n },\n\n _estimate: function(oldValue, object, key) {\n if (!oldValue) {\n var relation = new AV.Relation(object, key);\n relation.targetClassName = this._targetClassName;\n } else if (oldValue instanceof AV.Relation) {\n if (this._targetClassName) {\n if (oldValue.targetClassName) {\n if (oldValue.targetClassName !== this._targetClassName) {\n throw new Error(\"Related object must be a \" + oldValue.targetClassName +\n \", but a \" + this._targetClassName + \" was passed in.\");\n }\n } else {\n oldValue.targetClassName = this._targetClassName;\n }\n }\n return oldValue;\n } else {\n throw new Error('Op is invalid after previous op.');\n }\n }\n });\n\n AV.Op._registerDecoder(\"AddRelation\", function(json) {\n return new AV.Op.Relation(AV._decode(json.objects), []);\n });\n AV.Op._registerDecoder(\"RemoveRelation\", function(json) {\n return new AV.Op.Relation([], AV._decode(json.objects));\n });\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/op.js","const AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n AV.Installation = AV.Object.extend(\"_Installation\");\n\n /**\n * @namespace\n */\n AV.Push = AV.Push || {};\n\n /**\n * Sends a push notification.\n * @param {Object} data The data of the push notification.\n * @param {String[]} [data.channels] An Array of channels to push to.\n * @param {Date} [data.push_time] A Date object for when to send the push.\n * @param {Date} [data.expiration_time] A Date object for when to expire\n * the push.\n * @param {Number} [data.expiration_interval] The seconds from now to expire the push.\n * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match\n * a set of installations to push to.\n * @param {Date} data.data The data to send as part of the push\n * @param {AuthOptions} [options]\n * @return {Promise}\n */\n AV.Push.send = function(data, options) {\n if (data.where) {\n data.where = data.where.toJSON().where;\n }\n\n if(data.where && data.cql){\n throw new Error(\"Both where and cql can't be set\");\n }\n\n if (data.push_time) {\n data.push_time = data.push_time.toJSON();\n }\n\n if (data.expiration_time) {\n data.expiration_time = data.expiration_time.toJSON();\n }\n\n if (data.expiration_time && data.expiration_time_interval) {\n throw new Error(\"Both expiration_time and expiration_time_interval can't be set\");\n }\n\n var request = AVRequest('push', null, null, 'POST', data, options);\n return request;\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/push.js","const _ = require('underscore');\nconst debug = require('debug')('leancloud:query');\nconst Promise = require('./promise');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst { ensureArray } = require('./utils');\n\nconst requires = (value, message) => {\n if (value === undefined) {\n throw new Error(message);\n }\n};\n\n// AV.Query is a way to create a list of AV.Objects.\nmodule.exports = function(AV) {\n /**\n * Creates a new AV.Query for the given AV.Object subclass.\n * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string.\n * @class\n *\n *

AV.Query defines a query that is used to fetch AV.Objects. The\n * most common use case is finding all objects that match a query through the\n * find method. For example, this sample code fetches all objects\n * of class MyClass. It calls a different function depending on\n * whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.find().then(function(results) {\n   *   // results is an array of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to retrieve a single object whose id is\n * known, through the get method. For example, this sample code fetches an\n * object of class MyClass and id myId. It calls a\n * different function depending on whether the fetch succeeded or not.\n *\n *

\n   * var query = new AV.Query(MyClass);\n   * query.get(myId).then(function(object) {\n   *   // object is an instance of AV.Object.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n *\n *

An AV.Query can also be used to count the number of objects that match\n * the query without retrieving all of those objects. For example, this\n * sample code counts the number of objects of the class MyClass\n *

\n   * var query = new AV.Query(MyClass);\n   * query.count().then(function(number) {\n   *   // There are number instances of MyClass.\n   * }, function(error) {\n   *   // error is an instance of AVError.\n   * });

\n */\n AV.Query = function(objectClass) {\n if (_.isString(objectClass)) {\n objectClass = AV.Object._getSubclass(objectClass);\n }\n\n this.objectClass = objectClass;\n\n this.className = objectClass.prototype.className;\n\n this._where = {};\n this._include = [];\n this._select = [];\n this._limit = -1; // negative limit means, do not send a limit\n this._skip = 0;\n this._extraOptions = {};\n };\n\n /**\n * Constructs a AV.Query that is the OR of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.or(query1, query2, query3);
\n *\n * will create a compoundQuery that is an or of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to OR.\n * @return {AV.Query} The query that is the OR of the passed in queries.\n */\n AV.Query.or = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._orQuery(queries);\n return query;\n };\n\n /**\n * Constructs a AV.Query that is the AND of the passed in queries. For\n * example:\n *
var compoundQuery = AV.Query.and(query1, query2, query3);
\n *\n * will create a compoundQuery that is an 'and' of the query1, query2, and\n * query3.\n * @param {...AV.Query} var_args The list of queries to AND.\n * @return {AV.Query} The query that is the AND of the passed in queries.\n */\n AV.Query.and = function() {\n var queries = _.toArray(arguments);\n var className = null;\n AV._arrayEach(queries, function(q) {\n if (_.isNull(className)) {\n className = q.className;\n }\n\n if (className !== q.className) {\n throw new Error('All queries must be for the same class');\n }\n });\n var query = new AV.Query(className);\n query._andQuery(queries);\n return query;\n };\n\n /**\n * Retrieves a list of AVObjects that satisfy the CQL.\n * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n *\n * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}.\n * @param {Array} pvalues An array contains placeholder values.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n AV.Query.doCloudQuery = function(cql, pvalues, options) {\n var params = { cql: cql };\n if(_.isArray(pvalues)){\n params.pvalues = pvalues;\n } else {\n options = pvalues;\n }\n\n var request = AVRequest('cloudQuery', null, null, 'GET', params, options);\n return request.then(function(response) {\n //query to process results.\n var query = new AV.Query(response.className);\n var results = _.map(response.results, function(json) {\n var obj = query._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(query._processResult(json), true);\n }\n return obj;\n });\n return {\n results: results,\n count: response.count,\n className: response.className\n };\n });\n };\n\n AV.Query._extend = AV._extend;\n\n AV.Query.prototype = {\n //hook to iterate result. Added by dennis.\n _processResult: function(obj){\n return obj;\n },\n\n /**\n * Constructs an AV.Object whose id is already known by fetching data from\n * the server.\n *\n * @param {String} objectId The id of the object to be fetched.\n * @param {AuthOptions} options\n * @return {Promise.}\n */\n get: function(objectId, options) {\n if(!objectId) {\n var errorObject = new AVError(AVError.OBJECT_NOT_FOUND,\n \"Object not found.\");\n throw errorObject;\n }\n\n var self = this;\n\n var obj = self._newObject();\n obj.id = objectId;\n\n var queryJSON = self.toJSON();\n var fetchOptions = {};\n\n if (queryJSON.keys) fetchOptions.keys = queryJSON.keys;\n if (queryJSON.include) fetchOptions.include = queryJSON.include;\n\n return obj.fetch(fetchOptions, options);\n },\n\n /**\n * Returns a JSON representation of this query.\n * @return {Object}\n */\n toJSON: function() {\n var params = {\n where: this._where\n };\n\n if (this._include.length > 0) {\n params.include = this._include.join(\",\");\n }\n if (this._select.length > 0) {\n params.keys = this._select.join(\",\");\n }\n if (this._limit >= 0) {\n params.limit = this._limit;\n }\n if (this._skip > 0) {\n params.skip = this._skip;\n }\n if (this._order !== undefined) {\n params.order = this._order;\n }\n\n AV._objectEach(this._extraOptions, function(v, k) {\n params[k] = v;\n });\n\n return params;\n },\n\n _newObject: function(response){\n var obj;\n if (response && response.className) {\n obj = new AV.Object(response.className);\n } else {\n obj = new this.objectClass();\n }\n return obj;\n },\n _createRequest(params = this.toJSON(), options) {\n if (JSON.stringify(params).length > 2000) {\n const body = {\n requests: [{\n method: 'GET',\n path: `/1.1/classes/${this.className}`,\n params,\n }],\n };\n return AVRequest('batch', null, null, 'POST', body, options)\n .then(response => {\n const result = response[0];\n if (result.success) {\n return result.success;\n }\n const error = new Error(result.error.error || 'Unknown batch error');\n error.code = result.error.code;\n throw error;\n });\n }\n return AVRequest('classes', this.className, null, \"GET\", params, options);\n },\n\n _parseResponse(response) {\n return _.map(response.results, (json) => {\n var obj = this._newObject(response);\n if (obj._finishFetch) {\n obj._finishFetch(this._processResult(json), true);\n }\n return obj;\n });\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find(options) {\n const request = this._createRequest(undefined, options);\n return request.then(this._parseResponse.bind(this));\n },\n\n /**\n * scan a Query. masterKey required.\n *\n * @since 2.1.0\n * @param {object} [options]\n * @param {string} [options.orderedBy] specify the key to sort\n * @param {number} [options.batchSize] specify the batch size for each request\n * @param {AuthOptions} [authOptions]\n * @return {AsyncIterator.}\n * @example const scan = new AV.Query(TestClass).scan({\n * orderedBy: 'objectId',\n * batchSize: 10,\n * }, {\n * useMasterKey: true,\n * });\n * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next()));\n * getTen().then(results => {\n * // results are fisrt 10 instances of TestClass\n * return getTen();\n * }).then(results => {\n * // 11 - 20\n * });\n */\n scan({\n orderedBy,\n batchSize,\n } = {}, authOptions) {\n const condition = this.toJSON();\n debug('scan %O', condition);\n if (condition.order) {\n console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.');\n delete condition.order;\n }\n if (condition.skip) {\n console.warn('The skip option of the query is ignored for Query#scan.');\n delete condition.skip;\n }\n if (condition.limit) {\n console.warn('The limit option of the query is ignored for Query#scan.');\n delete condition.limit;\n }\n if (orderedBy) condition.scan_key = orderedBy;\n if (batchSize) condition.limit = batchSize;\n let promise = Promise.resolve([]);\n let cursor;\n let done = false;\n return {\n next: () => {\n promise = promise.then((remainResults) => {\n if (done) return [];\n if (remainResults.length > 1) return remainResults;\n // no cursor means we have reached the end\n // except for the first time\n if (!cursor && remainResults.length !== 0) {\n done = true;\n return remainResults;\n }\n // when only 1 item left in queue\n // start the next request to see if it is the last one\n return AVRequest(\n 'scan/classes',\n this.className,\n null,\n 'GET',\n cursor ? _.extend({}, condition, { cursor }) : condition,\n authOptions\n ).then(response => {\n cursor = response.cursor;\n return this._parseResponse(response);\n }).then(results => {\n if (!results.length) done = true;\n return remainResults.concat(results);\n });\n });\n return promise\n .then(remainResults => remainResults.shift())\n .then(result => ({\n value: result,\n done,\n }));\n },\n };\n },\n\n /**\n * Delete objects retrieved by this query.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the save\n * completes.\n */\n destroyAll: function(options){\n var self = this;\n return self.find(options).then(function(objects){\n return AV.Object.destroyAll(objects, options);\n });\n },\n\n /**\n * Counts the number of objects that match this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the count when\n * the query completes.\n */\n count: function(options) {\n var params = this.toJSON();\n params.limit = 0;\n params.count = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return response.count;\n });\n },\n\n /**\n * Retrieves at most one AV.Object that satisfies this query.\n *\n * @param {AuthOptions} options\n * @return {Promise} A promise that is resolved with the object when\n * the query completes.\n */\n first: function(options) {\n var self = this;\n\n var params = this.toJSON();\n params.limit = 1;\n var request = this._createRequest(params, options);\n\n return request.then(function(response) {\n return _.map(response.results, function(json) {\n var obj = self._newObject();\n if (obj._finishFetch) {\n obj._finishFetch(self._processResult(json), true);\n }\n return obj;\n })[0];\n });\n },\n\n /**\n * Sets the number of results to skip before returning any results.\n * This is useful for pagination.\n * Default is to skip zero results.\n * @param {Number} n the number of results to skip.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n skip: function(n) {\n requires(n, 'undefined is not a valid skip value');\n this._skip = n;\n return this;\n },\n\n /**\n * Sets the limit of the number of results to return. The default limit is\n * 100, with a maximum of 1000 results being returned at a time.\n * @param {Number} n the number of results to limit to.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n limit: function(n) {\n requires(n, 'undefined is not a valid limit value');\n this._limit = n;\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that the AV.Object must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n equalTo: function(key, value) {\n requires(key, 'undefined is not a valid key');\n requires(value, 'undefined is not a valid value');\n this._where[key] = AV._encode(value);\n return this;\n },\n\n /**\n * Helper for condition queries\n * @private\n */\n _addCondition: function(key, condition, value) {\n requires(key, 'undefined is not a valid condition key');\n requires(condition, 'undefined is not a valid condition');\n requires(value, 'undefined is not a valid condition value');\n\n // Check if we already have a condition\n if (!this._where[key]) {\n this._where[key] = {};\n }\n this._where[key][condition] = AV._encode(value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular\n * array key's length to be equal to the provided value.\n * @param {String} key The array key to check.\n * @param value The length value.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n sizeEqualTo: function(key, value) {\n this._addCondition(key, \"$size\", value);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be not equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that must not be equalled.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notEqualTo: function(key, value) {\n this._addCondition(key, \"$ne\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThan: function(key, value) {\n this._addCondition(key, \"$lt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThan: function(key, value) {\n this._addCondition(key, \"$gt\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be less than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an upper bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n lessThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$lte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be greater than or equal to the provided value.\n * @param {String} key The key to check.\n * @param value The value that provides an lower bound.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n greaterThanOrEqualTo: function(key, value) {\n this._addCondition(key, \"$gte\", value);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containedIn: function(key, values) {\n this._addCondition(key, \"$in\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * not be contained in the provided list of values.\n * @param {String} key The key to check.\n * @param {Array} values The values that will not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n notContainedIn: function(key, values) {\n this._addCondition(key, \"$nin\", values);\n return this;\n },\n\n /**\n * Add a constraint to the query that requires a particular key's value to\n * contain each one of the provided list of values.\n * @param {String} key The key to check. This key's value must be an array.\n * @param {Array} values The values that will match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n containsAll: function(key, values) {\n this._addCondition(key, \"$all\", values);\n return this;\n },\n\n\n /**\n * Add a constraint for finding objects that contain the given key.\n * @param {String} key The key that should exist.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n exists: function(key) {\n this._addCondition(key, \"$exists\", true);\n return this;\n },\n\n /**\n * Add a constraint for finding objects that do not contain a given key.\n * @param {String} key The key that should not exist\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotExist: function(key) {\n this._addCondition(key, \"$exists\", false);\n return this;\n },\n\n /**\n * Add a regular expression constraint for finding string values that match\n * the provided regular expression.\n * This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {RegExp} regex The regular expression pattern to match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matches: function(key, regex, modifiers) {\n this._addCondition(key, \"$regex\", regex);\n if (!modifiers) { modifiers = \"\"; }\n // Javascript regex options support mig as inline options but store them\n // as properties of the object. We support mi & should migrate them to\n // modifiers\n if (regex.ignoreCase) { modifiers += 'i'; }\n if (regex.multiline) { modifiers += 'm'; }\n\n if (modifiers && modifiers.length) {\n this._addCondition(key, \"$options\", modifiers);\n }\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value matches a AV.Query\n * constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$inQuery\", queryJSON);\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not matches a\n * AV.Query constraint.\n * @param {String} key The key that the contains the object to match the\n * query.\n * @param {AV.Query} query The query that should not match.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchQuery: function(key, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$notInQuery\", queryJSON);\n return this;\n },\n\n\n /**\n * Add a constraint that requires that a key's value matches a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * matched.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n matchesKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$select\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add a constraint that requires that a key's value not match a value in\n * an object returned by a different AV.Query.\n * @param {String} key The key that contains the value that is being\n * excluded.\n * @param {String} queryKey The key in the objects returned by the query to\n * match against.\n * @param {AV.Query} query The query to run.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n doesNotMatchKeyInQuery: function(key, queryKey, query) {\n var queryJSON = query.toJSON();\n queryJSON.className = query.className;\n this._addCondition(key, \"$dontSelect\",\n { key: queryKey, query: queryJSON });\n return this;\n },\n\n /**\n * Add constraint that at least one of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _orQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$or = queryJSON;\n return this;\n },\n\n /**\n * Add constraint that both of the passed in queries matches.\n * @param {Array} queries\n * @return {AV.Query} Returns the query, so you can chain this call.\n * @private\n */\n _andQuery: function(queries) {\n var queryJSON = _.map(queries, function(q) {\n return q.toJSON().where;\n });\n\n this._where.$and = queryJSON;\n return this;\n },\n\n\n /**\n * Converts a string into a regex that matches it.\n * Surrounding with \\Q .. \\E does this, we just need to escape \\E's in\n * the text separately.\n * @private\n */\n _quote: function(s) {\n return \"\\\\Q\" + s.replace(\"\\\\E\", \"\\\\E\\\\\\\\E\\\\Q\") + \"\\\\E\";\n },\n\n /**\n * Add a constraint for finding string values that contain a provided\n * string. This may be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} substring The substring that the value must contain.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n contains: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that start with a provided\n * string. This query will use the backend index, so it will be fast even\n * for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} prefix The substring that the value must start with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n startsWith: function(key, value) {\n this._addCondition(key, \"$regex\", \"^\" + this._quote(value));\n return this;\n },\n\n /**\n * Add a constraint for finding string values that end with a provided\n * string. This will be slow for large datasets.\n * @param {String} key The key that the string to match is stored in.\n * @param {String} suffix The substring that the value must end with.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n endsWith: function(key, value) {\n this._addCondition(key, \"$regex\", this._quote(value) + \"$\");\n return this;\n },\n\n /**\n * Sorts the results in ascending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n ascending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = key;\n return this;\n },\n\n /**\n * Also sorts the results in ascending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addAscending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',' + key;\n else\n this._order = key;\n return this;\n },\n\n /**\n * Sorts the results in descending order by the given key.\n *\n * @param {String} key The key to order by.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n descending: function(key) {\n requires(key, 'undefined is not a valid key');\n this._order = \"-\" + key;\n return this;\n },\n\n /**\n * Also sorts the results in descending order by the given key. The previous sort keys have\n * precedence over this key.\n *\n * @param {String} key The key to order by\n * @return {AV.Query} Returns the query so you can chain this call.\n */\n addDescending: function(key){\n requires(key, 'undefined is not a valid key');\n if(this._order)\n this._order += ',-' + key;\n else\n this._order = '-' + key;\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n near: function(key, point) {\n if (!(point instanceof AV.GeoPoint)) {\n // Try to cast it to a GeoPoint, so that near(\"loc\", [20,30]) works.\n point = new AV.GeoPoint(point);\n }\n this._addCondition(key, \"$nearSphere\", point);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param maxDistance Maximum distance (in radians) of results to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinRadians: function(key, point, distance) {\n this.near(key, point);\n this._addCondition(key, \"$maxDistance\", distance);\n return this;\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 3958.8 miles.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in miles) of results to\n * return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinMiles: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 3958.8);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given and within the maximum distance given.\n * Radius of earth used is 6371.0 kilometers.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Number} maxDistance Maximum distance (in kilometers) of results\n * to return.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinKilometers: function(key, point, distance) {\n return this.withinRadians(key, point, distance / 6371.0);\n },\n\n /**\n * Add a constraint to the query that requires a particular key's\n * coordinates be contained within a given rectangular geographic bounding\n * box.\n * @param {String} key The key to be constrained.\n * @param {AV.GeoPoint} southwest\n * The lower-left inclusive corner of the box.\n * @param {AV.GeoPoint} northeast\n * The upper-right inclusive corner of the box.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n withinGeoBox: function(key, southwest, northeast) {\n if (!(southwest instanceof AV.GeoPoint)) {\n southwest = new AV.GeoPoint(southwest);\n }\n if (!(northeast instanceof AV.GeoPoint)) {\n northeast = new AV.GeoPoint(northeast);\n }\n this._addCondition(key, '$within', { '$box': [southwest, northeast] });\n return this;\n },\n\n /**\n * Include nested AV.Objects for the provided key. You can use dot\n * notation to specify which fields in the included object are also fetch.\n * @param {String[]} keys The name of the key to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n include: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._include = this._include.concat(ensureArray(keys))\n });\n return this;\n },\n\n /**\n * Restrict the fields of the returned AV.Objects to include only the\n * provided keys. If this is called multiple times, then all of the keys\n * specified in each of the calls will be included.\n * @param {String[]} keys The names of the keys to include.\n * @return {AV.Query} Returns the query, so you can chain this call.\n */\n select: function(keys) {\n requires(keys, 'undefined is not a valid key');\n _(arguments).forEach(keys => {\n this._select = this._select.concat(ensureArray(keys));\n });\n return this;\n },\n\n /**\n * Iterates over each result of a query, calling a callback for each one. If\n * the callback returns a promise, the iteration will not continue until\n * that promise has been fulfilled. If the callback returns a rejected\n * promise, then iteration will stop with that error. The items are\n * processed in an unspecified order. The query may not have any sort order,\n * and may not use limit or skip.\n * @param callback {Function} Callback that will be called with each result\n * of the query.\n * @return {Promise} A promise that will be fulfilled once the\n * iteration has completed.\n */\n each: function(callback, options = {}) {\n\n if (this._order || this._skip || (this._limit >= 0)) {\n var error =\n new Error(\"Cannot iterate on a query with sort, skip, or limit.\");\n return AV.Promise.reject(error);\n }\n\n var query = new AV.Query(this.objectClass);\n // We can override the batch size from the options.\n // This is undocumented, but useful for testing.\n query._limit = options.batchSize || 100;\n query._where = _.clone(this._where);\n query._include = _.clone(this._include);\n\n query.ascending('objectId');\n\n var finished = false;\n return AV.Promise._continueWhile(function() {\n return !finished;\n\n }, function() {\n return query.find(options).then(function(results) {\n var callbacksDone = AV.Promise.resolve();\n _.each(results, function(result) {\n callbacksDone = callbacksDone.then(function() {\n return callback(result);\n });\n });\n\n return callbacksDone.then(function() {\n if (results.length >= query._limit) {\n query.greaterThan(\"objectId\", results[results.length - 1].id);\n } else {\n finished = true;\n }\n });\n });\n });\n }\n };\n\n AV.FriendShipQuery = AV.Query._extend({\n _objectClass: AV.User,\n _newObject: function(){\n return new AV.User();\n },\n _processResult: function(json){\n if(json && json[this._friendshipTag]) {\n var user = json[this._friendshipTag];\n if(user.__type === 'Pointer' && user.className === '_User'){\n delete user.__type;\n delete user.className;\n }\n return user;\n } else {\n return null;\n }\n },\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/query.js","var _ = require('underscore');\n\nmodule.exports = function(AV) {\n /**\n * Creates a new Relation for the given parent object and key. This\n * constructor should rarely be used directly, but rather created by\n * {@link AV.Object#relation}.\n * @param {AV.Object} parent The parent of this relation.\n * @param {String} key The key for this relation on the parent.\n * @see AV.Object#relation\n * @class\n *\n *

\n * A class that is used to access all of the children of a many-to-many\n * relationship. Each instance of AV.Relation is associated with a\n * particular parent object and key.\n *

\n */\n AV.Relation = function(parent, key) {\n if (! _.isString(key)) {\n throw new TypeError('key must be a string');\n }\n this.parent = parent;\n this.key = key;\n this.targetClassName = null;\n };\n\n /**\n * Creates a query that can be used to query the parent objects in this relation.\n * @param {String} parentClass The parent class or name.\n * @param {String} relationKey The relation field key in parent.\n * @param {AV.Object} child The child object.\n * @return {AV.Query}\n */\n AV.Relation.reverseQuery = function(parentClass, relationKey, child){\n var query = new AV.Query(parentClass);\n query.equalTo(relationKey, child._toPointer());\n return query;\n };\n\n AV.Relation.prototype = {\n /**\n * Makes sure that this relation has the right parent and key.\n * @private\n */\n _ensureParentAndKey: function(parent, key) {\n this.parent = this.parent || parent;\n this.key = this.key || key;\n if (this.parent !== parent) {\n throw new Error(\"Internal Error. Relation retrieved from two different Objects.\");\n }\n if (this.key !== key) {\n throw new Error(\"Internal Error. Relation retrieved from two different keys.\");\n }\n },\n\n /**\n * Adds a AV.Object or an array of AV.Objects to the relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to add.\n */\n add: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation(objects, []);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Removes a AV.Object or an array of AV.Objects from this relation.\n * @param {AV.Object|AV.Object[]} objects The item or items to remove.\n */\n remove: function(objects) {\n if (!_.isArray(objects)) {\n objects = [objects];\n }\n\n var change = new AV.Op.Relation([], objects);\n this.parent.set(this.key, change);\n this.targetClassName = change._targetClassName;\n },\n\n /**\n * Returns a JSON version of the object suitable for saving to disk.\n * @return {Object}\n */\n toJSON: function() {\n return { \"__type\": \"Relation\", \"className\": this.targetClassName };\n },\n\n /**\n * Returns a AV.Query that is limited to objects in this\n * relation.\n * @return {AV.Query}\n */\n query: function() {\n var targetClass;\n var query;\n if (!this.targetClassName) {\n targetClass = AV.Object._getSubclass(this.parent.className);\n query = new AV.Query(targetClass);\n query._extraOptions.redirectClassNameForKey = this.key;\n } else {\n targetClass = AV.Object._getSubclass(this.targetClassName);\n query = new AV.Query(targetClass);\n }\n query._addCondition(\"$relatedTo\", \"object\", this.parent._toPointer());\n query._addCondition(\"$relatedTo\", \"key\", this.key);\n\n return query;\n }\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/relation.js","const _ = require('underscore');\nconst AVError = require('./error');\n\nmodule.exports = function(AV) {\n AV.Role = AV.Object.extend(\"_Role\", /** @lends AV.Role.prototype */ {\n // Instance Methods\n\n /**\n * Represents a Role on the AV server. Roles represent groupings of\n * Users for the purposes of granting permissions (e.g. specifying an ACL\n * for an Object). Roles are specified by their sets of child users and\n * child roles, all of which are granted any permissions that the parent\n * role has.\n *\n *

Roles must have a name (which cannot be changed after creation of the\n * role), and must specify an ACL.

\n * An AV.Role is a local representation of a role persisted to the AV\n * cloud.\n * @class AV.Role\n * @param {String} name The name of the Role to create.\n * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL\n * `{'*': { read: true }}` will be used.\n */\n constructor: function(name, acl, noDefaultACL) {\n if (_.isString(name)) {\n AV.Object.prototype.constructor.call(this, null, null);\n this.setName(name);\n } else {\n AV.Object.prototype.constructor.call(this, name, acl);\n }\n if (acl === undefined) {\n if (!noDefaultACL) {\n if(!this.getACL()) {\n console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.');\n var defaultAcl = new AV.ACL();\n defaultAcl.setPublicReadAccess(true); \n this.setACL(defaultAcl);\n }\n }\n } else if (!(acl instanceof AV.ACL)) {\n throw new TypeError('acl must be an instance of AV.ACL');\n } else {\n this.setACL(acl);\n }\n },\n\n /**\n * Gets the name of the role. You can alternatively call role.get(\"name\")\n *\n * @return {String} the name of the role.\n */\n getName: function() {\n return this.get(\"name\");\n },\n\n /**\n * Sets the name for a role. This value must be set before the role has\n * been saved to the server, and cannot be set once the role has been\n * saved.\n *\n *

\n * A role's name can only contain alphanumeric characters, _, -, and\n * spaces.\n *

\n *\n *

This is equivalent to calling role.set(\"name\", name)

\n *\n * @param {String} name The name of the role.\n */\n setName: function(name, options) {\n return this.set(\"name\", name, options);\n },\n\n /**\n * Gets the AV.Relation for the AV.Users that are direct\n * children of this role. These users are granted any privileges that this\n * role has been granted (e.g. read or write access through ACLs). You can\n * add or remove users from the role through this relation.\n *\n *

This is equivalent to calling role.relation(\"users\")

\n *\n * @return {AV.Relation} the relation for the users belonging to this\n * role.\n */\n getUsers: function() {\n return this.relation(\"users\");\n },\n\n /**\n * Gets the AV.Relation for the AV.Roles that are direct\n * children of this role. These roles' users are granted any privileges that\n * this role has been granted (e.g. read or write access through ACLs). You\n * can add or remove child roles from this role through this relation.\n *\n *

This is equivalent to calling role.relation(\"roles\")

\n *\n * @return {AV.Relation} the relation for the roles belonging to this\n * role.\n */\n getRoles: function() {\n return this.relation(\"roles\");\n },\n\n /**\n * @ignore\n */\n validate: function(attrs, options) {\n if (\"name\" in attrs && attrs.name !== this.getName()) {\n var newName = attrs.name;\n if (this.id && this.id !== attrs.objectId) {\n // Check to see if the objectId being set matches this.id.\n // This happens during a fetch -- the id is set before calling fetch.\n // Let the name be set in this case.\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only be set before it has been saved.\");\n }\n if (!_.isString(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name must be a String.\");\n }\n if (!(/^[0-9a-zA-Z\\-_ ]+$/).test(newName)) {\n return new AVError(AVError.OTHER_CAUSE,\n \"A role's name can only contain alphanumeric characters, _,\" +\n \" -, and spaces.\");\n }\n }\n if (AV.Object.prototype.validate) {\n return AV.Object.prototype.validate.call(this, attrs, options);\n }\n return false;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/role.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n /**\n * A builder to generate sort string for app searching.For example:\n * @class\n * @since 0.5.1\n * @example\n * var builder = new AV.SearchSortBuilder();\n * builder.ascending('key1').descending('key2','max');\n * var query = new AV.SearchQuery('Player');\n * query.sortBy(builder);\n * query.find().then();\n */\n AV.SearchSortBuilder = function() {\n this._sortFields = [];\n };\n\n AV.SearchSortBuilder.prototype = {\n _addField: function(key, order, mode, missing) {\n var field = {};\n field[key] = {\n order: order || 'asc',\n mode: mode ||'avg',\n missing: '_' + (missing || 'last')\n };\n this._sortFields.push(field);\n return this;\n },\n\n\n /**\n * Sorts the results in ascending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n ascending: function(key, mode, missing) {\n return this._addField(key, 'asc', mode, missing);\n },\n\n /**\n * Sorts the results in descending order by the given key and options.\n *\n * @param {String} key The key to order by.\n * @param {String} mode The sort mode, default is 'avg', you can choose\n * 'max' or 'min' too.\n * @param {String} missing The missing key behaviour, default is 'last',\n * you can choose 'first' too.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n descending: function(key, mode, missing) {\n return this._addField(key, 'desc', mode, missing);\n },\n\n /**\n * Add a proximity based constraint for finding objects with key point\n * values near the point given.\n * @param {String} key The key that the AV.GeoPoint is stored in.\n * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.\n * @param {Object} options The other options such as mode,order, unit etc.\n * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call.\n */\n whereNear: function(key, point, options) {\n options = options || {};\n var field = {};\n var geo = {\n lat: point.latitude,\n lon: point.longitude\n };\n var m = {\n order: options.order || 'asc',\n mode: options.mode || 'avg',\n unit: options.unit || 'km'\n };\n m[key] = geo;\n field['_geo_distance'] = m;\n\n this._sortFields.push(field);\n return this;\n },\n\n /**\n * Build a sort string by configuration.\n * @return {String} the sort string.\n */\n build: function() {\n return JSON.stringify(AV._encode(this._sortFields));\n }\n };\n\n /**\n * App searching query.Use just like AV.Query:\n *\n * Visit App Searching Guide\n * for more details.\n * @class\n * @since 0.5.1\n * @example\n * var query = new AV.SearchQuery('Player');\n * query.queryString('*');\n * query.find().then(function(results) {\n * console.log('Found %d objects', query.hits());\n * //Process results\n * });\n */\n AV.SearchQuery = AV.Query._extend(/** @lends AV.SearchQuery.prototype */{\n _sid: null,\n _hits: 0,\n _queryString: null,\n _highlights: null,\n _sortBuilder: null,\n _createRequest: function(params, options){\n return AVRequest('search/select', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n /**\n * Sets the sid of app searching query.Default is null.\n * @param {String} sid Scroll id for searching.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n sid: function(sid) {\n this._sid = sid;\n return this;\n },\n\n /**\n * Sets the query string of app searching.\n * @param {String} q The query string.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n queryString: function(q) {\n this._queryString = q;\n return this;\n },\n\n\n /**\n * Sets the highlight fields. Such as\n *
\n     *   query.highlights('title');\n     *   //or pass an array.\n     *   query.highlights(['title', 'content'])\n     * 
\n * @param {String[]} highlights a list of fields.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n */\n highlights: function(highlights) {\n var objects;\n if (highlights && _.isString(highlights)) {\n objects = arguments;\n } else {\n objects = highlights;\n }\n this._highlights = objects;\n return this;\n },\n\n /**\n * Sets the sort builder for this query.\n * @see AV.SearchSortBuilder\n * @param { AV.SearchSortBuilder} builder The sort builder.\n * @return {AV.SearchQuery} Returns the query, so you can chain this call.\n *\n */\n sortBy: function(builder) {\n this._sortBuilder = builder;\n return this;\n },\n\n /**\n * Returns the number of objects that match this query.\n * @return {Number}\n */\n hits: function() {\n if (!this._hits) {\n this._hits = 0;\n }\n return this._hits;\n },\n\n _processResult: function(json){\n delete json['className'];\n delete json['_app_url'];\n delete json['_deeplink'];\n return json;\n },\n\n /**\n * Returns true when there are more documents can be retrieved by this\n * query instance, you can call find function to get more results.\n * @see AV.SearchQuery#find\n * @return {Boolean}\n */\n hasMore: function() {\n return !this._hitEnd;\n },\n\n /**\n * Reset current query instance state(such as sid, hits etc) except params\n * for a new searching. After resetting, hasMore() will return true.\n */\n reset: function() {\n this._hitEnd = false;\n this._sid = null;\n this._hits = 0;\n },\n\n /**\n * Retrieves a list of AVObjects that satisfy this query.\n * Either options.success or options.error is called when the find\n * completes.\n *\n * @see AV.Query#find\n * @return {AV.Promise} A promise that is resolved with the results when\n * the query completes.\n */\n find: function() {\n var self = this;\n\n var request = this._createRequest();\n\n return request.then(function(response) {\n //update sid for next querying.\n if(response.sid) {\n self._oldSid = self._sid;\n self._sid = response.sid;\n } else {\n self._sid = null;\n self._hitEnd = true;\n }\n self._hits = response.hits || 0;\n\n return _.map(response.results, function(json) {\n if(json.className) {\n response.className = json.className;\n }\n var obj = self._newObject(response);\n obj.appURL = json['_app_url'];\n obj._finishFetch(self._processResult(json), true);\n return obj;\n });\n });\n },\n\n toJSON: function(){\n var params = AV.SearchQuery.__super__.toJSON.call(this);\n delete params.where;\n if(this.className) {\n params.clazz = this.className;\n }\n if(this._sid) {\n params.sid = this._sid;\n }\n if(!this._queryString) {\n throw new Error('Please set query string.');\n } else {\n params.q = this._queryString;\n }\n if(this._highlights) {\n params.highlights = this._highlights.join(',');\n }\n if(this._sortBuilder && params.order) {\n throw new Error('sort and order can not be set at same time.');\n }\n if(this._sortBuilder) {\n params.sort = this._sortBuilder.build();\n }\n\n return params;\n }\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/search.js","const _ = require('underscore');\nconst AVRequest = require('./request').request;\n\nmodule.exports = function(AV) {\n const getUser = (options = {}) => AV.User.currentAsync()\n .then(currUser => currUser || AV.User._fetchUserBySessionToken(options.sessionToken));\n\n const getUserPointer = options => getUser(options)\n .then(currUser => AV.Object.createWithoutData('_User', currUser.id)._toPointer());\n\n /**\n * Contains functions to deal with Status in LeanCloud.\n * @class\n */\n AV.Status = function(imageUrl, message) {\n this.data = {};\n this.inboxType = 'default';\n this.query = null;\n if(imageUrl && typeof imageUrl === 'object') {\n this.data = imageUrl;\n } else {\n if(imageUrl){\n this.data.image = imageUrl;\n }\n if(message){\n this.data.message = message;\n }\n }\n return this;\n };\n\n AV.Status.prototype = {\n /**\n * Gets the value of an attribute in status data.\n * @param {String} attr The string name of an attribute.\n */\n get: function(attr){\n return this.data[attr];\n },\n /**\n * Sets a hash of model attributes on the status data.\n * @param {String} key The key to set.\n * @param {} value The value to give it.\n */\n set: function(key, value){\n this.data[key] = value;\n return this;\n },\n /**\n * Destroy this status,then it will not be avaiable in other user's inboxes.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the destroy\n * completes.\n */\n destroy: function(options){\n if(!this.id)\n return AV.Promise.reject(new Error('The status id is not exists.'));\n var request = AVRequest('statuses', null, this.id, 'DELETE', options);\n return request;\n },\n /**\n * Cast the AV.Status object to an AV.Object pointer.\n * @return {AV.Object} A AV.Object pointer.\n */\n toObject: function(){\n if(!this.id)\n return null;\n return AV.Object.createWithoutData('_Status', this.id);\n },\n _getDataJSON: function() {\n var json = _.clone(this.data);\n return AV._encode(json);\n },\n /**\n * Send a status by a AV.Query object.\n * @since 0.3.0\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a status to male users\n * var status = new AVStatus('image url', 'a message');\n * status.query = new AV.Query('_User');\n * status.query.equalTo('gender', 'male');\n * status.send().then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n send: function(options = {}){\n if(!options.sessionToken && !AV.User.current()) {\n throw new Error('Please signin an user.');\n }\n if(!this.query){\n return AV.Status.sendStatusToFollowers(this, options);\n }\n\n return getUserPointer(options).then(currUser => {\n var query = this.query.toJSON();\n query.className = this.query.className;\n var data = {};\n data.query = query;\n this.data = this.data || {};\n this.data.source = this.data.source || currUser;\n data.data = this._getDataJSON();\n data.inboxType = this.inboxType || 'default';\n\n return AVRequest('statuses', null, null, 'POST', data, options);\n })\n .then((response) => {\n this.id = response.objectId;\n this.createdAt = AV._parseDate(response.createdAt);\n return this;\n });\n },\n\n _finishFetch: function(serverData){\n this.id = serverData.objectId;\n this.createdAt = AV._parseDate(serverData.createdAt);\n this.updatedAt = AV._parseDate(serverData.updatedAt);\n this.messageId = serverData.messageId;\n delete serverData.messageId;\n delete serverData.objectId;\n delete serverData.createdAt;\n delete serverData.updatedAt;\n this.data = AV._decode(serverData);\n }\n };\n\n /**\n * Send a status to current signined user's followers.\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendStatusToFollowers(status).then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendStatusToFollowers = function(status, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_Follower';\n query.keys = 'follower';\n query.where = {user: currUser};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = status.inboxType || 'default';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n *

Send a status from current signined user to other user's private status inbox.

\n * @since 0.3.0\n * @param {AV.Status} status A status object to be send to followers.\n * @param {String} target The target user or user's objectId.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the send\n * completes.\n * @example\n * // send a private status to user '52e84e47e4b0f8de283b079b'\n * var status = new AVStatus('image url', 'a message');\n * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){\n * //send status successfully.\n * }, function(err){\n * //an error threw.\n * console.dir(err);\n * });\n */\n AV.Status.sendPrivateStatus = function(status, target, options = {}) {\n if(!options.sessionToken && !AV.User.current()){\n throw new Error('Please signin an user.');\n }\n if(!target){\n throw new Error(\"Invalid target user.\");\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error(\"Invalid target user.\");\n }\n return getUserPointer(options).then(currUser => {\n var query = {};\n query.className = '_User';\n query.where = {objectId: userObjectId};\n var data = {};\n data.query = query;\n status.data = status.data || {};\n status.data.source = status.data.source || currUser;\n data.data = status._getDataJSON();\n data.inboxType = 'private';\n status.inboxType = 'private';\n\n var request = AVRequest('statuses', null, null, 'POST', data, options);\n return request.then(function(response){\n status.id = response.objectId;\n status.createdAt = AV._parseDate(response.createdAt);\n return status;\n });\n });\n };\n\n /**\n * Count unread statuses in someone's inbox.\n * @since 0.3.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the count\n * completes.\n * @example\n * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.countUnreadStatuses = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options);\n });\n };\n\n /**\n * reset unread statuses count in someone's inbox.\n * @since 2.1.0\n * @param {Object} owner The status owner.\n * @param {String} inboxType The inbox type, 'default' by default.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the reset\n * completes.\n * @example\n * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){\n * console.log(response.unread); //unread statuses number.\n * console.log(response.total); //total statuses number.\n * });\n */\n AV.Status.resetUnreadCount = function(owner, inboxType = 'default', options = {}){\n if (!_.isString(inboxType)) options = inboxType;\n if(!options.sessionToken && owner == null && !AV.User.current()) {\n throw new Error('Please signin an user or pass the owner objectId.');\n }\n return getUser(options).then(owner => {\n var params = {};\n params.inboxType = AV._encode(inboxType);\n params.owner = AV._encode(owner);\n return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options);\n });\n };\n\n /**\n * Create a status query to find someone's published statuses.\n * @since 0.3.0\n * @param {Object} source The status source.\n * @return {AV.Query} The query object for status.\n * @example\n * //Find current user's published statuses.\n * var query = AV.Status.statusQuery(AV.User.current());\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.statusQuery = function(source){\n var query = new AV.Query('_Status');\n if(source){\n query.equalTo('source', source);\n }\n return query;\n };\n\n /**\n *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

\n * @class\n */\n AV.InboxQuery = AV.Query._extend(/** @lends AV.InboxQuery.prototype */{\n _objectClass: AV.Status,\n _sinceId: 0,\n _maxId: 0,\n _inboxType: 'default',\n _owner: null,\n _newObject: function(){\n return new AV.Status();\n },\n _createRequest: function(params, options){\n return AVRequest('subscribe/statuses', null, null, 'GET',\n params || this.toJSON(), options);\n },\n\n\n /**\n * Sets the messageId of results to skip before returning any results.\n * This is useful for pagination.\n * Default is zero.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n sinceId: function(id){\n this._sinceId = id;\n return this;\n },\n /**\n * Sets the maximal messageId of results。\n * This is useful for pagination.\n * Default is zero that is no limition.\n * @param {Number} n the mesage id.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n maxId: function(id){\n this._maxId = id;\n return this;\n },\n /**\n * Sets the owner of the querying inbox.\n * @param {Object} owner The inbox owner.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n owner: function(owner){\n this._owner = owner;\n return this;\n },\n /**\n * Sets the querying inbox type.default is 'default'.\n * @param {Object} owner The inbox type.\n * @return {AV.InboxQuery} Returns the query, so you can chain this call.\n */\n inboxType: function(type){\n this._inboxType = type;\n return this;\n },\n toJSON: function(){\n var params = AV.InboxQuery.__super__.toJSON.call(this);\n params.owner = AV._encode(this._owner);\n params.inboxType = AV._encode(this._inboxType);\n params.sinceId = AV._encode(this._sinceId);\n params.maxId = AV._encode(this._maxId);\n return params;\n }\n });\n\n /**\n * Create a inbox status query to find someone's inbox statuses.\n * @since 0.3.0\n * @param {Object} owner The inbox's owner\n * @param {String} inboxType The inbox type,'default' by default.\n * @return {AV.InboxQuery} The inbox query object.\n * @see AV.InboxQuery\n * @example\n * //Find current user's default inbox statuses.\n * var query = AV.Status.inboxQuery(AV.User.current());\n * //find the statuses after the last message id\n * query.sinceId(lastMessageId);\n * query.find().then(function(statuses){\n * //process statuses\n * });\n */\n AV.Status.inboxQuery = function(owner, inboxType){\n var query = new AV.InboxQuery(AV.Status);\n if(owner){\n query._owner = owner;\n }\n if(inboxType){\n query._inboxType = inboxType;\n }\n return query;\n };\n\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/status.js","const _ = require('underscore');\nconst AVError = require('./error');\nconst AVRequest = require('./request').request;\nconst Promise = require('./promise');\n\nconst getWeappLoginCode = () => {\n if (typeof wx === 'undefined' || typeof wx.login !== 'function') {\n throw new Error('Weapp Login is only available in Weapp');\n }\n return new Promise((resolve, reject) => {\n wx.login({\n success: ({ code, errMsg }) => {\n if (code) {\n resolve(code);\n } else {\n reject(new Error(errMsg));\n }\n },\n });\n });\n};\n\nmodule.exports = function(AV) {\n /**\n * @class\n *\n *

An AV.User object is a local representation of a user persisted to the\n * LeanCloud server. This class is a subclass of an AV.Object, and retains the\n * same functionality of an AV.Object, but also extends it with various\n * user specific methods, like authentication, signing up, and validation of\n * uniqueness.

\n */\n AV.User = AV.Object.extend(\"_User\", /** @lends AV.User.prototype */ {\n // Instance Variables\n _isCurrentUser: false,\n\n\n // Instance Methods\n\n /**\n * Internal method to handle special fields in a _User response.\n * @private\n */\n _mergeMagicFields: function(attrs) {\n if (attrs.sessionToken) {\n this._sessionToken = attrs.sessionToken;\n delete attrs.sessionToken;\n }\n AV.User.__super__._mergeMagicFields.call(this, attrs);\n },\n\n /**\n * Removes null values from authData (which exist temporarily for\n * unlinking)\n * @private\n */\n _cleanupAuthData: function() {\n if (!this.isCurrent()) {\n return;\n }\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n AV._objectEach(this.get('authData'), function(value, key) {\n if (!authData[key]) {\n delete authData[key];\n }\n });\n },\n\n /**\n * Synchronizes authData for all providers.\n * @private\n */\n _synchronizeAllAuthData: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._synchronizeAuthData(key);\n });\n },\n\n /**\n * Synchronizes auth data for a provider (e.g. puts the access token in the\n * right place to be used by the Facebook SDK).\n * @private\n */\n _synchronizeAuthData: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[authType];\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData');\n if (!authData || !provider) {\n return;\n }\n var success = provider.restoreAuthentication(authData[authType]);\n if (!success) {\n this._unlinkFrom(provider);\n }\n },\n\n _handleSaveResult: function(makeCurrent) {\n // Clean up and synchronize the authData object, removing any unset values\n if (makeCurrent && !AV._config.disableCurrentUser) {\n this._isCurrentUser = true;\n }\n this._cleanupAuthData();\n this._synchronizeAllAuthData();\n // Don't keep the password around.\n delete this._serverData.password;\n this._rebuildEstimatedDataForKey(\"password\");\n this._refreshCache();\n if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) {\n // Some old version of leanengine-node-sdk will overwrite\n // AV.User._saveCurrentUser which returns no Promise.\n // So we need a Promise wrapper.\n return Promise.resolve(AV.User._saveCurrentUser(this));\n } else {\n return Promise.resolve();\n }\n },\n\n /**\n * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can\n * call linkWith on the user (even if it doesn't exist yet on the server).\n * @private\n */\n _linkWith: function(provider, data) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n provider = AV.User._authProviders[provider];\n } else {\n authType = provider.getAuthType();\n }\n if (data) {\n var authData = this.get('authData') || {};\n authData[authType] = data;\n return this.save({ authData })\n .then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n } else {\n return provider.authenticate().then(result => this._linkWith(provider, result));\n }\n },\n\n /**\n * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。\n * 仅在小程序中可用。\n *\n * @return {AV.User}\n */\n linkWithWeapp() {\n return getWeappLoginCode().then(code => this._linkWith('lc_weapp', { code }));\n },\n\n /**\n * Unlinks a user from a service.\n * @private\n */\n _unlinkFrom: function(provider) {\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n return this._linkWith(provider, null).then(model => {\n this._synchronizeAuthData(provider);\n return model;\n });\n },\n\n /**\n * Checks whether a user is linked to a service.\n * @private\n */\n _isLinked: function(provider) {\n var authType;\n if (_.isString(provider)) {\n authType = provider;\n } else {\n authType = provider.getAuthType();\n }\n var authData = this.get('authData') || {};\n return !!authData[authType];\n },\n\n logOut: function() {\n this._logOutWithAll();\n this._isCurrentUser = false;\n },\n\n /**\n * Deauthenticates all providers.\n * @private\n */\n _logOutWithAll: function() {\n var authData = this.get('authData');\n if (!authData) {\n return;\n }\n var self = this;\n AV._objectEach(this.get('authData'), function(value, key) {\n self._logOutWith(key);\n });\n },\n\n /**\n * Deauthenticates a single provider (e.g. removing access tokens from the\n * Facebook SDK).\n * @private\n */\n _logOutWith: function(provider) {\n if (!this.isCurrent()) {\n return;\n }\n if (_.isString(provider)) {\n provider = AV.User._authProviders[provider];\n }\n if (provider && provider.deauthenticate) {\n provider.deauthenticate();\n }\n },\n\n /**\n * Signs up a new user. You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUp\n */\n signUp: function(attrs, options) {\n var error;\n\n var username = (attrs && attrs.username) || this.get(\"username\");\n if (!username || (username === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty name.\");\n throw error;\n }\n\n var password = (attrs && attrs.password) || this.get(\"password\");\n if (!password || (password === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up user with an empty password.\");\n throw error;\n }\n\n return this.save(attrs, options).then(function(model) {\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Signs up a new user with mobile phone and sms code.\n * You should call this instead of save for\n * new AV.Users. This will create a new AV.User on the server, and\n * also persist the session on disk so that you can access the user using\n * current.\n *\n *

A username and password must be set before calling signUp.

\n *\n * @param {Object} attrs Extra fields to set on the new user, or null.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled when the signup\n * finishes.\n * @see AV.User.signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(attrs, options = {}) {\n var error;\n\n var mobilePhoneNumber = (attrs && attrs.mobilePhoneNumber) ||\n this.get(\"mobilePhoneNumber\");\n if (!mobilePhoneNumber || (mobilePhoneNumber === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty mobilePhoneNumber.\");\n throw error;\n }\n\n var smsCode = (attrs && attrs.smsCode) || this.get(\"smsCode\");\n if (!smsCode || (smsCode === \"\")) {\n error = new AVError(\n AVError.OTHER_CAUSE,\n \"Cannot sign up or login user by mobilePhoneNumber \" +\n \"with an empty smsCode.\");\n throw error;\n }\n\n options._makeRequest = function(route, className, id, method, json) {\n return AVRequest('usersByMobilePhone', null, null, \"POST\", json);\n };\n return this.save(attrs, options).then(function(model) {\n delete model.attributes.smsCode;\n delete model._serverData.smsCode;\n return model._handleSaveResult(true).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Logs in a AV.User. On success, this saves the session to localStorage,\n * so you can retrieve the currently logged in user using\n * current.\n *\n *

A username and password must be set before calling logIn.

\n *\n * @see AV.User.logIn\n * @return {Promise} A promise that is fulfilled with the user when\n * the login is complete.\n */\n logIn: function() {\n var model = this;\n var request = AVRequest('login', null, null, 'POST', this.toJSON());\n return request.then(function(resp) {\n var serverAttrs = model.parse(resp);\n model._finishFetch(serverAttrs);\n return model._handleSaveResult(true).then(function() {\n if(!serverAttrs.smsCode)\n delete model.attributes['smsCode'];\n return model;\n });\n });\n },\n /**\n * @see AV.Object#save\n */\n save: function(arg1, arg2, arg3) {\n var i, attrs, current, options, saved;\n if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) {\n attrs = arg1;\n options = arg2;\n } else {\n attrs = {};\n attrs[arg1] = arg2;\n options = arg3;\n }\n options = options || {};\n\n return AV.Object.prototype.save\n .call(this, attrs, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Follow a user\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to follow.\n * @param {AuthOptions} options\n */\n follow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'POST', null, options);\n return request;\n },\n\n /**\n * Unfollow a user.\n * @since 0.3.0\n * @param {AV.User | String} target The target user or user's objectId to unfollow.\n * @param {AuthOptions} options\n */\n unfollow: function(target, options){\n if(!this.id){\n throw new Error('Please signin.');\n }\n if(!target){\n throw new Error('Invalid target user.');\n }\n var userObjectId = _.isString(target) ? target: target.id;\n if(!userObjectId){\n throw new Error('Invalid target user.');\n }\n var route = 'users/' + this.id + '/friendship/' + userObjectId;\n var request = AVRequest(route, null, null, 'DELETE', null, options);\n return request;\n },\n\n /**\n *Create a follower query to query the user's followers.\n * @since 0.3.0\n * @see AV.User#followerQuery\n */\n followerQuery: function() {\n return AV.User.followerQuery(this.id);\n },\n\n /**\n *Create a followee query to query the user's followees.\n * @since 0.3.0\n * @see AV.User#followeeQuery\n */\n followeeQuery: function() {\n return AV.User.followeeQuery(this.id);\n },\n\n /**\n * @see AV.Object#fetch\n */\n fetch: function(fetchOptions, options) {\n return AV.Object.prototype.fetch.call(this, fetchOptions, options)\n .then(function(model) {\n return model._handleSaveResult(false).then(function() {\n return model;\n });\n });\n },\n\n /**\n * Update user's new password safely based on old password.\n * @param {String} oldPassword the old password.\n * @param {String} newPassword the new password.\n * @param {AuthOptions} options\n */\n updatePassword: function(oldPassword, newPassword, options) {\n var route = 'users/' + this.id + '/updatePassword';\n var params = {\n old_password: oldPassword,\n new_password: newPassword\n };\n var request = AVRequest(route, null, null, 'PUT', params, options);\n return request;\n },\n\n /**\n * Returns true if current would return this user.\n * @see AV.User#current\n */\n isCurrent: function() {\n return this._isCurrentUser;\n },\n\n /**\n * Returns get(\"username\").\n * @return {String}\n * @see AV.Object#get\n */\n getUsername: function() {\n return this.get(\"username\");\n },\n\n /**\n * Returns get(\"mobilePhoneNumber\").\n * @return {String}\n * @see AV.Object#get\n */\n getMobilePhoneNumber: function(){\n return this.get(\"mobilePhoneNumber\");\n },\n\n /**\n * Calls set(\"mobilePhoneNumber\", phoneNumber, options) and returns the result.\n * @param {String} mobilePhoneNumber\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setMobilePhoneNumber: function(phone, options) {\n return this.set(\"mobilePhoneNumber\", phone, options);\n },\n\n /**\n * Calls set(\"username\", username, options) and returns the result.\n * @param {String} username\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setUsername: function(username, options) {\n return this.set(\"username\", username, options);\n },\n\n /**\n * Calls set(\"password\", password, options) and returns the result.\n * @param {String} password\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setPassword: function(password, options) {\n return this.set(\"password\", password, options);\n },\n\n /**\n * Returns get(\"email\").\n * @return {String}\n * @see AV.Object#get\n */\n getEmail: function() {\n return this.get(\"email\");\n },\n\n /**\n * Calls set(\"email\", email, options) and returns the result.\n * @param {String} email\n * @param {AuthOptions} options\n * @return {Boolean}\n * @see AV.Object#set\n */\n setEmail: function(email, options) {\n return this.set(\"email\", email, options);\n },\n\n /**\n * Checks whether this user is the current user and has been authenticated.\n * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),\n * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id\n * @return (Boolean) whether this user is the current user and is logged in.\n */\n authenticated: function() {\n console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。')\n return !!this._sessionToken &&\n (!AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id);\n },\n\n /**\n * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。\n *\n * @since 2.0.0\n * @return Promise.\n */\n isAuthenticated() {\n return Promise.resolve().then(() =>\n !!this._sessionToken &&\n AV.User._fetchUserBySessionToken(this._sessionToken).then(\n () => true,\n (error) => {\n if (error.code === 211) {\n return false;\n }\n throw error;\n }\n )\n );\n },\n\n /**\n * Get sessionToken of current user.\n * @return {String} sessionToken\n */\n getSessionToken() {\n return this._sessionToken;\n },\n\n /**\n * Refresh sessionToken of current user.\n * @since 2.1.0\n * @param {AuthOptions} [options]\n * @return {Promise.} user with refreshed sessionToken\n */\n refreshSessionToken(options) {\n return AVRequest(`users/${this.id}/refreshSessionToken`, null, null, 'PUT', null, options)\n .then(response => {\n this._finishFetch(response);\n return this._handleSaveResult(true).then(() => this);\n });\n },\n\n /**\n * Get this user's Roles.\n * @param {AuthOptions} [options]\n * @return {Promise} A promise that is fulfilled with the roles when\n * the query is complete.\n */\n getRoles(options) {\n return AV.Relation.reverseQuery(\"_Role\", \"users\", this).find(options);\n },\n\n }, /** @lends AV.User */ {\n // Class Variables\n\n // The currently logged-in user.\n _currentUser: null,\n\n // Whether currentUser is known to match the serialized version on disk.\n // This is useful for saving a localstorage check if you try to load\n // _currentUser frequently while there is none stored.\n _currentUserMatchesDisk: false,\n\n // The localStorage key suffix that the current user is stored under.\n _CURRENT_USER_KEY: \"currentUser\",\n\n // The mapping of auth provider names to actual providers\n _authProviders: {},\n\n // Class Methods\n\n /**\n * Signs up a new user with a username (or email) and password.\n * This will create a new AV.User on the server, and also persist the\n * session in localStorage so that you can access the user using\n * {@link #current}.\n *\n * @param {String} username The username (or email) to sign up with.\n * @param {String} password The password to sign up with.\n * @param {Object} attrs Extra fields to set on the new user.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the signup completes.\n * @see AV.User#signUp\n */\n signUp: function(username, password, attrs, options) {\n attrs = attrs || {};\n attrs.username = username;\n attrs.password = password;\n var user = AV.Object._create(\"_User\");\n return user.signUp(attrs, options);\n },\n\n /**\n * Logs in a user with a username (or email) and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} username The username (or email) to log in with.\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logIn: function(username, password, options) {\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ username: username, password: password });\n return user.logIn(options);\n },\n\n /**\n * Logs in a user with a session token. On success, this saves the session\n * to disk, so you can retrieve the currently logged in user using\n * current.\n *\n * @param {String} sessionToken The sessionToken to log in with.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n */\n become: function(sessionToken) {\n return this._fetchUserBySessionToken(sessionToken).then(user =>\n user._handleSaveResult(true).then(() => user)\n );\n },\n\n _fetchUserBySessionToken: function(sessionToken) {\n var user = AV.Object._create(\"_User\");\n return AVRequest(\n \"users\",\n \"me\",\n null,\n \"GET\", {\n session_token: sessionToken\n }\n ).then(function(resp) {\n var serverAttrs = user.parse(resp);\n user._finishFetch(serverAttrs);\n return user;\n });\n },\n\n /**\n * Logs in a user with a mobile phone number and sms code sent by\n * AV.User.requestLoginSmsCode.On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhoneSmsCode: function(mobilePhone, smsCode, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a mobilePhoneNumber and smsCode.\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {String} mobilePhoneNumber The user's mobilePhoneNumber.\n * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode\n * @param {Object} attributes The user's other attributes such as username etc.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#signUpOrlogInWithMobilePhone\n * @see AV.Cloud.requestSmsCode\n */\n signUpOrlogInWithMobilePhone: function(mobilePhoneNumber, smsCode, attrs, options) {\n attrs = attrs || {};\n attrs.mobilePhoneNumber = mobilePhoneNumber;\n attrs.smsCode = smsCode;\n var user = AV.Object._create(\"_User\");\n return user.signUpOrlogInWithMobilePhone(attrs, options);\n },\n\n\n /**\n * Logs in a user with a mobile phone number and password. On success, this\n * saves the session to disk, so you can retrieve the currently logged in\n * user using current.\n *\n * @param {String} mobilePhone The user's mobilePhoneNumber\n * @param {String} password The password to log in with.\n * @param {AuthOptions} options\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @see AV.User#logIn\n */\n logInWithMobilePhone: function(mobilePhone, password, options){\n var user = AV.Object._create(\"_User\");\n user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password });\n return user.logIn(options);\n },\n\n /**\n * Sign up or logs in a user with a third party auth data(AccessToken).\n * On success, this saves the session to disk, so you can retrieve the currently\n * logged in user using current.\n *\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @param {string} platform Available platform for sign up.\n * @return {Promise} A promise that is fulfilled with the user when\n * the login completes.\n * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户}\n */\n signUpOrlogInWithAuthData(authData, platform) {\n return AV.User._logInWith(platform, authData);\n },\n\n /**\n * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。\n * 仅在小程序中可用。\n *\n * @since 2.0.0\n * @return {AV.User}\n */\n loginWithWeapp() {\n return getWeappLoginCode().then(code => this.signUpOrlogInWithAuthData({ code }, 'lc_weapp'));\n },\n\n /**\n * Associate a user with a third party auth data(AccessToken).\n *\n * @param {AV.User} userObj A user which you want to associate.\n * @param {string} platform Available platform for sign up.\n * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 }\n * @return {Promise} A promise that is fulfilled with the user when completed.\n * @example AV.User.associateWithAuthData(loginUser, 'weixin', {\n * openid: 'abc123',\n * access_token: '123abc',\n * expires_in: 1382686496\n * }).then(function(user) {\n * //Access user here\n * }).catch(function(error) {\n * //console.error(\"error: \", error);\n * });\n */\n associateWithAuthData(userObj, platform, authData) {\n return userObj._linkWith(platform, authData);\n },\n /**\n * Logs out the currently logged in user session. This will remove the\n * session from disk, log out of linked services, and future calls to\n * current will return null.\n * @return {Promise}\n */\n logOut: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser !== null) {\n AV.User._currentUser._logOutWithAll();\n AV.User._currentUser._isCurrentUser = false;\n }\n AV.User._currentUserMatchesDisk = true;\n AV.User._currentUser = null;\n return AV.localStorage.removeItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY));\n },\n\n /**\n *Create a follower query for special user to query the user's followers.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followerQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Follower');\n query._friendshipTag ='follower';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n *Create a followee query for special user to query the user's followees.\n * @param {String} userObjectId The user object id.\n * @return {AV.FriendShipQuery}\n * @since 0.3.0\n */\n followeeQuery: function(userObjectId) {\n if(!userObjectId || !_.isString(userObjectId)) {\n throw new Error('Invalid user object id.');\n }\n var query = new AV.FriendShipQuery('_Followee');\n query._friendshipTag ='followee';\n query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId));\n return query;\n },\n\n /**\n * Requests a password reset email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * reset their password on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * forgot their password.\n * @return {Promise}\n */\n requestPasswordReset: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestPasswordReset\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify email to be sent to the specified email address\n * associated with the user account. This email allows the user to securely\n * verify their email address on the AV site.\n *\n * @param {String} email The email address associated with the user that\n * doesn't verify their email address.\n * @return {Promise}\n */\n requestEmailVerify: function(email) {\n var json = { email: email };\n var request = AVRequest(\"requestEmailVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Requests a verify sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * verify their mobile phone number by calling AV.User.verifyMobilePhone\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestMobilePhoneVerify: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestMobilePhoneVerify\", null, null, \"POST\",\n json);\n return request;\n },\n\n\n /**\n * Requests a reset password sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * reset their account's password by calling AV.User.resetPasswordBySmsCode\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that doesn't verify their mobile phone number.\n * @return {Promise}\n */\n requestPasswordResetBySmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestPasswordResetBySmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Makes a call to reset user's account password by sms code and new password.\n * The sms code is sent by AV.User.requestPasswordResetBySmsCode.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @param {String} password The new password.\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n resetPasswordBySmsCode: function(code, password){\n var json = { password: password};\n var request = AVRequest(\"resetPasswordBySmsCode\", null, code, \"PUT\",\n json);\n return request;\n },\n\n /**\n * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode\n * If verify successfully,the user mobilePhoneVerified attribute will be true.\n * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode\n * @return {Promise} A promise that will be resolved with the result\n * of the function.\n */\n verifyMobilePhone: function(code){\n var request = AVRequest(\"verifyMobilePhone\", null, code, \"POST\",\n null);\n return request;\n },\n\n /**\n * Requests a logIn sms code to be sent to the specified mobile phone\n * number associated with the user account. This sms code allows the user to\n * login by AV.User.logInWithMobilePhoneSmsCode function.\n *\n * @param {String} mobilePhone The mobile phone number associated with the\n * user that want to login by AV.User.logInWithMobilePhoneSmsCode\n * @return {Promise}\n */\n requestLoginSmsCode: function(mobilePhone){\n var json = { mobilePhoneNumber: mobilePhone };\n var request = AVRequest(\"requestLoginSmsCode\", null, null, \"POST\",\n json);\n return request;\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {Promise.} resolved with the currently logged in AV.User.\n */\n currentAsync: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return Promise.resolve(null);\n }\n\n if (AV.User._currentUser) {\n return Promise.resolve(AV.User._currentUser);\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return Promise.resolve(AV.User._currentUser);\n }\n\n\n return AV.localStorage.getItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY)\n ).then(function(userData) {\n if (!userData) {\n return null;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n });\n },\n\n /**\n * Retrieves the currently logged in AVUser with a valid session,\n * either from memory or localStorage, if necessary.\n * @return {AV.User} The currently logged in AV.User.\n */\n current: function() {\n if (AV._config.disableCurrentUser) {\n console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html');\n return null;\n }\n\n if (AV.User._currentUser) {\n return AV.User._currentUser;\n }\n\n if (AV.User._currentUserMatchesDisk) {\n\n return AV.User._currentUser;\n }\n\n // Load the user from local storage.\n AV.User._currentUserMatchesDisk = true;\n\n var userData = AV.localStorage.getItem(AV._getAVPath(\n AV.User._CURRENT_USER_KEY));\n if (!userData) {\n\n return null;\n }\n AV.User._currentUser = AV.Object._create(\"_User\");\n AV.User._currentUser._isCurrentUser = true;\n\n var json = JSON.parse(userData);\n AV.User._currentUser.id = json._id;\n delete json._id;\n AV.User._currentUser._sessionToken = json._sessionToken;\n delete json._sessionToken;\n AV.User._currentUser._finishFetch(json);\n //AV.User._currentUser.set(json);\n\n AV.User._currentUser._synchronizeAllAuthData();\n AV.User._currentUser._refreshCache();\n AV.User._currentUser._opSetQueue = [{}];\n return AV.User._currentUser;\n },\n\n /**\n * Persists a user as currentUser to localStorage, and into the singleton.\n * @private\n */\n _saveCurrentUser: function(user) {\n var promise;\n if (AV.User._currentUser !== user) {\n promise = AV.User.logOut();\n }\n else {\n promise = Promise.resolve();\n }\n return promise.then(function() {\n user._isCurrentUser = true;\n AV.User._currentUser = user;\n\n var json = user.toJSON();\n json._id = user.id;\n json._sessionToken = user._sessionToken;\n return AV.localStorage.setItemAsync(\n AV._getAVPath(AV.User._CURRENT_USER_KEY),\n JSON.stringify(json)\n ).then(function() {\n AV.User._currentUserMatchesDisk = true;\n });\n });\n },\n\n _registerAuthenticationProvider: function(provider) {\n AV.User._authProviders[provider.getAuthType()] = provider;\n // Synchronize the current user with the auth provider.\n if (!AV._config.disableCurrentUser && AV.User.current()) {\n AV.User.current()._synchronizeAuthData(provider.getAuthType());\n }\n },\n\n _logInWith: function(provider, options) {\n var user = AV.Object._create(\"_User\");\n return user._linkWith(provider, options);\n }\n\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/user.js","/*!\n * LeanCloud JavaScript SDK\n * https://leancloud.cn\n *\n * Copyright 2016 LeanCloud.cn, Inc.\n * The LeanCloud JavaScript SDK is freely distributable under the MIT license.\n */\n\nconst AV = require('./av');\n\nAV._ = require('underscore');\nAV.version = require('./version');\nAV.Promise = require('./promise');\nAV.localStorage = require('./localstorage');\nAV.Cache = require('./cache');\nAV.Error = require('./error');\n\nrequire('./init');\nrequire('./event')(AV);\nrequire('./geopoint')(AV);\nrequire('./acl')(AV);\nrequire('./op')(AV);\nrequire('./relation')(AV);\nrequire('./file')(AV);\nrequire('./object')(AV);\nrequire('./role')(AV);\nrequire('./user')(AV);\nrequire('./query')(AV);\nrequire('./cloudfunction')(AV);\nrequire('./push')(AV);\nrequire('./status')(AV);\nrequire('./search')(AV);\nrequire('./insight')(AV);\n\nmodule.exports = AV;\n\n/**\n * Options to controll the authentication for an operation\n * @typedef {Object} AuthOptions\n * @property {String} [sessionToken] Specify a user to excute the operation as.\n * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided.\n * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set.\n */\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","module.exports = [];\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/comments-browser.js","const version = require('../version');\nconst comments = [process.env.CLIENT_PLATFORM || 'Node.js'].concat(require('./comments'));\n\nmodule.exports = `LeanCloud-JS-SDK/${version} (${comments.join('; ')})`;\n\n\n\n// WEBPACK FOOTER //\n// ./src/ua/index.js","const request = require('superagent');\nconst debug = require('debug')('cos');\nconst Promise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n const uploadUrl = uploadInfo.upload_url + \"?sign=\" + encodeURIComponent(uploadInfo.token);\n\n return new Promise((resolve, reject) => {\n const req = request('POST', uploadUrl)\n .field('fileContent', data)\n .field('op', 'upload');\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/cos.js","const request = require('superagent');\nconst Promise = require('../promise');\nconst debug = require('debug')('qiniu');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n // Get the uptoken to upload files to qiniu.\n const uptoken = uploadInfo.token;\n return new Promise((resolve, reject) => {\n const req = request('POST', 'https://up.qbox.me')\n .field('file', data)\n .field('name', file.attributes.name)\n .field('key', file._qiniu_key)\n .field('token', uptoken);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (res) {\n debug(res.status, res.body, res.text);\n }\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/qiniu-browser.js","const request = require('superagent');\nconst AVPromise = require('../promise');\n\nmodule.exports = function upload(uploadInfo, data, file, saveOptions = {}) {\n file.attributes.url = uploadInfo.url;\n file._bucket = uploadInfo.bucket;\n file.id = uploadInfo.objectId;\n return new Promise((resolve, reject) => {\n // 海外节点,针对 S3 才会返回 upload_url\n const req = request('PUT', uploadInfo.upload_url)\n .set('Content-Type', file.get('mime_type'))\n .send(data);\n if (saveOptions.onprogress) {\n req.on('progress', saveOptions.onprogress);\n }\n req.end((err, res) => {\n if (err) {\n if (res) {\n err.statusCode = res.status;\n err.responseText = res.text;\n err.response = res.body;\n }\n return reject(err);\n }\n resolve(file);\n });\n });\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/uploader/s3.js","var _ = require('underscore');\nvar Promise = require('../promise');\n\n// interface Storage {\n// readonly attribute boolean async;\n// string getItem(string key);\n// void setItem(string key, string value);\n// void removeItem(string key);\n// void clear();\n// Promise getItemAsync(string key);\n// Promise setItemAsync(string key, string value);\n// Promise removeItemAsync(string key);\n// Promise clearAsync();\n// }\nvar Storage = {};\nvar apiNames = [\n 'getItem',\n 'setItem',\n 'removeItem',\n 'clear'\n];\n\nvar localStorage = global.localStorage;\n\ntry {\n var testKey = '__storejs__';\n localStorage.setItem(testKey, testKey);\n if (localStorage.getItem(testKey) != testKey) {\n throw new Error();\n }\n localStorage.removeItem(testKey);\n} catch (e) {\n localStorage = require('localstorage-memory');\n}\n\n// in browser, `localStorage.async = false` will excute `localStorage.setItem('async', false)`\n_(apiNames).each(function(apiName) {\n Storage[apiName] = function() {\n return global.localStorage[apiName].apply(global.localStorage, arguments);\n };\n});\nStorage.async = false;\n\nmodule.exports = Storage;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/localstorage-browser.js","var dataURItoBlob = function(dataURI, type) {\n var byteString;\n\n // 传入的 base64,不是 dataURL\n if (dataURI.indexOf('base64') < 0) {\n byteString = atob(dataURI);\n } else if (dataURI.split(',')[0].indexOf('base64') >= 0) {\n type = type || dataURI.split(',')[0].split(':')[1].split(';')[0];\n byteString = atob(dataURI.split(',')[1]);\n } else {\n byteString = unescape(dataURI.split(',')[1]);\n }\n var ia = new Uint8Array(byteString.length);\n for (var i = 0; i < byteString.length; i ++) {\n ia[i] = byteString.charCodeAt(i);\n }\n return new Blob([ia], {type});\n};\n\nmodule.exports = dataURItoBlob;\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/parse-base64-browser.js","\r\n/**\r\n * Expose `Emitter`.\r\n */\r\n\r\nif (typeof module !== 'undefined') {\r\n module.exports = Emitter;\r\n}\r\n\r\n/**\r\n * Initialize a new `Emitter`.\r\n *\r\n * @api public\r\n */\r\n\r\nfunction Emitter(obj) {\r\n if (obj) return mixin(obj);\r\n};\r\n\r\n/**\r\n * Mixin the emitter properties.\r\n *\r\n * @param {Object} obj\r\n * @return {Object}\r\n * @api private\r\n */\r\n\r\nfunction mixin(obj) {\r\n for (var key in Emitter.prototype) {\r\n obj[key] = Emitter.prototype[key];\r\n }\r\n return obj;\r\n}\r\n\r\n/**\r\n * Listen on the given `event` with `fn`.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.on =\r\nEmitter.prototype.addEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r\n .push(fn);\r\n return this;\r\n};\r\n\r\n/**\r\n * Adds an `event` listener that will be invoked a single\r\n * time then automatically removed.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.once = function(event, fn){\r\n function on() {\r\n this.off(event, on);\r\n fn.apply(this, arguments);\r\n }\r\n\r\n on.fn = fn;\r\n this.on(event, on);\r\n return this;\r\n};\r\n\r\n/**\r\n * Remove the given callback for `event` or all\r\n * registered callbacks.\r\n *\r\n * @param {String} event\r\n * @param {Function} fn\r\n * @return {Emitter}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.off =\r\nEmitter.prototype.removeListener =\r\nEmitter.prototype.removeAllListeners =\r\nEmitter.prototype.removeEventListener = function(event, fn){\r\n this._callbacks = this._callbacks || {};\r\n\r\n // all\r\n if (0 == arguments.length) {\r\n this._callbacks = {};\r\n return this;\r\n }\r\n\r\n // specific event\r\n var callbacks = this._callbacks['$' + event];\r\n if (!callbacks) return this;\r\n\r\n // remove all handlers\r\n if (1 == arguments.length) {\r\n delete this._callbacks['$' + event];\r\n return this;\r\n }\r\n\r\n // remove specific handler\r\n var cb;\r\n for (var i = 0; i < callbacks.length; i++) {\r\n cb = callbacks[i];\r\n if (cb === fn || cb.fn === fn) {\r\n callbacks.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emit `event` with the given args.\r\n *\r\n * @param {String} event\r\n * @param {Mixed} ...\r\n * @return {Emitter}\r\n */\r\n\r\nEmitter.prototype.emit = function(event){\r\n this._callbacks = this._callbacks || {};\r\n var args = [].slice.call(arguments, 1)\r\n , callbacks = this._callbacks['$' + event];\r\n\r\n if (callbacks) {\r\n callbacks = callbacks.slice(0);\r\n for (var i = 0, len = callbacks.length; i < len; ++i) {\r\n callbacks[i].apply(this, args);\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Return array of callbacks for `event`.\r\n *\r\n * @param {String} event\r\n * @return {Array}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.listeners = function(event){\r\n this._callbacks = this._callbacks || {};\r\n return this._callbacks['$' + event] || [];\r\n};\r\n\r\n/**\r\n * Check if this emitter has `event` handlers.\r\n *\r\n * @param {String} event\r\n * @return {Boolean}\r\n * @api public\r\n */\r\n\r\nEmitter.prototype.hasListeners = function(event){\r\n return !! this.listeners(event).length;\r\n};\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/component-emitter/index.js\n// module id = 38\n// module chunks = 0","(function() {\n var base64map\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n\n crypt = {\n // Bit-wise rotation left\n rotl: function(n, b) {\n return (n << b) | (n >>> (32 - b));\n },\n\n // Bit-wise rotation right\n rotr: function(n, b) {\n return (n << (32 - b)) | (n >>> b);\n },\n\n // Swap big-endian to little-endian and vice versa\n endian: function(n) {\n // If number given, swap endian\n if (n.constructor == Number) {\n return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;\n }\n\n // Else, assume array and swap all items\n for (var i = 0; i < n.length; i++)\n n[i] = crypt.endian(n[i]);\n return n;\n },\n\n // Generate an array of any length of random bytes\n randomBytes: function(n) {\n for (var bytes = []; n > 0; n--)\n bytes.push(Math.floor(Math.random() * 256));\n return bytes;\n },\n\n // Convert a byte array to big-endian 32-bit words\n bytesToWords: function(bytes) {\n for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)\n words[b >>> 5] |= bytes[i] << (24 - b % 32);\n return words;\n },\n\n // Convert big-endian 32-bit words to a byte array\n wordsToBytes: function(words) {\n for (var bytes = [], b = 0; b < words.length * 32; b += 8)\n bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);\n return bytes;\n },\n\n // Convert a byte array to a hex string\n bytesToHex: function(bytes) {\n for (var hex = [], i = 0; i < bytes.length; i++) {\n hex.push((bytes[i] >>> 4).toString(16));\n hex.push((bytes[i] & 0xF).toString(16));\n }\n return hex.join('');\n },\n\n // Convert a hex string to a byte array\n hexToBytes: function(hex) {\n for (var bytes = [], c = 0; c < hex.length; c += 2)\n bytes.push(parseInt(hex.substr(c, 2), 16));\n return bytes;\n },\n\n // Convert a byte array to a base-64 string\n bytesToBase64: function(bytes) {\n for (var base64 = [], i = 0; i < bytes.length; i += 3) {\n var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n for (var j = 0; j < 4; j++)\n if (i * 8 + j * 6 <= bytes.length * 8)\n base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));\n else\n base64.push('=');\n }\n return base64.join('');\n },\n\n // Convert a base-64 string to a byte array\n base64ToBytes: function(base64) {\n // Remove non-base-64 characters\n base64 = base64.replace(/[^A-Z0-9+\\/]/ig, '');\n\n for (var bytes = [], i = 0, imod4 = 0; i < base64.length;\n imod4 = ++i % 4) {\n if (imod4 == 0) continue;\n bytes.push(((base64map.indexOf(base64.charAt(i - 1))\n & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))\n | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));\n }\n return bytes;\n }\n };\n\n module.exports = crypt;\n})();\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/crypt/crypt.js\n// module id = 39\n// module chunks = 0","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n *\n * Expose `debug()` as the module.\n */\n\nexports = module.exports = createDebug.debug = createDebug['default'] = createDebug;\nexports.coerce = coerce;\nexports.disable = disable;\nexports.enable = enable;\nexports.enabled = enabled;\nexports.humanize = require('ms');\n\n/**\n * The currently active debug mode names, and names to skip.\n */\n\nexports.names = [];\nexports.skips = [];\n\n/**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n\nexports.formatters = {};\n\n/**\n * Previous log timestamp.\n */\n\nvar prevTime;\n\n/**\n * Select a color.\n * @param {String} namespace\n * @return {Number}\n * @api private\n */\n\nfunction selectColor(namespace) {\n var hash = 0, i;\n\n for (i in namespace) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n\n return exports.colors[Math.abs(hash) % exports.colors.length];\n}\n\n/**\n * Create a debugger with the given `namespace`.\n *\n * @param {String} namespace\n * @return {Function}\n * @api public\n */\n\nfunction createDebug(namespace) {\n\n function debug() {\n // disabled?\n if (!debug.enabled) return;\n\n var self = debug;\n\n // set `diff` timestamp\n var curr = +new Date();\n var ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n\n // turn the `arguments` into a proper Array\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n\n args[0] = exports.coerce(args[0]);\n\n if ('string' !== typeof args[0]) {\n // anything else let's inspect with %O\n args.unshift('%O');\n }\n\n // apply any `formatters` transformations\n var index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {\n // if we encounter an escaped % then don't increase the array index\n if (match === '%%') return match;\n index++;\n var formatter = exports.formatters[format];\n if ('function' === typeof formatter) {\n var val = args[index];\n match = formatter.call(self, val);\n\n // now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n\n // apply env-specific formatting (colors, etc.)\n exports.formatArgs.call(self, args);\n\n var logFn = debug.log || exports.log || console.log.bind(console);\n logFn.apply(self, args);\n }\n\n debug.namespace = namespace;\n debug.enabled = exports.enabled(namespace);\n debug.useColors = exports.useColors();\n debug.color = selectColor(namespace);\n\n // env-specific initialization logic for debug instances\n if ('function' === typeof exports.init) {\n exports.init(debug);\n }\n\n return debug;\n}\n\n/**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {String} namespaces\n * @api public\n */\n\nfunction enable(namespaces) {\n exports.save(namespaces);\n\n exports.names = [];\n exports.skips = [];\n\n var split = (namespaces || '').split(/[\\s,]+/);\n var len = split.length;\n\n for (var i = 0; i < len; i++) {\n if (!split[i]) continue; // ignore empty strings\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n } else {\n exports.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n}\n\n/**\n * Disable debug output.\n *\n * @api public\n */\n\nfunction disable() {\n exports.enable('');\n}\n\n/**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {String} name\n * @return {Boolean}\n * @api public\n */\n\nfunction enabled(name) {\n var i, len;\n for (i = 0, len = exports.skips.length; i < len; i++) {\n if (exports.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = exports.names.length; i < len; i++) {\n if (exports.names[i].test(name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Coerce `val`.\n *\n * @param {Mixed} val\n * @return {Mixed}\n * @api private\n */\n\nfunction coerce(val) {\n if (val instanceof Error) return val.stack || val.message;\n return val;\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/debug/src/debug.js\n// module id = 40\n// module chunks = 0","/*!\n * @overview es6-promise - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE\n * @version 4.1.0\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.ES6Promise = factory());\n}(this, (function () { 'use strict';\n\nfunction objectOrFunction(x) {\n return typeof x === 'function' || typeof x === 'object' && x !== null;\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\nvar _isArray = undefined;\nif (!Array.isArray) {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n} else {\n _isArray = Array.isArray;\n}\n\nvar isArray = _isArray;\n\nvar len = 0;\nvar vertxNext = undefined;\nvar customSchedulerFn = undefined;\n\nvar asap = function asap(callback, arg) {\n queue[len] = callback;\n queue[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 2, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n if (customSchedulerFn) {\n customSchedulerFn(flush);\n } else {\n scheduleFlush();\n }\n }\n};\n\nfunction setScheduler(scheduleFn) {\n customSchedulerFn = scheduleFn;\n}\n\nfunction setAsap(asapFn) {\n asap = asapFn;\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // see https://github.com/cujojs/when/issues/410 for details\n return function () {\n return process.nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n if (typeof vertxNext !== 'undefined') {\n return function () {\n vertxNext(flush);\n };\n }\n\n return useSetTimeout();\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n // Store setTimeout reference so es6-promise will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var globalSetTimeout = setTimeout;\n return function () {\n return globalSetTimeout(flush, 1);\n };\n}\n\nvar queue = new Array(1000);\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue[i];\n var arg = queue[i + 1];\n\n callback(arg);\n\n queue[i] = undefined;\n queue[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertx() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush = undefined;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush = attemptVertx();\n} else {\n scheduleFlush = useSetTimeout();\n}\n\nfunction then(onFulfillment, onRejection) {\n var _arguments = arguments;\n\n var parent = this;\n\n var child = new this.constructor(noop);\n\n if (child[PROMISE_ID] === undefined) {\n makePromise(child);\n }\n\n var _state = parent._state;\n\n if (_state) {\n (function () {\n var callback = _arguments[_state - 1];\n asap(function () {\n return invokeCallback(_state, child, callback, parent._result);\n });\n })();\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\n/**\n `Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {Any} value value that the returned promise will be resolved with\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve(object) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop);\n _resolve(promise, object);\n return promise;\n}\n\nvar PROMISE_ID = Math.random().toString(36).substring(16);\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nfunction selfFulfillment() {\n return new TypeError(\"You cannot resolve a promise with itself\");\n}\n\nfunction cannotReturnOwn() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then) {\n asap(function (promise) {\n var sealed = false;\n var error = tryThen(then, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n _resolve(promise, value);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n _reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n _reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n _reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n return _resolve(promise, value);\n }, function (reason) {\n return _reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$) {\n if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$ === GET_THEN_ERROR) {\n _reject(promise, GET_THEN_ERROR.error);\n GET_THEN_ERROR.error = null;\n } else if (then$$ === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$)) {\n handleForeignThenable(promise, maybeThenable, then$$);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction _resolve(promise, value) {\n if (promise === value) {\n _reject(promise, selfFulfillment());\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onerror) {\n promise._onerror(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length !== 0) {\n asap(publish, promise);\n }\n}\n\nfunction _reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n\n asap(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var _subscribers = parent._subscribers;\n var length = _subscribers.length;\n\n parent._onerror = null;\n\n _subscribers[length] = child;\n _subscribers[length + FULFILLED] = onFulfillment;\n _subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n asap(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = undefined,\n callback = undefined,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = undefined,\n error = undefined,\n succeeded = undefined,\n failed = undefined;\n\n if (hasCallback) {\n value = tryCatch(callback, detail);\n\n if (value === TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value.error = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n _reject(promise, cannotReturnOwn());\n return;\n }\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n _resolve(promise, value);\n } else if (failed) {\n _reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n _reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n try {\n resolver(function resolvePromise(value) {\n _resolve(promise, value);\n }, function rejectPromise(reason) {\n _reject(promise, reason);\n });\n } catch (e) {\n _reject(promise, e);\n }\n}\n\nvar id = 0;\nfunction nextId() {\n return id++;\n}\n\nfunction makePromise(promise) {\n promise[PROMISE_ID] = id++;\n promise._state = undefined;\n promise._result = undefined;\n promise._subscribers = [];\n}\n\nfunction Enumerator(Constructor, input) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop);\n\n if (!this.promise[PROMISE_ID]) {\n makePromise(this.promise);\n }\n\n if (isArray(input)) {\n this._input = input;\n this.length = input.length;\n this._remaining = input.length;\n\n this._result = new Array(this.length);\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate();\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n _reject(this.promise, validationError());\n }\n}\n\nfunction validationError() {\n return new Error('Array Methods must be provided an Array');\n};\n\nEnumerator.prototype._enumerate = function () {\n var length = this.length;\n var _input = this._input;\n\n for (var i = 0; this._state === PENDING && i < length; i++) {\n this._eachEntry(_input[i], i);\n }\n};\n\nEnumerator.prototype._eachEntry = function (entry, i) {\n var c = this._instanceConstructor;\n var resolve$$ = c.resolve;\n\n if (resolve$$ === resolve) {\n var _then = getThen(entry);\n\n if (_then === then && entry._state !== PENDING) {\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof _then !== 'function') {\n this._remaining--;\n this._result[i] = entry;\n } else if (c === Promise) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, _then);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve$$) {\n return resolve$$(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve$$(entry), i);\n }\n};\n\nEnumerator.prototype._settledAt = function (state, i, value) {\n var promise = this.promise;\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (state === REJECTED) {\n _reject(promise, value);\n } else {\n this._result[i] = value;\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n};\n\nEnumerator.prototype._willSettleAt = function (promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n};\n\n/**\n `Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = resolve(2);\n let promise3 = resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = resolve(1);\n let promise2 = reject(new Error(\"2\"));\n let promise3 = reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries) {\n return new Enumerator(this, entries).promise;\n}\n\n/**\n `Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} promises array of promises to observe\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (!isArray(entries)) {\n return new Constructor(function (_, reject) {\n return reject(new TypeError('You must pass an array to race.'));\n });\n } else {\n return new Constructor(function (resolve, reject) {\n var length = entries.length;\n for (var i = 0; i < length; i++) {\n Constructor.resolve(entries[i]).then(resolve, reject);\n }\n });\n }\n}\n\n/**\n `Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {Any} reason value that the returned promise will be rejected with.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject(reason) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop);\n _reject(promise, reason);\n return promise;\n}\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise's eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class Promise\n @param {function} resolver\n Useful for tooling.\n @constructor\n*/\nfunction Promise(resolver) {\n this[PROMISE_ID] = nextId();\n this._result = this._state = undefined;\n this._subscribers = [];\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n}\n\nPromise.all = all;\nPromise.race = race;\nPromise.resolve = resolve;\nPromise.reject = reject;\nPromise._setScheduler = setScheduler;\nPromise._setAsap = setAsap;\nPromise._asap = asap;\n\nPromise.prototype = {\n constructor: Promise,\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n \n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n \n Chaining\n --------\n \n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n \n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n \n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we're unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n \n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n \n Assimilation\n ------------\n \n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n \n If the assimliated promise rejects, then the downstream promise will also reject.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n \n Simple Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let result;\n \n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n \n Advanced Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let author, books;\n \n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n \n function foundBooks(books) {\n \n }\n \n function failure(reason) {\n \n }\n \n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n \n @method then\n @param {Function} onFulfilled\n @param {Function} onRejected\n Useful for tooling.\n @return {Promise}\n */\n then: then,\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn't find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function _catch(onRejection) {\n return this.then(null, onRejection);\n }\n};\n\nfunction polyfill() {\n var local = undefined;\n\n if (typeof global !== 'undefined') {\n local = global;\n } else if (typeof self !== 'undefined') {\n local = self;\n } else {\n try {\n local = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n }\n\n var P = local.Promise;\n\n if (P) {\n var promiseToString = null;\n try {\n promiseToString = Object.prototype.toString.call(P.resolve());\n } catch (e) {\n // silently ignored\n }\n\n if (promiseToString === '[object Promise]' && !P.cast) {\n return;\n }\n }\n\n local.Promise = Promise;\n}\n\n// Strange compat..\nPromise.polyfill = polyfill;\nPromise.Promise = Promise;\n\nreturn Promise;\n\n})));\n//# sourceMappingURL=es6-promise.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/es6-promise/dist/es6-promise.js\n// module id = 41\n// module chunks = 0","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nmodule.exports = function (obj) {\n return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)\n}\n\nfunction isBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/is-buffer/index.js\n// module id = 42\n// module chunks = 0","(function(root) {\n var localStorageMemory = {};\n var cache = {};\n\n /**\n * number of stored items.\n */\n localStorageMemory.length = 0;\n\n /**\n * returns item for passed key, or null\n *\n * @para {String} key\n * name of item to be returned\n * @returns {String|null}\n */\n localStorageMemory.getItem = function(key) {\n return cache[key] || null;\n };\n\n /**\n * sets item for key to passed value, as String\n *\n * @para {String} key\n * name of item to be set\n * @para {String} value\n * value, will always be turned into a String\n * @returns {undefined}\n */\n localStorageMemory.setItem = function(key, value) {\n if (typeof value === 'undefined') {\n localStorageMemory.removeItem(key);\n } else {\n if (!(cache.hasOwnProperty(key))) {\n localStorageMemory.length++;\n }\n\n cache[key] = '' + value;\n }\n };\n\n /**\n * removes item for passed key\n *\n * @para {String} key\n * name of item to be removed\n * @returns {undefined}\n */\n localStorageMemory.removeItem = function(key) {\n if (cache.hasOwnProperty(key)) {\n delete cache[key];\n localStorageMemory.length--;\n }\n };\n\n /**\n * returns name of key at passed index\n *\n * @para {Number} index\n * Position for key to be returned (starts at 0)\n * @returns {String|null}\n */\n localStorageMemory.key = function(index) {\n return Object.keys(cache)[index] || null;\n };\n\n /**\n * removes all stored items and sets length to 0\n *\n * @returns {undefined}\n */\n localStorageMemory.clear = function() {\n cache = {};\n localStorageMemory.length = 0;\n };\n\n if (typeof exports === 'object') {\n module.exports = localStorageMemory;\n } else {\n root.localStorageMemory = localStorageMemory;\n }\n})(this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/localstorage-memory/lib/localstorage-memory.js\n// module id = 43\n// module chunks = 0","(function(){\r\n var crypt = require('crypt'),\r\n utf8 = require('charenc').utf8,\r\n isBuffer = require('is-buffer'),\r\n bin = require('charenc').bin,\r\n\r\n // The core\r\n md5 = function (message, options) {\r\n // Convert to byte array\r\n if (message.constructor == String)\r\n if (options && options.encoding === 'binary')\r\n message = bin.stringToBytes(message);\r\n else\r\n message = utf8.stringToBytes(message);\r\n else if (isBuffer(message))\r\n message = Array.prototype.slice.call(message, 0);\r\n else if (!Array.isArray(message))\r\n message = message.toString();\r\n // else, assume byte array already\r\n\r\n var m = crypt.bytesToWords(message),\r\n l = message.length * 8,\r\n a = 1732584193,\r\n b = -271733879,\r\n c = -1732584194,\r\n d = 271733878;\r\n\r\n // Swap endian\r\n for (var i = 0; i < m.length; i++) {\r\n m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |\r\n ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;\r\n }\r\n\r\n // Padding\r\n m[l >>> 5] |= 0x80 << (l % 32);\r\n m[(((l + 64) >>> 9) << 4) + 14] = l;\r\n\r\n // Method shortcuts\r\n var FF = md5._ff,\r\n GG = md5._gg,\r\n HH = md5._hh,\r\n II = md5._ii;\r\n\r\n for (var i = 0; i < m.length; i += 16) {\r\n\r\n var aa = a,\r\n bb = b,\r\n cc = c,\r\n dd = d;\r\n\r\n a = FF(a, b, c, d, m[i+ 0], 7, -680876936);\r\n d = FF(d, a, b, c, m[i+ 1], 12, -389564586);\r\n c = FF(c, d, a, b, m[i+ 2], 17, 606105819);\r\n b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);\r\n a = FF(a, b, c, d, m[i+ 4], 7, -176418897);\r\n d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);\r\n c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);\r\n b = FF(b, c, d, a, m[i+ 7], 22, -45705983);\r\n a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);\r\n d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);\r\n c = FF(c, d, a, b, m[i+10], 17, -42063);\r\n b = FF(b, c, d, a, m[i+11], 22, -1990404162);\r\n a = FF(a, b, c, d, m[i+12], 7, 1804603682);\r\n d = FF(d, a, b, c, m[i+13], 12, -40341101);\r\n c = FF(c, d, a, b, m[i+14], 17, -1502002290);\r\n b = FF(b, c, d, a, m[i+15], 22, 1236535329);\r\n\r\n a = GG(a, b, c, d, m[i+ 1], 5, -165796510);\r\n d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);\r\n c = GG(c, d, a, b, m[i+11], 14, 643717713);\r\n b = GG(b, c, d, a, m[i+ 0], 20, -373897302);\r\n a = GG(a, b, c, d, m[i+ 5], 5, -701558691);\r\n d = GG(d, a, b, c, m[i+10], 9, 38016083);\r\n c = GG(c, d, a, b, m[i+15], 14, -660478335);\r\n b = GG(b, c, d, a, m[i+ 4], 20, -405537848);\r\n a = GG(a, b, c, d, m[i+ 9], 5, 568446438);\r\n d = GG(d, a, b, c, m[i+14], 9, -1019803690);\r\n c = GG(c, d, a, b, m[i+ 3], 14, -187363961);\r\n b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);\r\n a = GG(a, b, c, d, m[i+13], 5, -1444681467);\r\n d = GG(d, a, b, c, m[i+ 2], 9, -51403784);\r\n c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);\r\n b = GG(b, c, d, a, m[i+12], 20, -1926607734);\r\n\r\n a = HH(a, b, c, d, m[i+ 5], 4, -378558);\r\n d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);\r\n c = HH(c, d, a, b, m[i+11], 16, 1839030562);\r\n b = HH(b, c, d, a, m[i+14], 23, -35309556);\r\n a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);\r\n d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);\r\n c = HH(c, d, a, b, m[i+ 7], 16, -155497632);\r\n b = HH(b, c, d, a, m[i+10], 23, -1094730640);\r\n a = HH(a, b, c, d, m[i+13], 4, 681279174);\r\n d = HH(d, a, b, c, m[i+ 0], 11, -358537222);\r\n c = HH(c, d, a, b, m[i+ 3], 16, -722521979);\r\n b = HH(b, c, d, a, m[i+ 6], 23, 76029189);\r\n a = HH(a, b, c, d, m[i+ 9], 4, -640364487);\r\n d = HH(d, a, b, c, m[i+12], 11, -421815835);\r\n c = HH(c, d, a, b, m[i+15], 16, 530742520);\r\n b = HH(b, c, d, a, m[i+ 2], 23, -995338651);\r\n\r\n a = II(a, b, c, d, m[i+ 0], 6, -198630844);\r\n d = II(d, a, b, c, m[i+ 7], 10, 1126891415);\r\n c = II(c, d, a, b, m[i+14], 15, -1416354905);\r\n b = II(b, c, d, a, m[i+ 5], 21, -57434055);\r\n a = II(a, b, c, d, m[i+12], 6, 1700485571);\r\n d = II(d, a, b, c, m[i+ 3], 10, -1894986606);\r\n c = II(c, d, a, b, m[i+10], 15, -1051523);\r\n b = II(b, c, d, a, m[i+ 1], 21, -2054922799);\r\n a = II(a, b, c, d, m[i+ 8], 6, 1873313359);\r\n d = II(d, a, b, c, m[i+15], 10, -30611744);\r\n c = II(c, d, a, b, m[i+ 6], 15, -1560198380);\r\n b = II(b, c, d, a, m[i+13], 21, 1309151649);\r\n a = II(a, b, c, d, m[i+ 4], 6, -145523070);\r\n d = II(d, a, b, c, m[i+11], 10, -1120210379);\r\n c = II(c, d, a, b, m[i+ 2], 15, 718787259);\r\n b = II(b, c, d, a, m[i+ 9], 21, -343485551);\r\n\r\n a = (a + aa) >>> 0;\r\n b = (b + bb) >>> 0;\r\n c = (c + cc) >>> 0;\r\n d = (d + dd) >>> 0;\r\n }\r\n\r\n return crypt.endian([a, b, c, d]);\r\n };\r\n\r\n // Auxiliary functions\r\n md5._ff = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & c | ~b & d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._gg = function (a, b, c, d, x, s, t) {\r\n var n = a + (b & d | c & ~d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._hh = function (a, b, c, d, x, s, t) {\r\n var n = a + (b ^ c ^ d) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n md5._ii = function (a, b, c, d, x, s, t) {\r\n var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;\r\n return ((n << s) | (n >>> (32 - s))) + b;\r\n };\r\n\r\n // Package private blocksize\r\n md5._blocksize = 16;\r\n md5._digestsize = 16;\r\n\r\n module.exports = function (message, options) {\r\n if (message === undefined || message === null)\r\n throw new Error('Illegal argument ' + message);\r\n\r\n var digestbytes = crypt.wordsToBytes(md5(message, options));\r\n return options && options.asBytes ? digestbytes :\r\n options && options.asString ? bin.bytesToString(digestbytes) :\r\n crypt.bytesToHex(digestbytes);\r\n };\r\n\r\n})();\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/md5/md5.js\n// module id = 44\n// module chunks = 0","/**\n * Helpers.\n */\n\nvar s = 1000\nvar m = s * 60\nvar h = m * 60\nvar d = h * 24\nvar y = d * 365.25\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} options\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {}\n var type = typeof val\n if (type === 'string' && val.length > 0) {\n return parse(val)\n } else if (type === 'number' && isNaN(val) === false) {\n return options.long ?\n\t\t\tfmtLong(val) :\n\t\t\tfmtShort(val)\n }\n throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))\n}\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str)\n if (str.length > 10000) {\n return\n }\n var match = /^((?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)\n if (!match) {\n return\n }\n var n = parseFloat(match[1])\n var type = (match[2] || 'ms').toLowerCase()\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y\n case 'days':\n case 'day':\n case 'd':\n return n * d\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n\n default:\n return undefined\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n if (ms >= d) {\n return Math.round(ms / d) + 'd'\n }\n if (ms >= h) {\n return Math.round(ms / h) + 'h'\n }\n if (ms >= m) {\n return Math.round(ms / m) + 'm'\n }\n if (ms >= s) {\n return Math.round(ms / s) + 's'\n }\n return ms + 'ms'\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n return plural(ms, d, 'day') ||\n plural(ms, h, 'hour') ||\n plural(ms, m, 'minute') ||\n plural(ms, s, 'second') ||\n ms + ' ms'\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, n, name) {\n if (ms < n) {\n return\n }\n if (ms < n * 1.5) {\n return Math.floor(ms / n) + ' ' + name\n }\n return Math.ceil(ms / n) + ' ' + name + 's'\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/ms/index.js\n// module id = 45\n// module chunks = 0","/**\n * Check if `fn` is a function.\n *\n * @param {Function} fn\n * @return {Boolean}\n * @api private\n */\nvar isObject = require('./is-object');\n\nfunction isFunction(fn) {\n var tag = isObject(fn) ? Object.prototype.toString.call(fn) : '';\n return tag === '[object Function]';\n}\n\nmodule.exports = isFunction;\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/is-function.js\n// module id = 46\n// module chunks = 0","/**\n * Module of mixed-in functions shared between node and client code\n */\nvar isObject = require('./is-object');\n\n/**\n * Expose `RequestBase`.\n */\n\nmodule.exports = RequestBase;\n\n/**\n * Initialize a new `RequestBase`.\n *\n * @api public\n */\n\nfunction RequestBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in RequestBase.prototype) {\n obj[key] = RequestBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Clear previous timeout.\n *\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.clearTimeout = function _clearTimeout(){\n clearTimeout(this._timer);\n clearTimeout(this._responseTimeoutTimer);\n delete this._timer;\n delete this._responseTimeoutTimer;\n return this;\n};\n\n/**\n * Override default response body parser\n *\n * This function will be called to convert incoming data into request.body\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.parse = function parse(fn){\n this._parser = fn;\n return this;\n};\n\n/**\n * Set format of binary response body.\n * In browser valid formats are 'blob' and 'arraybuffer',\n * which return Blob and ArrayBuffer, respectively.\n *\n * In Node all values result in Buffer.\n *\n * Examples:\n *\n * req.get('/')\n * .responseType('blob')\n * .end(callback);\n *\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.responseType = function(val){\n this._responseType = val;\n return this;\n};\n\n/**\n * Override default request body serializer\n *\n * This function will be called to convert data set via .send or .attach into payload to send\n *\n * @param {Function}\n * @api public\n */\n\nRequestBase.prototype.serialize = function serialize(fn){\n this._serializer = fn;\n return this;\n};\n\n/**\n * Set timeouts.\n *\n * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.\n * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.\n *\n * Value of 0 or false means no timeout.\n *\n * @param {Number|Object} ms or {response, read, deadline}\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.timeout = function timeout(options){\n if (!options || 'object' !== typeof options) {\n this._timeout = options;\n this._responseTimeout = 0;\n return this;\n }\n\n for(var option in options) {\n switch(option) {\n case 'deadline':\n this._timeout = options.deadline;\n break;\n case 'response':\n this._responseTimeout = options.response;\n break;\n default:\n console.warn(\"Unknown timeout option\", option);\n }\n }\n return this;\n};\n\n/**\n * Set number of retry attempts on error.\n *\n * Failed requests will be retried 'count' times if timeout or err.code >= 500.\n *\n * @param {Number} count\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.retry = function retry(count){\n // Default to 1 if no count passed or true\n if (arguments.length === 0 || count === true) count = 1;\n if (count <= 0) count = 0;\n this._maxRetries = count;\n this._retries = 0;\n return this;\n};\n\n/**\n * Retry request\n *\n * @return {Request} for chaining\n * @api private\n */\n\nRequestBase.prototype._retry = function() {\n this.clearTimeout();\n\n // node\n if (this.req) {\n this.req = null;\n this.req = this.request();\n }\n\n this._aborted = false;\n this.timedout = false;\n\n return this._end();\n};\n\n/**\n * Promise support\n *\n * @param {Function} resolve\n * @param {Function} [reject]\n * @return {Request}\n */\n\nRequestBase.prototype.then = function then(resolve, reject) {\n if (!this._fullfilledPromise) {\n var self = this;\n if (this._endCalled) {\n console.warn(\"Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises\");\n }\n this._fullfilledPromise = new Promise(function(innerResolve, innerReject){\n self.end(function(err, res){\n if (err) innerReject(err); else innerResolve(res);\n });\n });\n }\n return this._fullfilledPromise.then(resolve, reject);\n}\n\nRequestBase.prototype.catch = function(cb) {\n return this.then(undefined, cb);\n};\n\n/**\n * Allow for extension\n */\n\nRequestBase.prototype.use = function use(fn) {\n fn(this);\n return this;\n}\n\nRequestBase.prototype.ok = function(cb) {\n if ('function' !== typeof cb) throw Error(\"Callback required\");\n this._okCallback = cb;\n return this;\n};\n\nRequestBase.prototype._isResponseOK = function(res) {\n if (!res) {\n return false;\n }\n\n if (this._okCallback) {\n return this._okCallback(res);\n }\n\n return res.status >= 200 && res.status < 300;\n};\n\n\n/**\n * Get request header `field`.\n * Case-insensitive.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nRequestBase.prototype.get = function(field){\n return this._header[field.toLowerCase()];\n};\n\n/**\n * Get case-insensitive header `field` value.\n * This is a deprecated internal API. Use `.get(field)` instead.\n *\n * (getHeader is no longer used internally by the superagent code base)\n *\n * @param {String} field\n * @return {String}\n * @api private\n * @deprecated\n */\n\nRequestBase.prototype.getHeader = RequestBase.prototype.get;\n\n/**\n * Set header `field` to `val`, or multiple fields with one object.\n * Case-insensitive.\n *\n * Examples:\n *\n * req.get('/')\n * .set('Accept', 'application/json')\n * .set('X-API-Key', 'foobar')\n * .end(callback);\n *\n * req.get('/')\n * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })\n * .end(callback);\n *\n * @param {String|Object} field\n * @param {String} val\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.set = function(field, val){\n if (isObject(field)) {\n for (var key in field) {\n this.set(key, field[key]);\n }\n return this;\n }\n this._header[field.toLowerCase()] = val;\n this.header[field] = val;\n return this;\n};\n\n/**\n * Remove header `field`.\n * Case-insensitive.\n *\n * Example:\n *\n * req.get('/')\n * .unset('User-Agent')\n * .end(callback);\n *\n * @param {String} field\n */\nRequestBase.prototype.unset = function(field){\n delete this._header[field.toLowerCase()];\n delete this.header[field];\n return this;\n};\n\n/**\n * Write the field `name` and `val`, or multiple fields with one object\n * for \"multipart/form-data\" request bodies.\n *\n * ``` js\n * request.post('/upload')\n * .field('foo', 'bar')\n * .end(callback);\n *\n * request.post('/upload')\n * .field({ foo: 'bar', baz: 'qux' })\n * .end(callback);\n * ```\n *\n * @param {String|Object} name\n * @param {String|Blob|File|Buffer|fs.ReadStream} val\n * @return {Request} for chaining\n * @api public\n */\nRequestBase.prototype.field = function(name, val) {\n\n // name should be either a string or an object.\n if (null === name || undefined === name) {\n throw new Error('.field(name, val) name can not be empty');\n }\n\n if (this._data) {\n console.error(\".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObject(name)) {\n for (var key in name) {\n this.field(key, name[key]);\n }\n return this;\n }\n\n if (Array.isArray(val)) {\n for (var i in val) {\n this.field(name, val[i]);\n }\n return this;\n }\n\n // val should be defined now\n if (null === val || undefined === val) {\n throw new Error('.field(name, val) val can not be empty');\n }\n if ('boolean' === typeof val) {\n val = '' + val;\n }\n this._getFormData().append(name, val);\n return this;\n};\n\n/**\n * Abort the request, and clear potential timeout.\n *\n * @return {Request}\n * @api public\n */\nRequestBase.prototype.abort = function(){\n if (this._aborted) {\n return this;\n }\n this._aborted = true;\n this.xhr && this.xhr.abort(); // browser\n this.req && this.req.abort(); // node\n this.clearTimeout();\n this.emit('abort');\n return this;\n};\n\n/**\n * Enable transmission of cookies with x-domain requests.\n *\n * Note that for this to work the origin must not be\n * using \"Access-Control-Allow-Origin\" with a wildcard,\n * and also must set \"Access-Control-Allow-Credentials\"\n * to \"true\".\n *\n * @api public\n */\n\nRequestBase.prototype.withCredentials = function(on){\n // This is browser-only functionality. Node side is no-op.\n if(on==undefined) on = true;\n this._withCredentials = on;\n return this;\n};\n\n/**\n * Set the max redirects to `n`. Does noting in browser XHR implementation.\n *\n * @param {Number} n\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.redirects = function(n){\n this._maxRedirects = n;\n return this;\n};\n\n/**\n * Convert to a plain javascript object (not JSON string) of scalar properties.\n * Note as this method is designed to return a useful non-this value,\n * it cannot be chained.\n *\n * @return {Object} describing method, url, and data of this request\n * @api public\n */\n\nRequestBase.prototype.toJSON = function(){\n return {\n method: this.method,\n url: this.url,\n data: this._data,\n headers: this._header\n };\n};\n\n\n/**\n * Send `data` as the request body, defaulting the `.type()` to \"json\" when\n * an object is given.\n *\n * Examples:\n *\n * // manual json\n * request.post('/user')\n * .type('json')\n * .send('{\"name\":\"tj\"}')\n * .end(callback)\n *\n * // auto json\n * request.post('/user')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // manual x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send('name=tj')\n * .end(callback)\n *\n * // auto x-www-form-urlencoded\n * request.post('/user')\n * .type('form')\n * .send({ name: 'tj' })\n * .end(callback)\n *\n * // defaults to x-www-form-urlencoded\n * request.post('/user')\n * .send('name=tobi')\n * .send('species=ferret')\n * .end(callback)\n *\n * @param {String|Object} data\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.send = function(data){\n var isObj = isObject(data);\n var type = this._header['content-type'];\n\n if (this._formData) {\n console.error(\".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()\");\n }\n\n if (isObj && !this._data) {\n if (Array.isArray(data)) {\n this._data = [];\n } else if (!this._isHost(data)) {\n this._data = {};\n }\n } else if (data && this._data && this._isHost(this._data)) {\n throw Error(\"Can't merge these send calls\");\n }\n\n // merge\n if (isObj && isObject(this._data)) {\n for (var key in data) {\n this._data[key] = data[key];\n }\n } else if ('string' == typeof data) {\n // default to x-www-form-urlencoded\n if (!type) this.type('form');\n type = this._header['content-type'];\n if ('application/x-www-form-urlencoded' == type) {\n this._data = this._data\n ? this._data + '&' + data\n : data;\n } else {\n this._data = (this._data || '') + data;\n }\n } else {\n this._data = data;\n }\n\n if (!isObj || this._isHost(data)) {\n return this;\n }\n\n // default to json\n if (!type) this.type('json');\n return this;\n};\n\n\n/**\n * Sort `querystring` by the sort function\n *\n *\n * Examples:\n *\n * // default order\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery()\n * .end(callback)\n *\n * // customized sort function\n * request.get('/user')\n * .query('name=Nick')\n * .query('search=Manny')\n * .sortQuery(function(a, b){\n * return a.length - b.length;\n * })\n * .end(callback)\n *\n *\n * @param {Function} sort\n * @return {Request} for chaining\n * @api public\n */\n\nRequestBase.prototype.sortQuery = function(sort) {\n // _sort default to true but otherwise can be a function or boolean\n this._sort = typeof sort === 'undefined' ? true : sort;\n return this;\n};\n\n/**\n * Invoke callback with timeout error.\n *\n * @api private\n */\n\nRequestBase.prototype._timeoutError = function(reason, timeout, errno){\n if (this._aborted) {\n return;\n }\n var err = new Error(reason + timeout + 'ms exceeded');\n err.timeout = timeout;\n err.code = 'ECONNABORTED';\n err.errno = errno;\n this.timedout = true;\n this.abort();\n this.callback(err);\n};\n\nRequestBase.prototype._setTimeouts = function() {\n var self = this;\n\n // deadline\n if (this._timeout && !this._timer) {\n this._timer = setTimeout(function(){\n self._timeoutError('Timeout of ', self._timeout, 'ETIME');\n }, this._timeout);\n }\n // response timeout\n if (this._responseTimeout && !this._responseTimeoutTimer) {\n this._responseTimeoutTimer = setTimeout(function(){\n self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');\n }, this._responseTimeout);\n }\n}\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/request-base.js\n// module id = 47\n// module chunks = 0","\n/**\n * Module dependencies.\n */\n\nvar utils = require('./utils');\n\n/**\n * Expose `ResponseBase`.\n */\n\nmodule.exports = ResponseBase;\n\n/**\n * Initialize a new `ResponseBase`.\n *\n * @api public\n */\n\nfunction ResponseBase(obj) {\n if (obj) return mixin(obj);\n}\n\n/**\n * Mixin the prototype properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in ResponseBase.prototype) {\n obj[key] = ResponseBase.prototype[key];\n }\n return obj;\n}\n\n/**\n * Get case-insensitive `field` value.\n *\n * @param {String} field\n * @return {String}\n * @api public\n */\n\nResponseBase.prototype.get = function(field){\n return this.header[field.toLowerCase()];\n};\n\n/**\n * Set header related properties:\n *\n * - `.type` the content type without params\n *\n * A response of \"Content-Type: text/plain; charset=utf-8\"\n * will provide you with a `.type` of \"text/plain\".\n *\n * @param {Object} header\n * @api private\n */\n\nResponseBase.prototype._setHeaderProperties = function(header){\n // TODO: moar!\n // TODO: make this a util\n\n // content-type\n var ct = header['content-type'] || '';\n this.type = utils.type(ct);\n\n // params\n var params = utils.params(ct);\n for (var key in params) this[key] = params[key];\n\n this.links = {};\n\n // links\n try {\n if (header.link) {\n this.links = utils.parseLinks(header.link);\n }\n } catch (err) {\n // ignore\n }\n};\n\n/**\n * Set flags such as `.ok` based on `status`.\n *\n * For example a 2xx response will give you a `.ok` of __true__\n * whereas 5xx will be __false__ and `.error` will be __true__. The\n * `.clientError` and `.serverError` are also available to be more\n * specific, and `.statusType` is the class of error ranging from 1..5\n * sometimes useful for mapping respond colors etc.\n *\n * \"sugar\" properties are also defined for common cases. Currently providing:\n *\n * - .noContent\n * - .badRequest\n * - .unauthorized\n * - .notAcceptable\n * - .notFound\n *\n * @param {Number} status\n * @api private\n */\n\nResponseBase.prototype._setStatusProperties = function(status){\n var type = status / 100 | 0;\n\n // status / class\n this.status = this.statusCode = status;\n this.statusType = type;\n\n // basics\n this.info = 1 == type;\n this.ok = 2 == type;\n this.redirect = 3 == type;\n this.clientError = 4 == type;\n this.serverError = 5 == type;\n this.error = (4 == type || 5 == type)\n ? this.toError()\n : false;\n\n // sugar\n this.accepted = 202 == status;\n this.noContent = 204 == status;\n this.badRequest = 400 == status;\n this.unauthorized = 401 == status;\n this.notAcceptable = 406 == status;\n this.forbidden = 403 == status;\n this.notFound = 404 == status;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/response-base.js\n// module id = 48\n// module chunks = 0","var ERROR_CODES = [\n 'ECONNRESET',\n 'ETIMEDOUT',\n 'EADDRINFO',\n 'ESOCKETTIMEDOUT'\n];\n\n/**\n * Determine if a request should be retried.\n * (Borrowed from segmentio/superagent-retry)\n *\n * @param {Error} err\n * @param {Response} [res]\n * @returns {Boolean}\n */\nmodule.exports = function shouldRetry(err, res) {\n if (err && err.code && ~ERROR_CODES.indexOf(err.code)) return true;\n if (res && res.status && res.status >= 500) return true;\n // Superagent timeout\n if (err && 'timeout' in err && err.code == 'ECONNABORTED') return true;\n if (err && 'crossDomain' in err) return true;\n return false;\n};\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/should-retry.js\n// module id = 49\n// module chunks = 0","\n/**\n * Return the mime type for the given `str`.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nexports.type = function(str){\n return str.split(/ *; */).shift();\n};\n\n/**\n * Return header field parameters.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.params = function(str){\n return str.split(/ *; */).reduce(function(obj, str){\n var parts = str.split(/ *= */);\n var key = parts.shift();\n var val = parts.shift();\n\n if (key && val) obj[key] = val;\n return obj;\n }, {});\n};\n\n/**\n * Parse Link header fields.\n *\n * @param {String} str\n * @return {Object}\n * @api private\n */\n\nexports.parseLinks = function(str){\n return str.split(/ *, */).reduce(function(obj, str){\n var parts = str.split(/ *; */);\n var url = parts[0].slice(1, -1);\n var rel = parts[1].split(/ *= */)[1].slice(1, -1);\n obj[rel] = url;\n return obj;\n }, {});\n};\n\n/**\n * Strip content related fields from `header`.\n *\n * @param {Object} header\n * @return {Object} header\n * @api private\n */\n\nexports.cleanHeader = function(header, shouldStripCookie){\n delete header['content-type'];\n delete header['content-length'];\n delete header['transfer-encoding'];\n delete header['host'];\n if (shouldStripCookie) {\n delete header['cookie'];\n }\n return header;\n};\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/superagent/lib/utils.js\n// module id = 50\n// module chunks = 0","/* (ignored) */\n\n\n//////////////////\n// WEBPACK FOOTER\n// vertx (ignored)\n// module id = 51\n// module chunks = 0"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/node/acl.js b/dist/node/acl.js new file mode 100644 index 000000000..c8ec393ad --- /dev/null +++ b/dist/node/acl.js @@ -0,0 +1,259 @@ +'use strict'; + +var _ = require('underscore'); + +module.exports = function (AV) { + var PUBLIC_KEY = "*"; + + /** + * Creates a new ACL. + * If no argument is given, the ACL has no permissions for anyone. + * If the argument is a AV.User, the ACL will have read and write + * permission for only that user. + * If the argument is any other JSON object, that object will be interpretted + * as a serialized ACL created with toJSON(). + * @see AV.Object#setACL + * @class + * + *

An ACL, or Access Control List can be added to any + * AV.Object to restrict access to only a subset of users + * of your application.

+ */ + AV.ACL = function (arg1) { + var self = this; + self.permissionsById = {}; + if (_.isObject(arg1)) { + if (arg1 instanceof AV.User) { + self.setReadAccess(arg1, true); + self.setWriteAccess(arg1, true); + } else { + if (_.isFunction(arg1)) { + throw new Error('AV.ACL() called with a function. Did you forget ()?'); + } + AV._objectEach(arg1, function (accessList, userId) { + if (!_.isString(userId)) { + throw new Error('Tried to create an ACL with an invalid userId.'); + } + self.permissionsById[userId] = {}; + AV._objectEach(accessList, function (allowed, permission) { + if (permission !== "read" && permission !== "write") { + throw new Error('Tried to create an ACL with an invalid permission type.'); + } + if (!_.isBoolean(allowed)) { + throw new Error('Tried to create an ACL with an invalid permission value.'); + } + self.permissionsById[userId][permission] = allowed; + }); + }); + } + } + }; + + /** + * Returns a JSON-encoded version of the ACL. + * @return {Object} + */ + AV.ACL.prototype.toJSON = function () { + return _.clone(this.permissionsById); + }; + + AV.ACL.prototype._setAccess = function (accessType, userId, allowed) { + if (userId instanceof AV.User) { + userId = userId.id; + } else if (userId instanceof AV.Role) { + userId = "role:" + userId.getName(); + } + if (!_.isString(userId)) { + throw new Error('userId must be a string.'); + } + if (!_.isBoolean(allowed)) { + throw new Error('allowed must be either true or false.'); + } + var permissions = this.permissionsById[userId]; + if (!permissions) { + if (!allowed) { + // The user already doesn't have this permission, so no action needed. + return; + } else { + permissions = {}; + this.permissionsById[userId] = permissions; + } + } + + if (allowed) { + this.permissionsById[userId][accessType] = true; + } else { + delete permissions[accessType]; + if (_.isEmpty(permissions)) { + delete this.permissionsById[userId]; + } + } + }; + + AV.ACL.prototype._getAccess = function (accessType, userId) { + if (userId instanceof AV.User) { + userId = userId.id; + } else if (userId instanceof AV.Role) { + userId = "role:" + userId.getName(); + } + var permissions = this.permissionsById[userId]; + if (!permissions) { + return false; + } + return permissions[accessType] ? true : false; + }; + + /** + * Set whether the given user is allowed to read this object. + * @param userId An instance of AV.User or its objectId. + * @param {Boolean} allowed Whether that user should have read access. + */ + AV.ACL.prototype.setReadAccess = function (userId, allowed) { + this._setAccess("read", userId, allowed); + }; + + /** + * Get whether the given user id is *explicitly* allowed to read this object. + * Even if this returns false, the user may still be able to access it if + * getPublicReadAccess returns true or a role that the user belongs to has + * write access. + * @param userId An instance of AV.User or its objectId, or a AV.Role. + * @return {Boolean} + */ + AV.ACL.prototype.getReadAccess = function (userId) { + return this._getAccess("read", userId); + }; + + /** + * Set whether the given user id is allowed to write this object. + * @param userId An instance of AV.User or its objectId, or a AV.Role.. + * @param {Boolean} allowed Whether that user should have write access. + */ + AV.ACL.prototype.setWriteAccess = function (userId, allowed) { + this._setAccess("write", userId, allowed); + }; + + /** + * Get whether the given user id is *explicitly* allowed to write this object. + * Even if this returns false, the user may still be able to write it if + * getPublicWriteAccess returns true or a role that the user belongs to has + * write access. + * @param userId An instance of AV.User or its objectId, or a AV.Role. + * @return {Boolean} + */ + AV.ACL.prototype.getWriteAccess = function (userId) { + return this._getAccess("write", userId); + }; + + /** + * Set whether the public is allowed to read this object. + * @param {Boolean} allowed + */ + AV.ACL.prototype.setPublicReadAccess = function (allowed) { + this.setReadAccess(PUBLIC_KEY, allowed); + }; + + /** + * Get whether the public is allowed to read this object. + * @return {Boolean} + */ + AV.ACL.prototype.getPublicReadAccess = function () { + return this.getReadAccess(PUBLIC_KEY); + }; + + /** + * Set whether the public is allowed to write this object. + * @param {Boolean} allowed + */ + AV.ACL.prototype.setPublicWriteAccess = function (allowed) { + this.setWriteAccess(PUBLIC_KEY, allowed); + }; + + /** + * Get whether the public is allowed to write this object. + * @return {Boolean} + */ + AV.ACL.prototype.getPublicWriteAccess = function () { + return this.getWriteAccess(PUBLIC_KEY); + }; + + /** + * Get whether users belonging to the given role are allowed + * to read this object. Even if this returns false, the role may + * still be able to write it if a parent role has read access. + * + * @param role The name of the role, or a AV.Role object. + * @return {Boolean} true if the role has read access. false otherwise. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.getRoleReadAccess = function (role) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + return this.getReadAccess("role:" + role); + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Get whether users belonging to the given role are allowed + * to write this object. Even if this returns false, the role may + * still be able to write it if a parent role has write access. + * + * @param role The name of the role, or a AV.Role object. + * @return {Boolean} true if the role has write access. false otherwise. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.getRoleWriteAccess = function (role) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + return this.getWriteAccess("role:" + role); + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Set whether users belonging to the given role are allowed + * to read this object. + * + * @param role The name of the role, or a AV.Role object. + * @param {Boolean} allowed Whether the given role can read this object. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.setRoleReadAccess = function (role, allowed) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + this.setReadAccess("role:" + role, allowed); + return; + } + throw new Error('role must be a AV.Role or a String'); + }; + + /** + * Set whether users belonging to the given role are allowed + * to write this object. + * + * @param role The name of the role, or a AV.Role object. + * @param {Boolean} allowed Whether the given role can write this object. + * @throws {String} If role is neither a AV.Role nor a String. + */ + AV.ACL.prototype.setRoleWriteAccess = function (role, allowed) { + if (role instanceof AV.Role) { + // Normalize to the String name + role = role.getName(); + } + if (_.isString(role)) { + this.setWriteAccess("role:" + role, allowed); + return; + } + throw new Error('role must be a AV.Role or a String'); + }; +}; \ No newline at end of file diff --git a/dist/node/av.js b/dist/node/av.js new file mode 100644 index 000000000..10b8d0848 --- /dev/null +++ b/dist/node/av.js @@ -0,0 +1,421 @@ +'use strict'; + +var _ = require('underscore'); +var userAgent = require('./ua'); + +var _require = require('./utils'), + isNullOrUndefined = _require.isNullOrUndefined; + +var AV = global.AV || {}; + +// All internal configuration items +AV._config = AV._config || {}; +var AVConfig = AV._config; + +_.extend(AVConfig, { + + // 服务器节点地区,默认中国大陆 + region: 'cn', + + // 服务器的 URL,默认初始化时被设置为大陆节点地址 + APIServerURL: AVConfig.APIServerURL || '', + + // 禁用 currentUser,通常用于多用户环境 + disableCurrentUser: false, + + // Internal config can modifie the UserAgent + userAgent: userAgent, + + // set production environment or test environment + // 1: production environment, 0: test environment, null: default environment + applicationProduction: null +}); + +/** + * Contains all AV API classes and functions. + * @namespace AV + */ + +// Helpers +// ------- + +// Shared empty constructor function to aid in prototype-chain creation. +var EmptyConstructor = function EmptyConstructor() {}; + +// Helper function to correctly set up the prototype chain, for subclasses. +// Similar to `goog.inherits`, but uses a hash of prototype properties and +// class properties to be extended. +var inherits = function inherits(parent, protoProps, staticProps) { + var child; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent's constructor. + if (protoProps && protoProps.hasOwnProperty('constructor')) { + child = protoProps.constructor; + } else { + /** @ignore */ + child = function child() { + parent.apply(this, arguments); + }; + } + + // Inherit class (static) properties from parent. + _.extend(child, parent); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + EmptyConstructor.prototype = parent.prototype; + child.prototype = new EmptyConstructor(); + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) { + _.extend(child.prototype, protoProps); + } + + // Add static properties to the constructor function, if supplied. + if (staticProps) { + _.extend(child, staticProps); + } + + // Correctly set child's `prototype.constructor`. + child.prototype.constructor = child; + + // Set a convenience property in case the parent's prototype is + // needed later. + child.__super__ = parent.prototype; + + return child; +}; + +/** + * Call this method to set production environment variable. + * @function AV.setProduction + * @param {Boolean} production True is production environment,and + * it's true by default. + */ +AV.setProduction = function (production) { + if (!isNullOrUndefined(production)) { + AVConfig.applicationProduction = production ? 1 : 0; + } else { + // change to default value + AVConfig.applicationProduction = null; + } +}; + +/** + * Returns prefix for localStorage keys used by this instance of AV. + * @param {String} path The relative suffix to append to it. + * null or undefined is treated as the empty string. + * @return {String} The full key name. + * @private + */ +AV._getAVPath = function (path) { + if (!AV.applicationId) { + throw new Error("You need to call AV.initialize before using AV."); + } + if (!path) { + path = ""; + } + if (!_.isString(path)) { + throw new Error("Tried to get a localStorage path that wasn't a String."); + } + if (path[0] === "/") { + path = path.substring(1); + } + return "AV/" + AV.applicationId + "/" + path; +}; + +/** + * Returns the unique string for this app on this machine. + * Gets reset when localStorage is cleared. + * @private + */ +AV._installationId = null; +AV._getInstallationId = function () { + // See if it's cached in RAM. + if (AV._installationId) { + return AV.Promise.resolve(AV._installationId); + } + + // Try to get it from localStorage. + var path = AV._getAVPath("installationId"); + return AV.localStorage.getItemAsync(path).then(function (_installationId) { + AV._installationId = _installationId; + if (!AV._installationId) { + // It wasn't in localStorage, so create a new one. + var hexOctet = function hexOctet() { + return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + }; + AV._installationId = hexOctet() + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + "-" + hexOctet() + hexOctet() + hexOctet(); + return AV.localStorage.setItemAsync(path, AV._installationId); + } else { + return _installationId; + } + }); +}; + +AV._parseDate = function (iso8601) { + var regexp = new RegExp("^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})" + "T" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})" + "(.([0-9]+))?" + "Z$"); + var match = regexp.exec(iso8601); + if (!match) { + return null; + } + + var year = match[1] || 0; + var month = (match[2] || 1) - 1; + var day = match[3] || 0; + var hour = match[4] || 0; + var minute = match[5] || 0; + var second = match[6] || 0; + var milli = match[8] || 0; + + return new Date(Date.UTC(year, month, day, hour, minute, second, milli)); +}; + +// A self-propagating extend function. +AV._extend = function (protoProps, classProps) { + var child = inherits(this, protoProps, classProps); + child.extend = this.extend; + return child; +}; + +// Helper function to get a value from a Backbone object as a property +// or as a function. +AV._getValue = function (object, prop) { + if (!(object && object[prop])) { + return null; + } + return _.isFunction(object[prop]) ? object[prop]() : object[prop]; +}; + +/** + * Converts a value in a AV Object into the appropriate representation. + * This is the JS equivalent of Java's AV.maybeReferenceAndEncode(Object) + * if seenObjects is falsey. Otherwise any AV.Objects not in + * seenObjects will be fully embedded rather than encoded + * as a pointer. This array will be used to prevent going into an infinite + * loop because we have circular references. If + * is set, then none of the AV Objects that are serialized can be dirty. + * @private + */ +AV._encode = function (value, seenObjects, disallowObjects) { + if (value instanceof AV.Object) { + if (disallowObjects) { + throw new Error("AV.Objects not allowed here"); + } + if (!seenObjects || _.include(seenObjects, value) || !value._hasData) { + return value._toPointer(); + } + if (!value.dirty()) { + seenObjects = seenObjects.concat(value); + return AV._encode(value._toFullJSON(seenObjects), seenObjects, disallowObjects); + } + throw new Error("Tried to save an object with a pointer to a new, unsaved object."); + } + if (value instanceof AV.ACL) { + return value.toJSON(); + } + if (_.isDate(value)) { + return { "__type": "Date", "iso": value.toJSON() }; + } + if (value instanceof AV.GeoPoint) { + return value.toJSON(); + } + if (_.isArray(value)) { + return _.map(value, function (x) { + return AV._encode(x, seenObjects, disallowObjects); + }); + } + if (_.isRegExp(value)) { + return value.source; + } + if (value instanceof AV.Relation) { + return value.toJSON(); + } + if (value instanceof AV.Op) { + return value.toJSON(); + } + if (value instanceof AV.File) { + if (!value.url() && !value.id) { + throw new Error("Tried to save an object containing an unsaved file."); + } + return value._toFullJSON(); + } + if (_.isObject(value)) { + return _.mapObject(value, function (v, k) { + return AV._encode(v, seenObjects, disallowObjects); + }); + } + return value; +}; + +/** + * The inverse function of AV._encode. + * @private + */ +AV._decode = function (value, key) { + if (!_.isObject(value) || _.isDate(value)) { + return value; + } + if (_.isArray(value)) { + return _.map(value, function (v) { + return AV._decode(v); + }); + } + if (value instanceof AV.Object) { + return value; + } + if (value instanceof AV.File) { + return value; + } + if (value instanceof AV.Op) { + return value; + } + if (value instanceof AV.GeoPoint) { + return value; + } + if (value instanceof AV.ACL) { + return value; + } + if (key === 'ACL') { + return new AV.ACL(value); + } + if (value.__op) { + return AV.Op._decode(value); + } + var className; + if (value.__type === "Pointer") { + className = value.className; + var pointer = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + if (Object.keys(value).length > 3) { + var v = _.clone(value); + delete v.__type; + delete v.className; + pointer._finishFetch(v, true); + } else { + pointer._finishFetch({ objectId: value.objectId }, false); + } + return pointer; + } + if (value.__type === "Object") { + // It's an Object included in a query result. + className = value.className; + var _v = _.clone(value); + delete _v.__type; + delete _v.className; + var object = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + object._finishFetch(_v, true); + return object; + } + if (value.__type === "Date") { + return AV._parseDate(value.iso); + } + if (value.__type === "GeoPoint") { + return new AV.GeoPoint({ + latitude: value.latitude, + longitude: value.longitude + }); + } + if (value.__type === "Relation") { + if (!key) throw new Error('key missing decoding a Relation'); + var relation = new AV.Relation(null, key); + relation.targetClassName = value.className; + return relation; + } + if (value.__type === 'File') { + var file = new AV.File(value.name); + var _v2 = _.clone(value); + delete _v2.__type; + file._finishFetch(_v2); + return file; + } + return _.mapObject(value, AV._decode); +}; + +AV._encodeObjectOrArray = function (value) { + var encodeAVObject = function encodeAVObject(object) { + if (object && object._toFullJSON) { + object = object._toFullJSON([]); + } + + return _.mapObject(object, function (value) { + return AV._encode(value, []); + }); + }; + + if (_.isArray(value)) { + return value.map(function (object) { + return encodeAVObject(object); + }); + } else { + return encodeAVObject(value); + } +}; + +AV._arrayEach = _.each; + +/** + * Does a deep traversal of every item in object, calling func on every one. + * @param {Object} object The object or array to traverse deeply. + * @param {Function} func The function to call for every item. It will + * be passed the item as an argument. If it returns a truthy value, that + * value will replace the item in its parent container. + * @returns {} the result of calling func on the top-level object itself. + * @private + */ +AV._traverse = function (object, func, seen) { + if (object instanceof AV.Object) { + seen = seen || []; + if (_.indexOf(seen, object) >= 0) { + // We've already visited this object in this call. + return; + } + seen.push(object); + AV._traverse(object.attributes, func, seen); + return func(object); + } + if (object instanceof AV.Relation || object instanceof AV.File) { + // Nothing needs to be done, but we don't want to recurse into the + // object's parent infinitely, so we catch this case. + return func(object); + } + if (_.isArray(object)) { + _.each(object, function (child, index) { + var newChild = AV._traverse(child, func, seen); + if (newChild) { + object[index] = newChild; + } + }); + return func(object); + } + if (_.isObject(object)) { + AV._each(object, function (child, key) { + var newChild = AV._traverse(child, func, seen); + if (newChild) { + object[key] = newChild; + } + }); + return func(object); + } + return func(object); +}; + +/** + * This is like _.each, except: + * * it doesn't work for so-called array-like objects, + * * it does work for dictionaries with a "length" attribute. + * @private + */ +AV._objectEach = AV._each = function (obj, callback) { + if (_.isObject(obj)) { + _.each(_.keys(obj), function (key) { + callback(obj[key], key); + }); + } else { + _.each(obj, callback); + } +}; + +module.exports = AV; \ No newline at end of file diff --git a/dist/node/cache.js b/dist/node/cache.js new file mode 100644 index 000000000..f80095d87 --- /dev/null +++ b/dist/node/cache.js @@ -0,0 +1,39 @@ +'use strict'; + +var storage = require('./localstorage'); +var AV = require('./av'); + +var removeAsync = exports.removeAsync = storage.removeItemAsync.bind(storage); + +var getCacheData = function getCacheData(cacheData, key) { + try { + cacheData = JSON.parse(cacheData); + } catch (e) { + return null; + } + if (cacheData) { + var expired = cacheData.expiredAt && cacheData.expiredAt < Date.now(); + if (!expired) { + return cacheData.value; + } + return removeAsync(key).then(function () { + return null; + }); + } + return null; +}; + +exports.getAsync = function (key) { + key = AV.applicationId + '/' + key; + return storage.getItemAsync(key).then(function (cache) { + return getCacheData(cache, key); + }); +}; + +exports.setAsync = function (key, value, ttl) { + var cache = { value: value }; + if (typeof ttl === 'number') { + cache.expiredAt = Date.now() + ttl; + } + return storage.setItemAsync(AV.applicationId + '/' + key, JSON.stringify(cache)); +}; \ No newline at end of file diff --git a/dist/node/cloudfunction.js b/dist/node/cloudfunction.js new file mode 100644 index 000000000..8459ac9f1 --- /dev/null +++ b/dist/node/cloudfunction.js @@ -0,0 +1,102 @@ +'use strict'; + +var _ = require('underscore'); +var AVRequest = require('./request').request; + +module.exports = function (AV) { + /** + * Contains functions for calling and declaring + *

+ * Some functions are only available from Cloud Code. + *

+ * + * @namespace + */ + AV.Cloud = AV.Cloud || {}; + + _.extend(AV.Cloud, /** @lends AV.Cloud */{ + /** + * Makes a call to a cloud function. + * @param {String} name The function name. + * @param {Object} data The parameters to send to the cloud function. + * @param {AuthOptions} options + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + run: function run(name, data, options) { + var request = AVRequest('functions', name, null, 'POST', AV._encode(data, null, true), options); + + return request.then(function (resp) { + return AV._decode(resp).result; + }); + }, + + /** + * Makes a call to a cloud function, you can send {AV.Object} as param or a field of param; the response + * from server will also be parsed as an {AV.Object}, array of {AV.Object}, or object includes {AV.Object} + * @param {String} name The function name. + * @param {Object} data The parameters to send to the cloud function. + * @param {AuthOptions} options + * @return {Promise} A promise that will be resolved with the result of the function. + */ + rpc: function rpc(name, data, options) { + if (_.isArray(data)) { + return Promise.reject(new Error('Can\'t pass Array as the param of rpc function in JavaScript SDK.')); + } + + return AVRequest('call', name, null, 'POST', AV._encodeObjectOrArray(data), options).then(function (resp) { + return AV._decode(resp).result; + }); + }, + + /** + * Make a call to request server date time. + * @return {Promise.} A promise that will be resolved with the result + * of the function. + * @since 0.5.9 + */ + getServerDate: function getServerDate() { + var request = AVRequest("date", null, null, 'GET'); + + return request.then(function (resp) { + return AV._decode(resp); + }); + }, + + /** + * Makes a call to request a sms code for operation verification. + * @param {Object} data The mobile phone number string or a JSON + * object that contains mobilePhoneNumber,template,op,ttl,name etc. + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + requestSmsCode: function requestSmsCode(data) { + if (_.isString(data)) { + data = { mobilePhoneNumber: data }; + } + if (!data.mobilePhoneNumber) { + throw new Error('Missing mobilePhoneNumber.'); + } + var request = AVRequest("requestSmsCode", null, null, 'POST', data); + return request; + }, + + /** + * Makes a call to verify sms code that sent by AV.Cloud.requestSmsCode + * @param {String} code The sms code sent by AV.Cloud.requestSmsCode + * @param {phone} phone The mobile phoner number(optional). + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + verifySmsCode: function verifySmsCode(code, phone) { + if (!code) throw new Error('Missing sms code.'); + var params = {}; + if (_.isString(phone)) { + params['mobilePhoneNumber'] = phone; + } + + var request = AVRequest("verifySmsCode", code, null, 'POST', params); + return request; + } + }); +}; \ No newline at end of file diff --git a/dist/node/error.js b/dist/node/error.js new file mode 100644 index 000000000..52135e6d5 --- /dev/null +++ b/dist/node/error.js @@ -0,0 +1,341 @@ +'use strict'; + +var _ = require('underscore'); + +/** + * @class AV.Error + */ + +function AVError(code, message) { + var error = new Error(message); + error.code = code; + return error; +} + +_.extend(AVError, /** @lends AV.Error */{ + /** + * Error code indicating some error other than those enumerated here. + * @constant + */ + OTHER_CAUSE: -1, + + /** + * Error code indicating that something has gone wrong with the server. + * If you get this error code, it is AV's fault. Contact us at + * https://avoscloud.com/help + * @constant + */ + INTERNAL_SERVER_ERROR: 1, + + /** + * Error code indicating the connection to the AV servers failed. + * @constant + */ + CONNECTION_FAILED: 100, + + /** + * Error code indicating the specified object doesn't exist. + * @constant + */ + OBJECT_NOT_FOUND: 101, + + /** + * Error code indicating you tried to query with a datatype that doesn't + * support it, like exact matching an array or object. + * @constant + */ + INVALID_QUERY: 102, + + /** + * Error code indicating a missing or invalid classname. Classnames are + * case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the + * only valid characters. + * @constant + */ + INVALID_CLASS_NAME: 103, + + /** + * Error code indicating an unspecified object id. + * @constant + */ + MISSING_OBJECT_ID: 104, + + /** + * Error code indicating an invalid key name. Keys are case-sensitive. They + * must start with a letter, and a-zA-Z0-9_ are the only valid characters. + * @constant + */ + INVALID_KEY_NAME: 105, + + /** + * Error code indicating a malformed pointer. You should not see this unless + * you have been mucking about changing internal AV code. + * @constant + */ + INVALID_POINTER: 106, + + /** + * Error code indicating that badly formed JSON was received upstream. This + * either indicates you have done something unusual with modifying how + * things encode to JSON, or the network is failing badly. + * @constant + */ + INVALID_JSON: 107, + + /** + * Error code indicating that the feature you tried to access is only + * available internally for testing purposes. + * @constant + */ + COMMAND_UNAVAILABLE: 108, + + /** + * You must call AV.initialize before using the AV library. + * @constant + */ + NOT_INITIALIZED: 109, + + /** + * Error code indicating that a field was set to an inconsistent type. + * @constant + */ + INCORRECT_TYPE: 111, + + /** + * Error code indicating an invalid channel name. A channel name is either + * an empty string (the broadcast channel) or contains only a-zA-Z0-9_ + * characters. + * @constant + */ + INVALID_CHANNEL_NAME: 112, + + /** + * Error code indicating that push is misconfigured. + * @constant + */ + PUSH_MISCONFIGURED: 115, + + /** + * Error code indicating that the object is too large. + * @constant + */ + OBJECT_TOO_LARGE: 116, + + /** + * Error code indicating that the operation isn't allowed for clients. + * @constant + */ + OPERATION_FORBIDDEN: 119, + + /** + * Error code indicating the result was not found in the cache. + * @constant + */ + CACHE_MISS: 120, + + /** + * Error code indicating that an invalid key was used in a nested + * JSONObject. + * @constant + */ + INVALID_NESTED_KEY: 121, + + /** + * Error code indicating that an invalid filename was used for AVFile. + * A valid file name contains only a-zA-Z0-9_. characters and is between 1 + * and 128 characters. + * @constant + */ + INVALID_FILE_NAME: 122, + + /** + * Error code indicating an invalid ACL was provided. + * @constant + */ + INVALID_ACL: 123, + + /** + * Error code indicating that the request timed out on the server. Typically + * this indicates that the request is too expensive to run. + * @constant + */ + TIMEOUT: 124, + + /** + * Error code indicating that the email address was invalid. + * @constant + */ + INVALID_EMAIL_ADDRESS: 125, + + /** + * Error code indicating a missing content type. + * @constant + */ + MISSING_CONTENT_TYPE: 126, + + /** + * Error code indicating a missing content length. + * @constant + */ + MISSING_CONTENT_LENGTH: 127, + + /** + * Error code indicating an invalid content length. + * @constant + */ + INVALID_CONTENT_LENGTH: 128, + + /** + * Error code indicating a file that was too large. + * @constant + */ + FILE_TOO_LARGE: 129, + + /** + * Error code indicating an error saving a file. + * @constant + */ + FILE_SAVE_ERROR: 130, + + /** + * Error code indicating an error deleting a file. + * @constant + */ + FILE_DELETE_ERROR: 153, + + /** + * Error code indicating that a unique field was given a value that is + * already taken. + * @constant + */ + DUPLICATE_VALUE: 137, + + /** + * Error code indicating that a role's name is invalid. + * @constant + */ + INVALID_ROLE_NAME: 139, + + /** + * Error code indicating that an application quota was exceeded. Upgrade to + * resolve. + * @constant + */ + EXCEEDED_QUOTA: 140, + + /** + * Error code indicating that a Cloud Code script failed. + * @constant + */ + SCRIPT_FAILED: 141, + + /** + * Error code indicating that a Cloud Code validation failed. + * @constant + */ + VALIDATION_ERROR: 142, + + /** + * Error code indicating that invalid image data was provided. + * @constant + */ + INVALID_IMAGE_DATA: 150, + + /** + * Error code indicating an unsaved file. + * @constant + */ + UNSAVED_FILE_ERROR: 151, + + /** + * Error code indicating an invalid push time. + */ + INVALID_PUSH_TIME_ERROR: 152, + + /** + * Error code indicating that the username is missing or empty. + * @constant + */ + USERNAME_MISSING: 200, + + /** + * Error code indicating that the password is missing or empty. + * @constant + */ + PASSWORD_MISSING: 201, + + /** + * Error code indicating that the username has already been taken. + * @constant + */ + USERNAME_TAKEN: 202, + + /** + * Error code indicating that the email has already been taken. + * @constant + */ + EMAIL_TAKEN: 203, + + /** + * Error code indicating that the email is missing, but must be specified. + * @constant + */ + EMAIL_MISSING: 204, + + /** + * Error code indicating that a user with the specified email was not found. + * @constant + */ + EMAIL_NOT_FOUND: 205, + + /** + * Error code indicating that a user object without a valid session could + * not be altered. + * @constant + */ + SESSION_MISSING: 206, + + /** + * Error code indicating that a user can only be created through signup. + * @constant + */ + MUST_CREATE_USER_THROUGH_SIGNUP: 207, + + /** + * Error code indicating that an an account being linked is already linked + * to another user. + * @constant + */ + ACCOUNT_ALREADY_LINKED: 208, + + /** + * Error code indicating that a user cannot be linked to an account because + * that account's id could not be found. + * @constant + */ + LINKED_ID_MISSING: 250, + + /** + * Error code indicating that a user with a linked (e.g. Facebook) account + * has an invalid session. + * @constant + */ + INVALID_LINKED_SESSION: 251, + + /** + * Error code indicating that a service being linked (e.g. Facebook or + * Twitter) is unsupported. + * @constant + */ + UNSUPPORTED_SERVICE: 252, + /** + * Error code indicating a real error code is unavailable because + * we had to use an XDomainRequest object to allow CORS requests in + * Internet Explorer, which strips the body from HTTP responses that have + * a non-2XX status code. + * @constant + */ + X_DOMAIN_REQUEST: 602 +}); + +module.exports = AVError; \ No newline at end of file diff --git a/dist/node/event.js b/dist/node/event.js new file mode 100644 index 000000000..5762d1660 --- /dev/null +++ b/dist/node/event.js @@ -0,0 +1,154 @@ +'use strict'; + +var _ = require('underscore'); + +module.exports = function (AV) { + var eventSplitter = /\s+/; + var slice = Array.prototype.slice; + + /** + * @class + * + *

AV.Events is a fork of Backbone's Events module, provided for your + * convenience.

+ * + *

A module that can be mixed in to any object in order to provide + * it with custom events. You may bind callback functions to an event + * with `on`, or remove these functions with `off`. + * Triggering an event fires all callbacks in the order that `on` was + * called. + * + * @private + * @example + * var object = {}; + * _.extend(object, AV.Events); + * object.on('expand', function(){ alert('expanded'); }); + * object.trigger('expand');

+ * + */ + AV.Events = { + /** + * Bind one or more space separated events, `events`, to a `callback` + * function. Passing `"all"` will bind the callback to all events fired. + */ + on: function on(events, callback, context) { + + var calls, event, node, tail, list; + if (!callback) { + return this; + } + events = events.split(eventSplitter); + calls = this._callbacks || (this._callbacks = {}); + + // Create an immutable callback list, allowing traversal during + // modification. The tail is an empty object that will always be used + // as the next node. + event = events.shift(); + while (event) { + list = calls[event]; + node = list ? list.tail : {}; + node.next = tail = {}; + node.context = context; + node.callback = callback; + calls[event] = { tail: tail, next: list ? list.next : node }; + event = events.shift(); + } + + return this; + }, + + /** + * Remove one or many callbacks. If `context` is null, removes all callbacks + * with that function. If `callback` is null, removes all callbacks for the + * event. If `events` is null, removes all bound callbacks for all events. + */ + off: function off(events, callback, context) { + var event, calls, node, tail, cb, ctx; + + // No events, or removing *all* events. + if (!(calls = this._callbacks)) { + return; + } + if (!(events || callback || context)) { + delete this._callbacks; + return this; + } + + // Loop through the listed events and contexts, splicing them out of the + // linked list of callbacks if appropriate. + events = events ? events.split(eventSplitter) : _.keys(calls); + event = events.shift(); + while (event) { + node = calls[event]; + delete calls[event]; + if (!node || !(callback || context)) { + continue; + } + // Create a new list, omitting the indicated callbacks. + tail = node.tail; + node = node.next; + while (node !== tail) { + cb = node.callback; + ctx = node.context; + if (callback && cb !== callback || context && ctx !== context) { + this.on(event, cb, ctx); + } + node = node.next; + } + event = events.shift(); + } + + return this; + }, + + /** + * Trigger one or many events, firing all bound callbacks. Callbacks are + * passed the same arguments as `trigger` is, apart from the event name + * (unless you're listening on `"all"`, which will cause your callback to + * receive the true name of the event as the first argument). + */ + trigger: function trigger(events) { + var event, node, calls, tail, args, all, rest; + if (!(calls = this._callbacks)) { + return this; + } + all = calls.all; + events = events.split(eventSplitter); + rest = slice.call(arguments, 1); + + // For each event, walk through the linked list of callbacks twice, + // first to trigger the event, then to trigger any `"all"` callbacks. + event = events.shift(); + while (event) { + node = calls[event]; + if (node) { + tail = node.tail; + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, rest); + } + } + node = all; + if (node) { + tail = node.tail; + args = [event].concat(rest); + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, args); + } + } + event = events.shift(); + } + + return this; + } + }; + + /** + * @function + */ + AV.Events.bind = AV.Events.on; + + /** + * @function + */ + AV.Events.unbind = AV.Events.off; +}; \ No newline at end of file diff --git a/dist/node/file.js b/dist/node/file.js new file mode 100644 index 000000000..c1c9167ed --- /dev/null +++ b/dist/node/file.js @@ -0,0 +1,568 @@ +'use strict'; + +var _ = require('underscore'); +var cos = require('./uploader/cos'); +var qiniu = require('./uploader/qiniu'); +var s3 = require('./uploader/s3'); +var AVError = require('./error'); +var AVRequest = require('./request').request; +var Promise = require('./promise'); + +var _require = require('./utils'), + tap = _require.tap; + +var debug = require('debug')('leancloud:file'); +var parseBase64 = require('./utils/parse-base64'); + +module.exports = function (AV) { + + // 挂载一些配置 + var avConfig = AV._config; + + var hexOctet = function hexOctet() { + return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); + }; + + // port from browserify path module + // since react-native packager won't shim node modules. + var extname = function extname(path) { + return path.match(/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/)[4]; + }; + + var b64Digit = function b64Digit(number) { + if (number < 26) { + return String.fromCharCode(65 + number); + } + if (number < 52) { + return String.fromCharCode(97 + (number - 26)); + } + if (number < 62) { + return String.fromCharCode(48 + (number - 52)); + } + if (number === 62) { + return '+'; + } + if (number === 63) { + return '/'; + } + throw new Error('Tried to encode large digit ' + number + ' in base64.'); + }; + + var encodeBase64 = function encodeBase64(array) { + var chunks = []; + chunks.length = Math.ceil(array.length / 3); + _.times(chunks.length, function (i) { + var b1 = array[i * 3]; + var b2 = array[i * 3 + 1] || 0; + var b3 = array[i * 3 + 2] || 0; + + var has2 = i * 3 + 1 < array.length; + var has3 = i * 3 + 2 < array.length; + + chunks[i] = [b64Digit(b1 >> 2 & 0x3F), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0F), has2 ? b64Digit(b2 << 2 & 0x3C | b3 >> 6 & 0x03) : "=", has3 ? b64Digit(b3 & 0x3F) : "="].join(""); + }); + return chunks.join(""); + }; + + /** + * An AV.File is a local representation of a file that is saved to the AV + * cloud. + * @param name {String} The file's name. This will change to a unique value + * once the file has finished saving. + * @param data {Array} The data for the file, as either: + * 1. an Array of byte value Numbers, or + * 2. an Object like { base64: "..." } with a base64-encoded String. + * 3. a File object selected with a file upload control. (3) only works + * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+. + * 4.a Buffer object in Node.js runtime. + * + * For example:
+   * var fileUploadControl = $("#profilePhotoFileUpload")[0];
+   * if (fileUploadControl.files.length > 0) {
+   *   var file = fileUploadControl.files[0];
+   *   var name = "photo.jpg";
+   *   var file = new AV.File(name, file);
+   *   file.save().then(function() {
+   *     // The file has been saved to AV.
+   *   }, function(error) {
+   *     // The file either could not be read, or could not be saved to AV.
+   *   });
+   * }
+ * + * @class + * @param [mimeType] {String} Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + */ + AV.File = function (name, data, mimeType) { + + this.attributes = { + name: name, + url: '', + metaData: {}, + // 用来存储转换后要上传的 base64 String + base64: '' + }; + + if (_.isString(data)) { + throw new TypeError("Creating an AV.File from a String is not yet supported."); + } + if (_.isArray(data)) { + this.attributes.metaData.size = data.length; + data = { base64: encodeBase64(data) }; + } + + this._extName = ''; + this._data = data; + + var owner = void 0; + if (data && data.owner) { + owner = data.owner; + } else if (!AV._config.disableCurrentUser) { + try { + owner = AV.User.current(); + } catch (error) { + if ('SYNC_API_NOT_AVAILABLE' === error.code) { + console.warn('Get current user failed. It seems this runtime use an async storage system, please create AV.File in the callback of AV.User.currentAsync().'); + } else { + throw error; + } + } + } + + this.attributes.metaData.owner = owner ? owner.id : 'unknown'; + + this.set('mime_type', mimeType); + }; + + /** + * Creates a fresh AV.File object with exists url for saving to AVOS Cloud. + * @param {String} name the file name + * @param {String} url the file url. + * @param {Object} [metaData] the file metadata object. + * @param {String} [type] Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + * @return {AV.File} the file object + */ + AV.File.withURL = function (name, url, metaData, type) { + if (!name || !url) { + throw new Error("Please provide file name and url"); + } + var file = new AV.File(name, null, type); + //copy metaData properties to file. + if (metaData) { + for (var prop in metaData) { + if (!file.attributes.metaData[prop]) file.attributes.metaData[prop] = metaData[prop]; + } + } + file.attributes.url = url; + //Mark the file is from external source. + file.attributes.metaData.__source = 'external'; + return file; + }; + + /** + * Creates a file object with exists objectId. + * @param {String} objectId The objectId string + * @return {AV.File} the file object + */ + AV.File.createWithoutData = function (objectId) { + var file = new AV.File(); + file.id = objectId; + return file; + }; + + AV.File.prototype = { + className: '_File', + + _toFullJSON: function _toFullJSON(seenObjects) { + var _this = this; + + var json = _.clone(this.attributes); + AV._objectEach(json, function (val, key) { + json[key] = AV._encode(val, seenObjects); + }); + AV._objectEach(this._operations, function (val, key) { + json[key] = val; + }); + + if (_.has(this, "id")) { + json.objectId = this.id; + } + _(['createdAt', 'updatedAt']).each(function (key) { + if (_.has(_this, key)) { + var val = _this[key]; + json[key] = _.isDate(val) ? val.toJSON() : val; + } + }); + json.__type = "File"; + return json; + }, + toJSON: function toJSON() { + var json = this._toFullJSON(); + // add id and keep __type for backward compatible + if (_.has(this, 'id')) { + json.id = this.id; + } + return json; + }, + + + /** + * Returns the ACL for this file. + * @returns {AV.ACL} An instance of AV.ACL. + */ + getACL: function getACL() { + return this._acl; + }, + + /** + * Sets the ACL to be used for this file. + * @param {AV.ACL} acl An instance of AV.ACL. + */ + setACL: function setACL(acl) { + if (!(acl instanceof AV.ACL)) { + return new AVError(AVError.OTHER_CAUSE, 'ACL must be a AV.ACL.'); + } + this._acl = acl; + }, + + /** + * Gets the name of the file. Before save is called, this is the filename + * given by the user. After save is called, that name gets prefixed with a + * unique identifier. + */ + name: function name() { + return this.get('name'); + }, + + /** + * Gets the url of the file. It is only available after you save the file or + * after you get the file from a AV.Object. + * @return {String} + */ + url: function url() { + return this.get('url'); + }, + + /** + * Gets the attributs of the file object. + * @param {String} The attribute name which want to get. + * @returns {Any} + */ + get: function get(attrName) { + switch (attrName) { + case 'objectId': + return this.id; + case 'url': + case 'name': + case 'mime_type': + case 'metaData': + case 'createdAt': + case 'updatedAt': + return this.attributes[attrName]; + default: + return this.attributes.metaData[attrName]; + } + }, + + /** + * Set the metaData of the file object. + * @param {Object} Object is an key value Object for setting metaData. + * @param {String} attr is an optional metadata key. + * @param {Object} value is an optional metadata value. + * @returns {String|Number|Array|Object} + */ + set: function set() { + var _this2 = this; + + var set = function set(attrName, value) { + switch (attrName) { + case 'name': + case 'url': + case 'mime_type': + case 'base64': + case 'metaData': + _this2.attributes[attrName] = value; + break; + default: + // File 并非一个 AVObject,不能完全自定义其他属性,所以只能都放在 metaData 上面 + _this2.attributes.metaData[attrName] = value; + break; + } + }; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + switch (args.length) { + case 1: + // 传入一个 Object + for (var k in args[0]) { + set(k, args[0][k]); + } + break; + case 2: + set(args[0], args[1]); + break; + } + }, + + /** + *

Returns the file's metadata JSON object if no arguments is given.Returns the + * metadata value if a key is given.Set metadata value if key and value are both given.

+ *

+    *  var metadata = file.metaData(); //Get metadata JSON object.
+    *  var size = file.metaData('size');  // Get the size metadata value.
+    *  file.metaData('format', 'jpeg'); //set metadata attribute and value.
+    *

+ * @return {Object} The file's metadata JSON object. + * @param {String} attr an optional metadata key. + * @param {Object} value an optional metadata value. + **/ + metaData: function metaData(attr, value) { + if (attr && value) { + this.attributes.metaData[attr] = value; + return this; + } else if (attr && !value) { + return this.attributes.metaData[attr]; + } else { + return this.attributes.metaData; + } + }, + + /** + * 如果文件是图片,获取图片的缩略图URL。可以传入宽度、高度、质量、格式等参数。 + * @return {String} 缩略图URL + * @param {Number} width 宽度,单位:像素 + * @param {Number} heigth 高度,单位:像素 + * @param {Number} quality 质量,1-100的数字,默认100 + * @param {Number} scaleToFit 是否将图片自适应大小。默认为true。 + * @param {String} fmt 格式,默认为png,也可以为jpeg,gif等格式。 + */ + + thumbnailURL: function thumbnailURL(width, height, quality, scaleToFit, fmt) { + var url = this.attributes.url; + if (!url) { + throw new Error('Invalid url.'); + } + if (!width || !height || width <= 0 || height <= 0) { + throw new Error('Invalid width or height value.'); + } + quality = quality || 100; + scaleToFit = !scaleToFit ? true : scaleToFit; + if (quality <= 0 || quality > 100) { + throw new Error('Invalid quality value.'); + } + fmt = fmt || 'png'; + var mode = scaleToFit ? 2 : 1; + return url + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt; + }, + + /** + * Returns the file's size. + * @return {Number} The file's size in bytes. + **/ + size: function size() { + return this.metaData().size; + }, + + /** + * Returns the file's owner. + * @return {String} The file's owner id. + */ + ownerId: function ownerId() { + return this.metaData().owner; + }, + + /** + * Destroy the file. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + if (!this.id) { + return Promise.reject(new Error('The file id is not eixsts.')); + } + var request = AVRequest("files", null, this.id, 'DELETE', null, options); + return request; + }, + + /** + * Request Qiniu upload token + * @param {string} type + * @return {Promise} Resolved with the response + * @private + */ + _fileToken: function _fileToken(type) { + var route = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'fileTokens'; + + var name = this.attributes.name; + + var extName = extname(name); + if (!extName && this._extName) { + name += this._extName; + extName = this._extName; + } + // Create 16-bits uuid as qiniu key. + var key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName; + var data = { + key: key, + name: name, + ACL: this._acl, + mime_type: type, + metaData: this.attributes.metaData + }; + this._qiniu_key = key; + return AVRequest(route, null, null, 'POST', data); + }, + + + /** + * @callback UploadProgressCallback + * @param {XMLHttpRequestProgressEvent} event - The progress event with 'loaded' and 'total' attributes + */ + /** + * Saves the file to the AV cloud. + * @param {Object} [options] + * @param {UploadProgressCallback} [options.onprogress] 文件上传进度,在 Node.js 与小程序中无效,回调参数说明详见 {@link UploadProgressCallback}。 + * @return {Promise} Promise that is resolved when the save finishes. + */ + save: function save(options) { + var _this3 = this; + + if (this.id) { + throw new Error('File already saved. If you want to manipulate a file, use AV.Query to get it.'); + } + if (!this._previousSave) { + if (this._data) { + var mimeType = this.get('mime_type'); + this._previousSave = this._fileToken(mimeType).then(function (uploadInfo) { + if (uploadInfo.mime_type) { + mimeType = uploadInfo.mime_type; + _this3.set('mime_type', mimeType); + } + _this3._token = uploadInfo.token; + return Promise.resolve().then(function () { + var data = _this3._data; + if (data && data.base64) { + return parseBase64(data.base64, mimeType); + } + if (data && data.blob) { + if (!data.blob.type && mimeType) { + data.blob.type = mimeType; + } + if (!data.blob.name) { + data.blob.name = _this3.get('name'); + } + if (process.env.CLIENT_PLATFORM === 'ReactNative' || process.env.CLIENT_PLATFORM === 'Weapp') { + _this3._extName = extname(data.blob.uri); + } + return data.blob; + } + if (typeof File !== "undefined" && data instanceof File) { + if (data.size) { + _this3.attributes.metaData.size = data.size; + } + if (data.name) { + _this3._extName = extname(data.name); + } + return data; + } + if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) { + _this3.attributes.metaData.size = data.length; + return data; + } + throw new TypeError('malformed file data'); + }).then(function (data) { + var uploadPromise = void 0; + switch (uploadInfo.provider) { + case 's3': + uploadPromise = s3(uploadInfo, data, _this3, options); + break; + case 'qcloud': + uploadPromise = cos(uploadInfo, data, _this3, options); + break; + case 'qiniu': + default: + uploadPromise = qiniu(uploadInfo, data, _this3, options); + break; + } + return uploadPromise.then(tap(function () { + return _this3._callback(true); + }), function (error) { + _this3._callback(false); + throw error; + }); + }); + }); + } else if (this.attributes.url && this.attributes.metaData.__source === 'external') { + // external link file. + var data = { + name: this.attributes.name, + ACL: this._acl, + metaData: this.attributes.metaData, + mime_type: this.mimeType, + url: this.attributes.url + }; + this._previousSave = AVRequest('files', this.attributes.name, null, 'post', data).then(function (response) { + _this3.attributes.name = response.name; + _this3.attributes.url = response.url; + _this3.id = response.objectId; + if (response.size) { + _this3.attributes.metaData.size = response.size; + } + return _this3; + }); + } + } + return this._previousSave; + }, + _callback: function _callback(success) { + AVRequest('fileCallback', null, null, 'post', { + token: this._token, + result: success + }).catch(debug); + delete this._token; + delete this._data; + }, + + + /** + * fetch the file from server. If the server's representation of the + * model differs from its current attributes, they will be overriden, + * @param {AuthOptions} options AuthOptions plus 'keys' and 'include' option. + * @return {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch: function fetch(options) { + var options = null; + + var request = AVRequest('files', null, this.id, 'GET', options); + return request.then(this._finishFetch.bind(this)); + }, + _finishFetch: function _finishFetch(response) { + var value = AV.Object.prototype.parse(response); + value.attributes = { + name: value.name, + url: value.url, + mime_type: value.mime_type, + bucket: value.bucket + }; + value.attributes.metaData = value.metaData || {}; + value.id = value.objectId; + // clean + delete value.objectId; + delete value.metaData; + delete value.url; + delete value.name; + delete value.mime_type; + delete value.bucket; + _.extend(this, value); + return this; + } + }; +}; \ No newline at end of file diff --git a/dist/node/geopoint.js b/dist/node/geopoint.js new file mode 100644 index 000000000..a3c8848e7 --- /dev/null +++ b/dist/node/geopoint.js @@ -0,0 +1,167 @@ +"use strict"; + +var _ = require('underscore'); + +/*global navigator: false */ +module.exports = function (AV) { + /** + * Creates a new GeoPoint with any of the following forms:
+ * @example + * new GeoPoint(otherGeoPoint) + * new GeoPoint(30, 30) + * new GeoPoint([30, 30]) + * new GeoPoint({latitude: 30, longitude: 30}) + * new GeoPoint() // defaults to (0, 0) + * @class + * + *

Represents a latitude / longitude point that may be associated + * with a key in a AVObject or used as a reference point for geo queries. + * This allows proximity-based queries on the key.

+ * + *

Only one key in a class may contain a GeoPoint.

+ * + *

Example:

+   *   var point = new AV.GeoPoint(30.0, -20.0);
+   *   var object = new AV.Object("PlaceObject");
+   *   object.set("location", point);
+   *   object.save();

+ */ + AV.GeoPoint = function (arg1, arg2) { + if (_.isArray(arg1)) { + AV.GeoPoint._validate(arg1[0], arg1[1]); + this.latitude = arg1[0]; + this.longitude = arg1[1]; + } else if (_.isObject(arg1)) { + AV.GeoPoint._validate(arg1.latitude, arg1.longitude); + this.latitude = arg1.latitude; + this.longitude = arg1.longitude; + } else if (_.isNumber(arg1) && _.isNumber(arg2)) { + AV.GeoPoint._validate(arg1, arg2); + this.latitude = arg1; + this.longitude = arg2; + } else { + this.latitude = 0; + this.longitude = 0; + } + + // Add properties so that anyone using Webkit or Mozilla will get an error + // if they try to set values that are out of bounds. + var self = this; + if (this.__defineGetter__ && this.__defineSetter__) { + // Use _latitude and _longitude to actually store the values, and add + // getters and setters for latitude and longitude. + this._latitude = this.latitude; + this._longitude = this.longitude; + this.__defineGetter__("latitude", function () { + return self._latitude; + }); + this.__defineGetter__("longitude", function () { + return self._longitude; + }); + this.__defineSetter__("latitude", function (val) { + AV.GeoPoint._validate(val, self.longitude); + self._latitude = val; + }); + this.__defineSetter__("longitude", function (val) { + AV.GeoPoint._validate(self.latitude, val); + self._longitude = val; + }); + } + }; + + /** + * @lends AV.GeoPoint.prototype + * @property {float} latitude North-south portion of the coordinate, in range + * [-90, 90]. Throws an exception if set out of range in a modern browser. + * @property {float} longitude East-west portion of the coordinate, in range + * [-180, 180]. Throws if set out of range in a modern browser. + */ + + /** + * Throws an exception if the given lat-long is out of bounds. + * @private + */ + AV.GeoPoint._validate = function (latitude, longitude) { + if (latitude < -90.0) { + throw new Error("AV.GeoPoint latitude " + latitude + " < -90.0."); + } + if (latitude > 90.0) { + throw new Error("AV.GeoPoint latitude " + latitude + " > 90.0."); + } + if (longitude < -180.0) { + throw new Error("AV.GeoPoint longitude " + longitude + " < -180.0."); + } + if (longitude > 180.0) { + throw new Error("AV.GeoPoint longitude " + longitude + " > 180.0."); + } + }; + + /** + * Creates a GeoPoint with the user's current location, if available. + * @return {Promise.} + */ + AV.GeoPoint.current = function () { + return new AV.Promise(function (resolve, reject) { + navigator.geolocation.getCurrentPosition(function (location) { + resolve(new AV.GeoPoint({ + latitude: location.coords.latitude, + longitude: location.coords.longitude + })); + }, reject); + }); + }; + + AV.GeoPoint.prototype = { + /** + * Returns a JSON representation of the GeoPoint, suitable for AV. + * @return {Object} + */ + toJSON: function toJSON() { + AV.GeoPoint._validate(this.latitude, this.longitude); + return { + "__type": "GeoPoint", + latitude: this.latitude, + longitude: this.longitude + }; + }, + + /** + * Returns the distance from this GeoPoint to another in radians. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + radiansTo: function radiansTo(point) { + var d2r = Math.PI / 180.0; + var lat1rad = this.latitude * d2r; + var long1rad = this.longitude * d2r; + var lat2rad = point.latitude * d2r; + var long2rad = point.longitude * d2r; + var deltaLat = lat1rad - lat2rad; + var deltaLong = long1rad - long2rad; + var sinDeltaLatDiv2 = Math.sin(deltaLat / 2); + var sinDeltaLongDiv2 = Math.sin(deltaLong / 2); + // Square of half the straight line chord distance between both points. + var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2; + a = Math.min(1.0, a); + return 2 * Math.asin(Math.sqrt(a)); + }, + + /** + * Returns the distance from this GeoPoint to another in kilometers. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + kilometersTo: function kilometersTo(point) { + return this.radiansTo(point) * 6371.0; + }, + + /** + * Returns the distance from this GeoPoint to another in miles. + * @param {AV.GeoPoint} point the other AV.GeoPoint. + * @return {Number} + */ + milesTo: function milesTo(point) { + return this.radiansTo(point) * 3958.8; + } + }; +}; \ No newline at end of file diff --git a/dist/node/index-weapp.js b/dist/node/index-weapp.js new file mode 100644 index 000000000..ace66cfb0 --- /dev/null +++ b/dist/node/index-weapp.js @@ -0,0 +1,5 @@ +'use strict'; + +require('weapp-polyfill/auto-polyfill'); + +module.exports = require('./index'); \ No newline at end of file diff --git a/dist/node/index.js b/dist/node/index.js new file mode 100644 index 000000000..57d914cfa --- /dev/null +++ b/dist/node/index.js @@ -0,0 +1,45 @@ +'use strict'; + +/*! + * LeanCloud JavaScript SDK + * https://leancloud.cn + * + * Copyright 2016 LeanCloud.cn, Inc. + * The LeanCloud JavaScript SDK is freely distributable under the MIT license. + */ + +var AV = require('./av'); + +AV._ = require('underscore'); +AV.version = require('./version'); +AV.Promise = require('./promise'); +AV.localStorage = require('./localstorage'); +AV.Cache = require('./cache'); +AV.Error = require('./error'); + +require('./init'); +require('./event')(AV); +require('./geopoint')(AV); +require('./acl')(AV); +require('./op')(AV); +require('./relation')(AV); +require('./file')(AV); +require('./object')(AV); +require('./role')(AV); +require('./user')(AV); +require('./query')(AV); +require('./cloudfunction')(AV); +require('./push')(AV); +require('./status')(AV); +require('./search')(AV); +require('./insight')(AV); + +module.exports = AV; + +/** + * Options to controll the authentication for an operation + * @typedef {Object} AuthOptions + * @property {String} [sessionToken] Specify a user to excute the operation as. + * @property {AV.User} [user] Specify a user to excute the operation as. The user must have _sessionToken. This option will be ignored if sessionToken option provided. + * @property {Boolean} [useMasterKey] Indicates whether masterKey is used for this operation. Only valid when masterKey is set. + */ \ No newline at end of file diff --git a/dist/node/init.js b/dist/node/init.js new file mode 100644 index 000000000..6b0e548bd --- /dev/null +++ b/dist/node/init.js @@ -0,0 +1,73 @@ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var AV = require('./av'); +var request = require('./request'); + +var initialize = function initialize(appId, appKey, masterKey, hookKey) { + if (AV.applicationId && appId !== AV.applicationId && appKey !== AV.applicationKey && masterKey !== AV.masterKey) { + console.warn('LeanCloud SDK is already initialized, please do not reinitialize it.'); + } + AV.applicationId = appId; + AV.applicationKey = appKey; + AV.masterKey = masterKey; + if (!process.env.CLIENT_PLATFORM) { + AV.hookKey = hookKey || process.env.LEANCLOUD_APP_HOOK_KEY; + } + AV._useMasterKey = false; +}; + +var masterKeyWarn = function masterKeyWarn() { + console.warn('MasterKey is not supposed to be used in browser.'); +}; + +/** + * Call this method first to set up your authentication tokens for AV. + * You can get your app keys from the LeanCloud dashboard on http://leancloud.cn . + * @function AV.init + * @param {Object} options + * @param {String} options.appId application id + * @param {String} options.appKey application key + * @param {String} options.masterKey application master key +*/ + +AV.init = function () { + if (arguments.length === 1) { + var options = arguments.length <= 0 ? undefined : arguments[0]; + if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { + if (process.env.CLIENT_PLATFORM && options.masterKey) { + masterKeyWarn(); + } + initialize(options.appId, options.appKey, options.masterKey, options.hookKey); + request.setServerUrlByRegion(options.region); + } else { + throw new Error('AV.init(): Parameter is not correct.'); + } + } else { + // 兼容旧版本的初始化方法 + if (process.env.CLIENT_PLATFORM && (arguments.length <= 3 ? undefined : arguments[3])) { + masterKeyWarn(); + } + initialize.apply(undefined, arguments); + request.setServerUrlByRegion('cn'); + } +}; + +// If we're running in node.js, allow using the master key. +if (!process.env.CLIENT_PLATFORM) { + AV.Cloud = AV.Cloud || {}; + /** + * Switches the LeanCloud SDK to using the Master key. The Master key grants + * priveleged access to the data in LeanCloud and can be used to bypass ACLs and + * other restrictions that are applied to the client SDKs. + *

Available in Cloud Code and Node.js only. + *

+ */ + AV.Cloud.useMasterKey = function () { + AV._useMasterKey = true; + }; +} + +// 兼容老版本的初始化方法 +AV.initialize = AV.init; \ No newline at end of file diff --git a/dist/node/insight.js b/dist/node/insight.js new file mode 100644 index 000000000..fc09de19c --- /dev/null +++ b/dist/node/insight.js @@ -0,0 +1,132 @@ +'use strict'; + +var _ = require('underscore'); +var AVError = require('./error'); +var AVRequest = require('./request').request; + +module.exports = function (AV) { + /** + * 包含了使用了 LeanCloud + * 离线数据分析功能的函数。 + *

+ * 仅在云引擎运行环境下有效。 + *

+ * @namespace + */ + AV.Insight = AV.Insight || {}; + + _.extend(AV.Insight, /** @lends AV.Insight */{ + + /** + * 开始一个 Insight 任务。结果里将返回 Job id,你可以拿得到的 id 使用 + * AV.Insight.JobQuery 查询任务状态和结果。 + * @param {Object} jobConfig 任务配置的 JSON 对象,例如:
+     *                   { "sql" : "select count(*) as c,gender from _User group by gender",
+     *                     "saveAs": {
+     *                         "className" : "UserGender",
+     *                         "limit": 1
+     *                      }
+     *                   }
+     *                  
+ * sql 指定任务执行的 SQL 语句, saveAs(可选) 指定将结果保存在哪张表里,limit 最大 1000。 + * @param {AuthOptions} [options] + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + startJob: function startJob(jobConfig, options) { + if (!jobConfig || !jobConfig.sql) { + throw new Error('Please provide the sql to run the job.'); + } + var data = { + jobConfig: jobConfig, + appId: AV.applicationId + }; + var request = AVRequest("bigquery", 'jobs', null, 'POST', AV._encode(data, null, true), options); + + return request.then(function (resp) { + return AV._decode(resp).id; + }); + }, + + /** + * 监听 Insight 任务事件,目前仅支持 end 事件,表示任务完成。 + *

+ * 仅在云引擎运行环境下有效。 + *

+ * @param {String} event 监听的事件,目前仅支持 'end' ,表示任务完成 + * @param {Function} 监听回调函数,接收 (err, id) 两个参数,err 表示错误信息, + * id 表示任务 id。接下来你可以拿这个 id 使用AV.Insight.JobQuery 查询任务状态和结果。 + * + */ + on: function on(event, cb) {} + }); + + /** + * 创建一个对象,用于查询 Insight 任务状态和结果。 + * @class + * @param {String} id 任务 id + * @since 0.5.5 + */ + AV.Insight.JobQuery = function (id, className) { + if (!id) { + throw new Error('Please provide the job id.'); + } + this.id = id; + this.className = className; + this._skip = 0; + this._limit = 100; + }; + + AV.Insight.JobQuery.prototype = { + + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * @param {Number} n the number of results to skip. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + skip: function skip(n) { + this._skip = n; + return this; + }, + + /** + * Sets the limit of the number of results to return. The default limit is + * 100, with a maximum of 1000 results being returned at a time. + * @param {Number} n the number of results to limit to. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + limit: function limit(n) { + this._limit = n; + return this; + }, + + /** + * 查询任务状态和结果,任务结果为一个 JSON 对象,包括 status 表示任务状态, totalCount 表示总数, + * results 数组表示任务结果数组,previewCount 表示可以返回的结果总数,任务的开始和截止时间 + * startTime、endTime 等信息。 + * + * @param {AuthOptions} [options] + * @return {Promise} A promise that will be resolved with the result + * of the function. + * + */ + find: function find(options) { + var params = { + skip: this._skip, + limit: this._limit + }; + + var request = AVRequest("bigquery", 'jobs', this.id, "GET", params, options); + var self = this; + return request.then(function (response) { + if (response.error) { + return AV.Promise.reject(new AVError(response.code, response.error)); + } + return AV.Promise.resolve(response); + }); + } + + }; +}; \ No newline at end of file diff --git a/dist/node/localstorage.js b/dist/node/localstorage.js new file mode 100644 index 000000000..c853b8601 --- /dev/null +++ b/dist/node/localstorage.js @@ -0,0 +1,30 @@ +'use strict'; + +var _ = require('underscore'); +var Promise = require('./promise'); +var localStorage = require('./utils/localstorage'); + +var syncApiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +if (!localStorage.async) { + // wrap sync apis with async ones. + _(syncApiNames).each(function (apiName) { + if (typeof localStorage[apiName] === 'function') { + localStorage[apiName + 'Async'] = function () { + return Promise.resolve(localStorage[apiName].apply(localStorage, arguments)); + }; + } + }); +} else { + _(syncApiNames).each(function (apiName) { + if (typeof localStorage[apiName] !== 'function') { + localStorage[apiName] = function () { + var error = new Error('Synchronous API [' + apiName + '] is not available in this runtime.'); + error.code = 'SYNC_API_NOT_AVAILABLE'; + throw error; + }; + } + }); +} + +module.exports = localStorage; \ No newline at end of file diff --git a/dist/node/object.js b/dist/node/object.js new file mode 100644 index 000000000..c6e35b1b5 --- /dev/null +++ b/dist/node/object.js @@ -0,0 +1,1578 @@ +'use strict'; + +var _ = require('underscore'); +var AVError = require('./error'); +var AVRequest = require('./request').request; +var utils = require('./utils'); + +var RESERVED_KEYS = ['objectId', 'createdAt', 'updatedAt']; +var checkReservedKey = function checkReservedKey(key) { + if (RESERVED_KEYS.indexOf(key) !== -1) { + throw new Error('key[' + key + '] is reserved'); + } +}; + +// AV.Object is analogous to the Java AVObject. +// It also implements the same interface as a Backbone model. + +module.exports = function (AV) { + /** + * Creates a new model with defined attributes. A client id (cid) is + * automatically generated and assigned for you. + * + *

You won't normally call this method directly. It is recommended that + * you use a subclass of AV.Object instead, created by calling + * extend.

+ * + *

However, if you don't want to use a subclass, or aren't sure which + * subclass is appropriate, you can use this form:

+   *     var object = new AV.Object("ClassName");
+   * 
+ * That is basically equivalent to:
+   *     var MyClass = AV.Object.extend("ClassName");
+   *     var object = new MyClass();
+   * 

+ * + * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @see AV.Object.extend + * + * @class + * + *

The fundamental unit of AV data, which implements the Backbone Model + * interface.

+ */ + AV.Object = function (attributes, options) { + // Allow new AV.Object("ClassName") as a shortcut to _create. + if (_.isString(attributes)) { + return AV.Object._create.apply(this, arguments); + } + + attributes = attributes || {}; + if (options && options.parse) { + attributes = this.parse(attributes); + attributes = this._mergeMagicFields(attributes); + } + var defaults = AV._getValue(this, 'defaults'); + if (defaults) { + attributes = _.extend({}, defaults, attributes); + } + if (options && options.collection) { + this.collection = options.collection; + } + + this._serverData = {}; // The last known data for this object from cloud. + this._opSetQueue = [{}]; // List of sets of changes to the data. + this._flags = {}; + this.attributes = {}; // The best estimate of this's current data. + + this._hashedJSON = {}; // Hash of values of containers at last save. + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this.set(attributes, { silent: true }); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this._hasData = true; + this._previousAttributes = _.clone(this.attributes); + this.initialize.apply(this, arguments); + }; + + /** + * @lends AV.Object.prototype + * @property {String} id The objectId of the AV Object. + */ + + /** + * Saves the given list of AV.Object. + * If any error is encountered, stops and calls the error handler. + * + *
+   *   AV.Object.saveAll([object1, object2, ...]).then(function(list) {
+   *     // All the objects were saved.
+   *   }, function(error) {
+   *     // An error occurred while saving one of the objects.
+   *   });
+   *
+   * @param {Array} list A list of AV.Object.
+   */
+  AV.Object.saveAll = function (list, options) {
+    return AV.Object._deepSaveAsync(list, null, options);
+  };
+
+  /**
+   * Fetch the given list of AV.Object.
+   *
+   * @param {AV.Object[]} objects A list of AV.Object
+   * @param {AuthOptions} options
+   * @return {Promise.} The given list of AV.Object, updated
+   */
+
+  AV.Object.fetchAll = function (objects, options) {
+    return AV.Promise.resolve().then(function () {
+      return AVRequest('batch', null, null, 'POST', {
+        requests: _.map(objects, function (object) {
+          if (!object.className) throw new Error('object must have className to fetch');
+          if (!object.id) throw new Error('object must have id to fetch');
+          if (object.dirty()) throw new Error('object is modified but not saved');
+          return {
+            method: 'GET',
+            path: '/1.1/classes/' + object.className + '/' + object.id
+          };
+        })
+      }, options);
+    }).then(function (response) {
+      _.forEach(objects, function (object, i) {
+        if (response[i].success) {
+          object._finishFetch(object.parse(response[i].success));
+        } else {
+          var error = new Error(response[i].error.error);
+          error.code = response[i].error.code;
+          throw error;
+        }
+      });
+      return objects;
+    });
+  };
+
+  // Attach all inheritable methods to the AV.Object prototype.
+  _.extend(AV.Object.prototype, AV.Events,
+  /** @lends AV.Object.prototype */{
+    _fetchWhenSave: false,
+
+    /**
+     * Initialize is an empty function by default. Override it with your own
+     * initialization logic.
+     */
+    initialize: function initialize() {},
+
+    /**
+      * Set whether to enable fetchWhenSave option when updating object.
+      * When set true, SDK would fetch the latest object after saving.
+      * Default is false.
+      *
+      * @deprecated use AV.Object#save with options.fetchWhenSave instead
+      * @param {boolean} enable  true to enable fetchWhenSave option.
+      */
+    fetchWhenSave: function fetchWhenSave(enable) {
+      console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');
+      if (!_.isBoolean(enable)) {
+        throw new Error('Expect boolean value for fetchWhenSave');
+      }
+      this._fetchWhenSave = enable;
+    },
+
+    /**
+     * Returns the object's objectId.
+     * @return {String} the objectId.
+     */
+    getObjectId: function getObjectId() {
+      return this.id;
+    },
+
+    /**
+     * Returns the object's createdAt attribute.
+     * @return {Date}
+     */
+    getCreatedAt: function getCreatedAt() {
+      return this.createdAt || this.get('createdAt');
+    },
+
+    /**
+     * Returns the object's updatedAt attribute.
+     * @return {Date}
+     */
+    getUpdatedAt: function getUpdatedAt() {
+      return this.updatedAt || this.get('updatedAt');
+    },
+
+    /**
+     * Returns a JSON version of the object suitable for saving to AV.
+     * @return {Object}
+     */
+    toJSON: function toJSON() {
+      var json = this._toFullJSON();
+      AV._arrayEach(["__type", "className"], function (key) {
+        delete json[key];
+      });
+      return json;
+    },
+
+    _toFullJSON: function _toFullJSON(seenObjects) {
+      var _this = this;
+
+      var json = _.clone(this.attributes);
+      AV._objectEach(json, function (val, key) {
+        json[key] = AV._encode(val, seenObjects);
+      });
+      AV._objectEach(this._operations, function (val, key) {
+        json[key] = val;
+      });
+
+      if (_.has(this, "id")) {
+        json.objectId = this.id;
+      }
+      _(['createdAt', 'updatedAt']).each(function (key) {
+        if (_.has(_this, key)) {
+          var val = _this[key];
+          json[key] = _.isDate(val) ? val.toJSON() : val;
+        }
+      });
+      json.__type = "Object";
+      json.className = this.className;
+      return json;
+    },
+
+    /**
+     * Updates _hashedJSON to reflect the current state of this object.
+     * Adds any changed hash values to the set of pending changes.
+     * @private
+     */
+    _refreshCache: function _refreshCache() {
+      var self = this;
+      if (self._refreshingCache) {
+        return;
+      }
+      self._refreshingCache = true;
+      AV._objectEach(this.attributes, function (value, key) {
+        if (value instanceof AV.Object) {
+          value._refreshCache();
+        } else if (_.isObject(value)) {
+          if (self._resetCacheForKey(key)) {
+            self.set(key, new AV.Op.Set(value), { silent: true });
+          }
+        }
+      });
+      delete self._refreshingCache;
+    },
+
+    /**
+     * Returns true if this object has been modified since its last
+     * save/refresh.  If an attribute is specified, it returns true only if that
+     * particular attribute has been modified since the last save/refresh.
+     * @param {String} attr An attribute name (optional).
+     * @return {Boolean}
+     */
+    dirty: function dirty(attr) {
+      this._refreshCache();
+
+      var currentChanges = _.last(this._opSetQueue);
+
+      if (attr) {
+        return currentChanges[attr] ? true : false;
+      }
+      if (!this.id) {
+        return true;
+      }
+      if (_.keys(currentChanges).length > 0) {
+        return true;
+      }
+      return false;
+    },
+
+    /**
+     * Gets a Pointer referencing this Object.
+     * @private
+     */
+    _toPointer: function _toPointer() {
+      // if (!this.id) {
+      //   throw new Error("Can't serialize an unsaved AV.Object");
+      // }
+      return { __type: "Pointer",
+        className: this.className,
+        objectId: this.id };
+    },
+
+    /**
+     * Gets the value of an attribute.
+     * @param {String} attr The string name of an attribute.
+     */
+    get: function get(attr) {
+      switch (attr) {
+        case 'objectId':
+          return this.id;
+        case 'createdAt':
+        case 'updatedAt':
+          return this[attr];
+        default:
+          return this.attributes[attr];
+      }
+    },
+
+    /**
+     * Gets a relation on the given class for the attribute.
+     * @param {String} attr The attribute to get the relation for.
+     * @return {AV.Relation}
+     */
+    relation: function relation(attr) {
+      var value = this.get(attr);
+      if (value) {
+        if (!(value instanceof AV.Relation)) {
+          throw new Error("Called relation() on non-relation field " + attr);
+        }
+        value._ensureParentAndKey(this, attr);
+        return value;
+      } else {
+        return new AV.Relation(this, attr);
+      }
+    },
+
+    /**
+     * Gets the HTML-escaped value of an attribute.
+     */
+    escape: function escape(attr) {
+      var html = this._escapedAttributes[attr];
+      if (html) {
+        return html;
+      }
+      var val = this.attributes[attr];
+      var escaped;
+      if (utils.isNullOrUndefined(val)) {
+        escaped = '';
+      } else {
+        escaped = _.escape(val.toString());
+      }
+      this._escapedAttributes[attr] = escaped;
+      return escaped;
+    },
+
+    /**
+     * Returns true if the attribute contains a value that is not
+     * null or undefined.
+     * @param {String} attr The string name of the attribute.
+     * @return {Boolean}
+     */
+    has: function has(attr) {
+      return !utils.isNullOrUndefined(this.attributes[attr]);
+    },
+
+    /**
+     * Pulls "special" fields like objectId, createdAt, etc. out of attrs
+     * and puts them on "this" directly.  Removes them from attrs.
+     * @param attrs - A dictionary with the data for this AV.Object.
+     * @private
+     */
+    _mergeMagicFields: function _mergeMagicFields(attrs) {
+      // Check for changes of magic fields.
+      var model = this;
+      var specialFields = ["objectId", "createdAt", "updatedAt"];
+      AV._arrayEach(specialFields, function (attr) {
+        if (attrs[attr]) {
+          if (attr === "objectId") {
+            model.id = attrs[attr];
+          } else if ((attr === "createdAt" || attr === "updatedAt") && !_.isDate(attrs[attr])) {
+            model[attr] = AV._parseDate(attrs[attr]);
+          } else {
+            model[attr] = attrs[attr];
+          }
+          delete attrs[attr];
+        }
+      });
+      return attrs;
+    },
+
+    /**
+     * Returns the json to be sent to the server.
+     * @private
+     */
+    _startSave: function _startSave() {
+      this._opSetQueue.push({});
+    },
+
+    /**
+     * Called when a save fails because of an error. Any changes that were part
+     * of the save need to be merged with changes made after the save. This
+     * might throw an exception is you do conflicting operations. For example,
+     * if you do:
+     *   object.set("foo", "bar");
+     *   object.set("invalid field name", "baz");
+     *   object.save();
+     *   object.increment("foo");
+     * then this will throw when the save fails and the client tries to merge
+     * "bar" with the +1.
+     * @private
+     */
+    _cancelSave: function _cancelSave() {
+      var self = this;
+      var failedChanges = _.first(this._opSetQueue);
+      this._opSetQueue = _.rest(this._opSetQueue);
+      var nextChanges = _.first(this._opSetQueue);
+      AV._objectEach(failedChanges, function (op, key) {
+        var op1 = failedChanges[key];
+        var op2 = nextChanges[key];
+        if (op1 && op2) {
+          nextChanges[key] = op2._mergeWithPrevious(op1);
+        } else if (op1) {
+          nextChanges[key] = op1;
+        }
+      });
+      this._saving = this._saving - 1;
+    },
+
+    /**
+     * Called when a save completes successfully. This merges the changes that
+     * were saved into the known server data, and overrides it with any data
+     * sent directly from the server.
+     * @private
+     */
+    _finishSave: function _finishSave(serverData) {
+      // Grab a copy of any object referenced by this object. These instances
+      // may have already been fetched, and we don't want to lose their data.
+      // Note that doing it like this means we will unify separate copies of the
+      // same object, but that's a risk we have to take.
+      var fetchedObjects = {};
+      AV._traverse(this.attributes, function (object) {
+        if (object instanceof AV.Object && object.id && object._hasData) {
+          fetchedObjects[object.id] = object;
+        }
+      });
+
+      var savedChanges = _.first(this._opSetQueue);
+      this._opSetQueue = _.rest(this._opSetQueue);
+      this._applyOpSet(savedChanges, this._serverData);
+      this._mergeMagicFields(serverData);
+      var self = this;
+      AV._objectEach(serverData, function (value, key) {
+        self._serverData[key] = AV._decode(value, key);
+
+        // Look for any objects that might have become unfetched and fix them
+        // by replacing their values with the previously observed values.
+        var fetched = AV._traverse(self._serverData[key], function (object) {
+          if (object instanceof AV.Object && fetchedObjects[object.id]) {
+            return fetchedObjects[object.id];
+          }
+        });
+        if (fetched) {
+          self._serverData[key] = fetched;
+        }
+      });
+      this._rebuildAllEstimatedData();
+      this._saving = this._saving - 1;
+    },
+
+    /**
+     * Called when a fetch or login is complete to set the known server data to
+     * the given object.
+     * @private
+     */
+    _finishFetch: function _finishFetch(serverData, hasData) {
+      // Clear out any changes the user might have made previously.
+      this._opSetQueue = [{}];
+
+      // Bring in all the new server data.
+      this._mergeMagicFields(serverData);
+      var self = this;
+      AV._objectEach(serverData, function (value, key) {
+        self._serverData[key] = AV._decode(value, key);
+      });
+
+      // Refresh the attributes.
+      this._rebuildAllEstimatedData();
+
+      // Clear out the cache of mutable containers.
+      this._refreshCache();
+      this._opSetQueue = [{}];
+
+      this._hasData = hasData;
+    },
+
+    /**
+     * Applies the set of AV.Op in opSet to the object target.
+     * @private
+     */
+    _applyOpSet: function _applyOpSet(opSet, target) {
+      var self = this;
+      AV._objectEach(opSet, function (change, key) {
+        target[key] = change._estimate(target[key], self, key);
+        if (target[key] === AV.Op._UNSET) {
+          delete target[key];
+        }
+      });
+    },
+
+    /**
+     * Replaces the cached value for key with the current value.
+     * Returns true if the new value is different than the old value.
+     * @private
+     */
+    _resetCacheForKey: function _resetCacheForKey(key) {
+      var value = this.attributes[key];
+      if (_.isObject(value) && !(value instanceof AV.Object) && !(value instanceof AV.File)) {
+
+        value = value.toJSON ? value.toJSON() : value;
+        var json = JSON.stringify(value);
+        if (this._hashedJSON[key] !== json) {
+          var wasSet = !!this._hashedJSON[key];
+          this._hashedJSON[key] = json;
+          return wasSet;
+        }
+      }
+      return false;
+    },
+
+    /**
+     * Populates attributes[key] by starting with the last known data from the
+     * server, and applying all of the local changes that have been made to that
+     * key since then.
+     * @private
+     */
+    _rebuildEstimatedDataForKey: function _rebuildEstimatedDataForKey(key) {
+      var self = this;
+      delete this.attributes[key];
+      if (this._serverData[key]) {
+        this.attributes[key] = this._serverData[key];
+      }
+      AV._arrayEach(this._opSetQueue, function (opSet) {
+        var op = opSet[key];
+        if (op) {
+          self.attributes[key] = op._estimate(self.attributes[key], self, key);
+          if (self.attributes[key] === AV.Op._UNSET) {
+            delete self.attributes[key];
+          } else {
+            self._resetCacheForKey(key);
+          }
+        }
+      });
+    },
+
+    /**
+     * Populates attributes by starting with the last known data from the
+     * server, and applying all of the local changes that have been made since
+     * then.
+     * @private
+     */
+    _rebuildAllEstimatedData: function _rebuildAllEstimatedData() {
+      var self = this;
+
+      var previousAttributes = _.clone(this.attributes);
+
+      this.attributes = _.clone(this._serverData);
+      AV._arrayEach(this._opSetQueue, function (opSet) {
+        self._applyOpSet(opSet, self.attributes);
+        AV._objectEach(opSet, function (op, key) {
+          self._resetCacheForKey(key);
+        });
+      });
+
+      // Trigger change events for anything that changed because of the fetch.
+      AV._objectEach(previousAttributes, function (oldValue, key) {
+        if (self.attributes[key] !== oldValue) {
+          self.trigger('change:' + key, self, self.attributes[key], {});
+        }
+      });
+      AV._objectEach(this.attributes, function (newValue, key) {
+        if (!_.has(previousAttributes, key)) {
+          self.trigger('change:' + key, self, newValue, {});
+        }
+      });
+    },
+
+    /**
+     * Sets a hash of model attributes on the object, firing
+     * "change" unless you choose to silence it.
+     *
+     * 

You can call it with an object containing keys and values, or with one + * key and value. For example:

+     *   gameTurn.set({
+     *     player: player1,
+     *     diceRoll: 2
+     *   }, {
+     *     error: function(gameTurnAgain, error) {
+     *       // The set failed validation.
+     *     }
+     *   });
+     *
+     *   game.set("currentPlayer", player2, {
+     *     error: function(gameTurnAgain, error) {
+     *       // The set failed validation.
+     *     }
+     *   });
+     *
+     *   game.set("finished", true);

+ * + * @param {String} key The key to set. + * @param {Any} value The value to give it. + * @param {Object} [options] + * @param {Boolean} [options.silent] + * @return {AV.Object} self if succeeded, throws if the value is not valid. + * @see AV.Object#validate + */ + set: function set(key, value, options) { + var attrs; + if (_.isObject(key) || utils.isNullOrUndefined(key)) { + attrs = _.mapObject(key, function (v, k) { + checkReservedKey(k); + return AV._decode(v, k); + }); + options = value; + } else { + attrs = {}; + checkReservedKey(key); + attrs[key] = AV._decode(value, key); + } + + // Extract attributes and options. + options = options || {}; + if (!attrs) { + return this; + } + if (attrs instanceof AV.Object) { + attrs = attrs.attributes; + } + + // If the unset option is used, every attribute should be a Unset. + if (options.unset) { + AV._objectEach(attrs, function (unused_value, key) { + attrs[key] = new AV.Op.Unset(); + }); + } + + // Apply all the attributes to get the estimated values. + var dataToValidate = _.clone(attrs); + var self = this; + AV._objectEach(dataToValidate, function (value, key) { + if (value instanceof AV.Op) { + dataToValidate[key] = value._estimate(self.attributes[key], self, key); + if (dataToValidate[key] === AV.Op._UNSET) { + delete dataToValidate[key]; + } + } + }); + + // Run validation. + this._validate(attrs, options); + + options.changes = {}; + var escaped = this._escapedAttributes; + var prev = this._previousAttributes || {}; + + // Update attributes. + AV._arrayEach(_.keys(attrs), function (attr) { + var val = attrs[attr]; + + // If this is a relation object we need to set the parent correctly, + // since the location where it was parsed does not have access to + // this object. + if (val instanceof AV.Relation) { + val.parent = self; + } + + if (!(val instanceof AV.Op)) { + val = new AV.Op.Set(val); + } + + // See if this change will actually have any effect. + var isRealChange = true; + if (val instanceof AV.Op.Set && _.isEqual(self.attributes[attr], val.value)) { + isRealChange = false; + } + + if (isRealChange) { + delete escaped[attr]; + if (options.silent) { + self._silent[attr] = true; + } else { + options.changes[attr] = true; + } + } + + var currentChanges = _.last(self._opSetQueue); + currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]); + self._rebuildEstimatedDataForKey(attr); + + if (isRealChange) { + self.changed[attr] = self.attributes[attr]; + if (!options.silent) { + self._pending[attr] = true; + } + } else { + delete self.changed[attr]; + delete self._pending[attr]; + } + }); + + if (!options.silent) { + this.change(options); + } + return this; + }, + + /** + * Remove an attribute from the model, firing "change" unless + * you choose to silence it. This is a noop if the attribute doesn't + * exist. + */ + unset: function unset(attr, options) { + options = options || {}; + options.unset = true; + return this.set(attr, null, options); + }, + + /** + * Atomically increments the value of the given attribute the next time the + * object is saved. If no amount is specified, 1 is used by default. + * + * @param attr {String} The key. + * @param amount {Number} The amount to increment by. + */ + increment: function increment(attr, amount) { + if (_.isUndefined(amount) || _.isNull(amount)) { + amount = 1; + } + return this.set(attr, new AV.Op.Increment(amount)); + }, + + /** + * Atomically add an object to the end of the array associated with a given + * key. + * @param attr {String} The key. + * @param item {} The item to add. + */ + add: function add(attr, item) { + return this.set(attr, new AV.Op.Add(utils.ensureArray(item))); + }, + + /** + * Atomically add an object to the array associated with a given key, only + * if it is not already present in the array. The position of the insert is + * not guaranteed. + * + * @param attr {String} The key. + * @param item {} The object to add. + */ + addUnique: function addUnique(attr, item) { + return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item))); + }, + + /** + * Atomically remove all instances of an object from the array associated + * with a given key. + * + * @param attr {String} The key. + * @param item {} The object to remove. + */ + remove: function remove(attr, item) { + return this.set(attr, new AV.Op.Remove(utils.ensureArray(item))); + }, + + /** + * Returns an instance of a subclass of AV.Op describing what kind of + * modification has been performed on this field since the last time it was + * saved. For example, after calling object.increment("x"), calling + * object.op("x") would return an instance of AV.Op.Increment. + * + * @param attr {String} The key. + * @returns {AV.Op} The operation, or undefined if none. + */ + op: function op(attr) { + return _.last(this._opSetQueue)[attr]; + }, + + /** + * Clear all attributes on the model, firing "change" unless + * you choose to silence it. + */ + clear: function clear(options) { + options = options || {}; + options.unset = true; + var keysToClear = _.extend(this.attributes, this._operations); + return this.set(keysToClear, options); + }, + + /** + * Returns a JSON-encoded set of operations to be sent with the next save + * request. + * @private + */ + _getSaveJSON: function _getSaveJSON() { + var json = _.clone(_.first(this._opSetQueue)); + AV._objectEach(json, function (op, key) { + json[key] = op.toJSON(); + }); + return json; + }, + + /** + * Returns true if this object can be serialized for saving. + * @private + */ + _canBeSerialized: function _canBeSerialized() { + return AV.Object._canBeSerializedAsValue(this.attributes); + }, + + /** + * Fetch the model from the server. If the server's representation of the + * model differs from its current attributes, they will be overriden, + * triggering a "change" event. + * @param {Object} fetchOptions Optional options to set 'keys' and + * 'include' option. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the fetch + * completes. + */ + fetch: function fetch() { + var fetchOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var options = arguments[1]; + + if (_.isArray(fetchOptions.keys)) { + fetchOptions.keys = fetchOptions.keys.join(','); + } + if (_.isArray(fetchOptions.include)) { + fetchOptions.include = fetchOptions.include.join(','); + } + + var self = this; + var request = AVRequest('classes', this.className, this.id, 'GET', fetchOptions, options); + return request.then(function (response) { + self._finishFetch(self.parse(response), true); + return self; + }); + }, + + /** + * Set a hash of model attributes, and save the model to the server. + * updatedAt will be updated when the request returns. + * You can either call it as:
+     *   object.save();
+ * or
+     *   object.save(null, options);
+ * or
+     *   object.save(attrs, options);
+ * or
+     *   object.save(key, value, options);
+ * + * For example,
+     *   gameTurn.save({
+     *     player: "Jake Cutter",
+     *     diceRoll: 2
+     *   }).then(function(gameTurnAgain) {
+     *     // The save was successful.
+     *   }, function(error) {
+     *     // The save failed.  Error is an instance of AVError.
+     *   });
+ * @param {AuthOptions} options AuthOptions plus: + * @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded + * @param {AV.Query} options.query Save object only when it matches the query + * @return {AV.Promise} A promise that is fulfilled when the save + * completes. + * @see AVError + */ + save: function save(arg1, arg2, arg3) { + var i, attrs, current, options, saved; + if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) { + attrs = arg1; + options = arg2; + } else { + attrs = {}; + attrs[arg1] = arg2; + options = arg3; + } + + options = _.clone(options) || {}; + if (options.wait) { + current = _.clone(this.attributes); + } + + var setOptions = _.clone(options) || {}; + if (setOptions.wait) { + setOptions.silent = true; + } + if (attrs) { + this.set(attrs, setOptions); + } + + var model = this; + + // If there is any unsaved child, save it first. + model._refreshCache(); + + var unsavedChildren = []; + var unsavedFiles = []; + AV.Object._findUnsavedChildren(model.attributes, unsavedChildren, unsavedFiles); + if (unsavedChildren.length + unsavedFiles.length > 0) { + return AV.Object._deepSaveAsync(this.attributes, model, options).then(function () { + return model.save(null, options); + }); + } + + this._startSave(); + this._saving = (this._saving || 0) + 1; + + this._allPreviousSaves = this._allPreviousSaves || AV.Promise.resolve(); + this._allPreviousSaves = this._allPreviousSaves.catch(function (e) {}).then(function () { + var method = model.id ? 'PUT' : 'POST'; + + var json = model._getSaveJSON(); + + if (model._fetchWhenSave) { + //Sepcial-case fetchWhenSave when updating object. + json._fetchWhenSave = true; + } + + if (options.fetchWhenSave) { + json._fetchWhenSave = true; + } + if (options.query) { + var queryJSON; + if (typeof options.query.toJSON === 'function') { + queryJSON = options.query.toJSON(); + if (queryJSON) { + json._where = queryJSON.where; + } + } + if (!json._where) { + var error = new Error('options.query is not an AV.Query'); + throw error; + } + } + + _.extend(json, model._flags); + + var route = "classes"; + var className = model.className; + if (model.className === "_User" && !model.id) { + // Special-case user sign-up. + route = "users"; + className = null; + } + //hook makeRequest in options. + var makeRequest = options._makeRequest || AVRequest; + var request = makeRequest(route, className, model.id, method, json, options); + + request = request.then(function (resp) { + var serverAttrs = model.parse(resp); + if (options.wait) { + serverAttrs = _.extend(attrs || {}, serverAttrs); + } + model._finishSave(serverAttrs); + if (options.wait) { + model.set(current, setOptions); + } + return model; + }, function (error) { + model._cancelSave(); + throw error; + }); + + return request; + }); + return this._allPreviousSaves; + }, + + /** + * Destroy this model on the server if it was already persisted. + * Optimistically removes the model from its collection, if it has one. + * @param {AuthOptions} options AuthOptions plus: + * @param {Boolean} [options.wait] wait for the server to respond + * before removal. + * + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + options = options || {}; + var model = this; + + var triggerDestroy = function triggerDestroy() { + model.trigger('destroy', model, model.collection, options); + }; + + if (!this.id) { + return triggerDestroy(); + } + + if (!options.wait) { + triggerDestroy(); + } + + var request = AVRequest('classes', this.className, this.id, 'DELETE', this._flags, options); + return request.then(function () { + if (options.wait) { + triggerDestroy(); + } + return model; + }); + }, + + /** + * Converts a response into the hash of attributes to be set on the model. + * @ignore + */ + parse: function parse(resp) { + var output = _.clone(resp); + _(["createdAt", "updatedAt"]).each(function (key) { + if (output[key]) { + output[key] = AV._parseDate(output[key]); + } + }); + if (!output.updatedAt) { + output.updatedAt = output.createdAt; + } + return output; + }, + + /** + * Creates a new model with identical attributes to this one. + * @return {AV.Object} + */ + clone: function clone() { + return new this.constructor(this.attributes); + }, + + /** + * Returns true if this object has never been saved to AV. + * @return {Boolean} + */ + isNew: function isNew() { + return !this.id; + }, + + /** + * Call this method to manually fire a `"change"` event for this model and + * a `"change:attribute"` event for each changed attribute. + * Calling this will cause all objects observing the model to update. + */ + change: function change(options) { + options = options || {}; + var changing = this._changing; + this._changing = true; + + // Silent changes become pending changes. + var self = this; + AV._objectEach(this._silent, function (attr) { + self._pending[attr] = true; + }); + + // Silent changes are triggered. + var changes = _.extend({}, options.changes, this._silent); + this._silent = {}; + AV._objectEach(changes, function (unused_value, attr) { + self.trigger('change:' + attr, self, self.get(attr), options); + }); + if (changing) { + return this; + } + + // This is to get around lint not letting us make a function in a loop. + var deleteChanged = function deleteChanged(value, attr) { + if (!self._pending[attr] && !self._silent[attr]) { + delete self.changed[attr]; + } + }; + + // Continue firing `"change"` events while there are pending changes. + while (!_.isEmpty(this._pending)) { + this._pending = {}; + this.trigger('change', this, options); + // Pending and silent changes still remain. + AV._objectEach(this.changed, deleteChanged); + self._previousAttributes = _.clone(this.attributes); + } + + this._changing = false; + return this; + }, + + /** + * Determine if the model has changed since the last "change" + * event. If you specify an attribute name, determine if that attribute + * has changed. + * @param {String} attr Optional attribute name + * @return {Boolean} + */ + hasChanged: function hasChanged(attr) { + if (!arguments.length) { + return !_.isEmpty(this.changed); + } + return this.changed && _.has(this.changed, attr); + }, + + /** + * Returns an object containing all the attributes that have changed, or + * false if there are no changed attributes. Useful for determining what + * parts of a view need to be updated and/or what attributes need to be + * persisted to the server. Unset attributes will be set to undefined. + * You can also pass an attributes object to diff against the model, + * determining if there *would be* a change. + */ + changedAttributes: function changedAttributes(diff) { + if (!diff) { + return this.hasChanged() ? _.clone(this.changed) : false; + } + var changed = {}; + var old = this._previousAttributes; + AV._objectEach(diff, function (diffVal, attr) { + if (!_.isEqual(old[attr], diffVal)) { + changed[attr] = diffVal; + } + }); + return changed; + }, + + /** + * Gets the previous value of an attribute, recorded at the time the last + * "change" event was fired. + * @param {String} attr Name of the attribute to get. + */ + previous: function previous(attr) { + if (!arguments.length || !this._previousAttributes) { + return null; + } + return this._previousAttributes[attr]; + }, + + /** + * Gets all of the attributes of the model at the time of the previous + * "change" event. + * @return {Object} + */ + previousAttributes: function previousAttributes() { + return _.clone(this._previousAttributes); + }, + + /** + * Checks if the model is currently in a valid state. It's only possible to + * get into an *invalid* state if you're using silent changes. + * @return {Boolean} + */ + isValid: function isValid() { + try { + this.validate(this.attributes); + } catch (error) { + return false; + } + return true; + }, + + /** + * You should not call this function directly unless you subclass + * AV.Object, in which case you can override this method + * to provide additional validation on set and + * save. Your implementation should throw an Error if + * the attrs is invalid + * + * @param {Object} attrs The current data to validate. + * @see AV.Object#set + */ + validate: function validate(attrs) { + if (_.has(attrs, "ACL") && !(attrs.ACL instanceof AV.ACL)) { + throw new AVError(AVError.OTHER_CAUSE, "ACL must be a AV.ACL."); + } + }, + + /** + * Run validation against a set of incoming attributes, returning `true` + * if all is well. If a specific `error` callback has been passed, + * call that instead of firing the general `"error"` event. + * @private + */ + _validate: function _validate(attrs, options) { + if (options.silent || !this.validate) { + return; + } + attrs = _.extend({}, this.attributes, attrs); + this.validate(attrs); + }, + + /** + * Returns the ACL for this object. + * @returns {AV.ACL} An instance of AV.ACL. + * @see AV.Object#get + */ + getACL: function getACL() { + return this.get("ACL"); + }, + + /** + * Sets the ACL to be used for this object. + * @param {AV.ACL} acl An instance of AV.ACL. + * @param {Object} options Optional Backbone-like options object to be + * passed in to set. + * @return {Boolean} Whether the set passed validation. + * @see AV.Object#set + */ + setACL: function setACL(acl, options) { + return this.set("ACL", acl, options); + }, + + disableBeforeHook: function disableBeforeHook() { + this.ignoreHook('beforeSave'); + this.ignoreHook('beforeUpdate'); + this.ignoreHook('beforeDelete'); + }, + + disableAfterHook: function disableAfterHook() { + this.ignoreHook('afterSave'); + this.ignoreHook('afterUpdate'); + this.ignoreHook('afterDelete'); + }, + + ignoreHook: function ignoreHook(hookName) { + if (!_.contains(['beforeSave', 'afterSave', 'beforeUpdate', 'afterUpdate', 'beforeDelete', 'afterDelete'], hookName)) { + console.trace('Unsupported hookName: ' + hookName); + } + + if (!AV.hookKey) { + console.trace('ignoreHook required hookKey'); + } + + if (!this._flags.__ignore_hooks) { + this._flags.__ignore_hooks = []; + } + + this._flags.__ignore_hooks.push(hookName); + } + }); + + /** + * Creates an instance of a subclass of AV.Object for the give classname + * and id. + * @param {String} className The name of the AV class backing this model. + * @param {String} id The object id of this model. + * @return {AV.Object} A new subclass instance of AV.Object. + */ + AV.Object.createWithoutData = function (className, id, hasData) { + var result = AV.Object._create(className, undefined, undefined, /* noDefaultACL*/true); + result.id = id; + result._hasData = hasData; + return result; + }; + /** + * Delete objects in batch. + * @param {AV.Object[]} objects The AV.Object array to be deleted. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the save + * completes. + */ + AV.Object.destroyAll = function (objects) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!objects || objects.length === 0) { + return AV.Promise.resolve(); + } + var objectsByClassNameAndFlags = _.groupBy(objects, function (object) { + return JSON.stringify({ + className: object.className, + flags: object._flags + }); + }); + var body = { + requests: _.map(objectsByClassNameAndFlags, function (objects) { + var ids = _.map(objects, 'id').join(','); + return { + method: 'DELETE', + path: '/1.1/classes/' + objects[0].className + '/' + ids, + body: objects[0]._flags + }; + }) + }; + return AVRequest('batch', null, null, 'POST', body, options); + }; + + /** + * Returns the appropriate subclass for making new instances of the given + * className string. + * @private + */ + AV.Object._getSubclass = function (className) { + if (!_.isString(className)) { + throw new Error('AV.Object._getSubclass requires a string argument.'); + } + var ObjectClass = AV.Object._classMap[className]; + if (!ObjectClass) { + ObjectClass = AV.Object.extend(className); + AV.Object._classMap[className] = ObjectClass; + } + return ObjectClass; + }; + + /** + * Creates an instance of a subclass of AV.Object for the given classname. + * @private + */ + AV.Object._create = function (className, attributes, options, noDefaultACL) { + var ObjectClass = AV.Object._getSubclass(className); + return new ObjectClass(attributes, options, noDefaultACL); + }; + + // Set up a map of className to class so that we can create new instances of + // AV Objects from JSON automatically. + AV.Object._classMap = {}; + + AV.Object._extend = AV._extend; + + /** + * Creates a new model with defined attributes, + * It's the same with + *
+   *   new AV.Object(attributes, options);
+   *  
+ * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @return {AV.Object} + * @since v0.4.4 + * @see AV.Object + * @see AV.Object.extend + */ + AV.Object['new'] = function (attributes, options) { + return new AV.Object(attributes, options); + }; + + /** + * Creates a new subclass of AV.Object for the given AV class name. + * + *

Every extension of a AV class will inherit from the most recent + * previous extension of that class. When a AV.Object is automatically + * created by parsing JSON, it will use the most recent extension of that + * class.

+ * + *

You should call either:

+   *     var MyClass = AV.Object.extend("MyClass", {
+   *         Instance properties
+   *     }, {
+   *         Class properties
+   *     });
+ * or, for Backbone compatibility:
+   *     var MyClass = AV.Object.extend({
+   *         className: "MyClass",
+   *         Other instance properties
+   *     }, {
+   *         Class properties
+   *     });

+ * + * @param {String} className The name of the AV class backing this model. + * @param {Object} protoProps Instance properties to add to instances of the + * class returned from this method. + * @param {Object} classProps Class properties to add the class returned from + * this method. + * @return {Class} A new subclass of AV.Object. + */ + AV.Object.extend = function (className, protoProps, classProps) { + // Handle the case with only two args. + if (!_.isString(className)) { + if (className && _.has(className, "className")) { + return AV.Object.extend(className.className, className, protoProps); + } else { + throw new Error("AV.Object.extend's first argument should be the className."); + } + } + + // If someone tries to subclass "User", coerce it to the right type. + if (className === "User") { + className = "_User"; + } + + var NewClassObject = null; + if (_.has(AV.Object._classMap, className)) { + var OldClassObject = AV.Object._classMap[className]; + // This new subclass has been told to extend both from "this" and from + // OldClassObject. This is multiple inheritance, which isn't supported. + // For now, let's just pick one. + if (protoProps || classProps) { + NewClassObject = OldClassObject._extend(protoProps, classProps); + } else { + return OldClassObject; + } + } else { + protoProps = protoProps || {}; + protoProps._className = className; + NewClassObject = this._extend(protoProps, classProps); + } + // Extending a subclass should reuse the classname automatically. + NewClassObject.extend = function (arg0) { + if (_.isString(arg0) || arg0 && _.has(arg0, "className")) { + return AV.Object.extend.apply(NewClassObject, arguments); + } + var newArguments = [className].concat(_.toArray(arguments)); + return AV.Object.extend.apply(NewClassObject, newArguments); + }; + NewClassObject['new'] = function (attributes, options) { + return new NewClassObject(attributes, options); + }; + AV.Object._classMap[className] = NewClassObject; + return NewClassObject; + }; + + // ES6 class syntax support + Object.defineProperty(AV.Object.prototype, 'className', { + get: function get() { + var className = this._className || this.constructor._LCClassName || this.constructor.name; + // If someone tries to subclass "User", coerce it to the right type. + if (className === "User") { + return "_User"; + } + return className; + } + }); + + /** + * Register a class. + * If a subclass of AV.Object is defined with your own implement + * rather then AV.Object.extend, the subclass must be registered. + * @param {Function} klass A subclass of AV.Object + * @param {String} [name] Specify the name of the class. Useful when the class might be uglified. + * @example + * class Person extend AV.Object {} + * AV.Object.register(Person); + */ + AV.Object.register = function (klass, name) { + if (!(klass.prototype instanceof AV.Object)) { + throw new Error('registered class is not a subclass of AV.Object'); + } + var className = name || klass.name; + if (!className.length) { + throw new Error('registered class must be named'); + } + if (name) { + klass._LCClassName = name; + } + AV.Object._classMap[className] = klass; + }; + + AV.Object._findUnsavedChildren = function (object, children, files) { + AV._traverse(object, function (object) { + if (object instanceof AV.Object) { + object._refreshCache(); + if (object.dirty()) { + children.push(object); + } + return; + } + + if (object instanceof AV.File) { + if (!object.url() && !object.id) { + files.push(object); + } + return; + } + }); + }; + + AV.Object._canBeSerializedAsValue = function (object) { + var canBeSerializedAsValue = true; + + if (object instanceof AV.Object || object instanceof AV.File) { + canBeSerializedAsValue = !!object.id; + } else if (_.isArray(object)) { + AV._arrayEach(object, function (child) { + if (!AV.Object._canBeSerializedAsValue(child)) { + canBeSerializedAsValue = false; + } + }); + } else if (_.isObject(object)) { + AV._objectEach(object, function (child) { + if (!AV.Object._canBeSerializedAsValue(child)) { + canBeSerializedAsValue = false; + } + }); + } + + return canBeSerializedAsValue; + }; + + AV.Object._deepSaveAsync = function (object, model, options) { + var unsavedChildren = []; + var unsavedFiles = []; + AV.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles); + if (model) { + unsavedChildren = _.filter(unsavedChildren, function (object) { + return object != model; + }); + } + + var promise = AV.Promise.resolve(); + _.each(unsavedFiles, function (file) { + promise = promise.then(function () { + return file.save(); + }); + }); + + var objects = _.uniq(unsavedChildren); + var remaining = _.uniq(objects); + + return promise.then(function () { + return AV.Promise._continueWhile(function () { + return remaining.length > 0; + }, function () { + + // Gather up all the objects that can be saved in this batch. + var batch = []; + var newRemaining = []; + AV._arrayEach(remaining, function (object) { + // Limit batches to 20 objects. + if (batch.length > 20) { + newRemaining.push(object); + return; + } + + if (object._canBeSerialized()) { + batch.push(object); + } else { + newRemaining.push(object); + } + }); + remaining = newRemaining; + + // If we can't save any objects, there must be a circular reference. + if (batch.length === 0) { + return AV.Promise.reject(new AVError(AVError.OTHER_CAUSE, "Tried to save a batch with a cycle.")); + } + + // Reserve a spot in every object's save queue. + var readyToStart = AV.Promise.resolve(_.map(batch, function (object) { + return object._allPreviousSaves || AV.Promise.resolve(); + })); + + // Save a single batch, whether previous saves succeeded or failed. + var bathSavePromise = readyToStart.then(function () { + return AVRequest("batch", null, null, "POST", { + requests: _.map(batch, function (object) { + var json = object._getSaveJSON(); + _.extend(json, object._flags); + var method = "POST"; + + var path = "/1.1/classes/" + object.className; + if (object.id) { + path = path + "/" + object.id; + method = "PUT"; + } + + object._startSave(); + + return { + method: method, + path: path, + body: json + }; + }) + + }, options).then(function (response) { + var error; + AV._arrayEach(batch, function (object, i) { + if (response[i].success) { + object._finishSave(object.parse(response[i].success)); + } else { + error = error || response[i].error; + object._cancelSave(); + } + }); + if (error) { + return AV.Promise.reject(new AVError(error.code, error.error)); + } + }); + }); + AV._arrayEach(batch, function (object) { + object._allPreviousSaves = bathSavePromise; + }); + return bathSavePromise; + }); + }).then(function () { + return object; + }); + }; +}; \ No newline at end of file diff --git a/dist/node/op.js b/dist/node/op.js new file mode 100644 index 000000000..21f06a0ec --- /dev/null +++ b/dist/node/op.js @@ -0,0 +1,533 @@ +"use strict"; + +var _ = require('underscore'); + +module.exports = function (AV) { + + /** + * @private + * @class + * A AV.Op is an atomic operation that can be applied to a field in a + * AV.Object. For example, calling object.set("foo", "bar") + * is an example of a AV.Op.Set. Calling object.unset("foo") + * is a AV.Op.Unset. These operations are stored in a AV.Object and + * sent to the server as part of object.save() operations. + * Instances of AV.Op should be immutable. + * + * You should not create subclasses of AV.Op or instantiate AV.Op + * directly. + */ + AV.Op = function () { + this._initialize.apply(this, arguments); + }; + + AV.Op.prototype = { + _initialize: function _initialize() {} + }; + + _.extend(AV.Op, { + /** + * To create a new Op, call AV.Op._extend(); + * @private + */ + _extend: AV._extend, + + // A map of __op string to decoder function. + _opDecoderMap: {}, + + /** + * Registers a function to convert a json object with an __op field into an + * instance of a subclass of AV.Op. + * @private + */ + _registerDecoder: function _registerDecoder(opName, decoder) { + AV.Op._opDecoderMap[opName] = decoder; + }, + + /** + * Converts a json object into an instance of a subclass of AV.Op. + * @private + */ + _decode: function _decode(json) { + var decoder = AV.Op._opDecoderMap[json.__op]; + if (decoder) { + return decoder(json); + } else { + return undefined; + } + } + }); + + /* + * Add a handler for Batch ops. + */ + AV.Op._registerDecoder("Batch", function (json) { + var op = null; + AV._arrayEach(json.ops, function (nextOp) { + nextOp = AV.Op._decode(nextOp); + op = nextOp._mergeWithPrevious(op); + }); + return op; + }); + + /** + * @private + * @class + * A Set operation indicates that either the field was changed using + * AV.Object.set, or it is a mutable container that was detected as being + * changed. + */ + AV.Op.Set = AV.Op._extend( /** @lends AV.Op.Set.prototype */{ + _initialize: function _initialize(value) { + this._value = value; + }, + + /** + * Returns the new value of this field after the set. + */ + value: function value() { + return this._value; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return AV._encode(this.value()); + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + return this; + }, + + _estimate: function _estimate(oldValue) { + return this.value(); + } + }); + + /** + * A sentinel value that is returned by AV.Op.Unset._estimate to + * indicate the field should be deleted. Basically, if you find _UNSET as a + * value in your object, you should remove that key. + */ + AV.Op._UNSET = {}; + + /** + * @private + * @class + * An Unset operation indicates that this field has been deleted from the + * object. + */ + AV.Op.Unset = AV.Op._extend( /** @lends AV.Op.Unset.prototype */{ + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Delete" }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + return this; + }, + + _estimate: function _estimate(oldValue) { + return AV.Op._UNSET; + } + }); + + AV.Op._registerDecoder("Delete", function (json) { + return new AV.Op.Unset(); + }); + + /** + * @private + * @class + * An Increment is an atomic operation where the numeric value for the field + * will be increased by a given amount. + */ + AV.Op.Increment = AV.Op._extend( + /** @lends AV.Op.Increment.prototype */{ + + _initialize: function _initialize(amount) { + this._amount = amount; + }, + + /** + * Returns the amount to increment by. + * @return {Number} the amount to increment by. + */ + amount: function amount() { + return this._amount; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Increment", amount: this._amount }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.amount()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(previous.value() + this.amount()); + } else if (previous instanceof AV.Op.Increment) { + return new AV.Op.Increment(this.amount() + previous.amount()); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return this.amount(); + } + return oldValue + this.amount(); + } + }); + + AV.Op._registerDecoder("Increment", function (json) { + return new AV.Op.Increment(json.amount); + }); + + /** + * @private + * @class + * Add is an atomic operation where the given objects will be appended to the + * array that is stored in this field. + */ + AV.Op.Add = AV.Op._extend( /** @lends AV.Op.Add.prototype */{ + _initialize: function _initialize(objects) { + this._objects = objects; + }, + + /** + * Returns the objects to be added to the array. + * @return {Array} The objects to be added to the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Add", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.objects()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.Add) { + return new AV.Op.Add(previous.objects().concat(this.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return _.clone(this.objects()); + } else { + return oldValue.concat(this.objects()); + } + } + }); + + AV.Op._registerDecoder("Add", function (json) { + return new AV.Op.Add(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * AddUnique is an atomic operation where the given items will be appended to + * the array that is stored in this field only if they were not already + * present in the array. + */ + AV.Op.AddUnique = AV.Op._extend( + /** @lends AV.Op.AddUnique.prototype */{ + + _initialize: function _initialize(objects) { + this._objects = _.uniq(objects); + }, + + /** + * Returns the objects to be added to the array. + * @return {Array} The objects to be added to the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "AddUnique", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return new AV.Op.Set(this.objects()); + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.AddUnique) { + return new AV.Op.AddUnique(this._estimate(previous.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return _.clone(this.objects()); + } else { + // We can't just take the _.uniq(_.union(...)) of oldValue and + // this.objects, because the uniqueness may not apply to oldValue + // (especially if the oldValue was set via .set()) + var newValue = _.clone(oldValue); + AV._arrayEach(this.objects(), function (obj) { + if (obj instanceof AV.Object && obj.id) { + var matchingObj = _.find(newValue, function (anObj) { + return anObj instanceof AV.Object && anObj.id === obj.id; + }); + if (!matchingObj) { + newValue.push(obj); + } else { + var index = _.indexOf(newValue, matchingObj); + newValue[index] = obj; + } + } else if (!_.contains(newValue, obj)) { + newValue.push(obj); + } + }); + return newValue; + } + } + }); + + AV.Op._registerDecoder("AddUnique", function (json) { + return new AV.Op.AddUnique(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * Remove is an atomic operation where the given objects will be removed from + * the array that is stored in this field. + */ + AV.Op.Remove = AV.Op._extend( /** @lends AV.Op.Remove.prototype */{ + _initialize: function _initialize(objects) { + this._objects = _.uniq(objects); + }, + + /** + * Returns the objects to be removed from the array. + * @return {Array} The objects to be removed from the array. + */ + objects: function objects() { + return this._objects; + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + return { __op: "Remove", objects: AV._encode(this.objects()) }; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + return previous; + } else if (previous instanceof AV.Op.Set) { + return new AV.Op.Set(this._estimate(previous.value())); + } else if (previous instanceof AV.Op.Remove) { + return new AV.Op.Remove(_.union(previous.objects(), this.objects())); + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue) { + if (!oldValue) { + return []; + } else { + var newValue = _.difference(oldValue, this.objects()); + // If there are saved AV Objects being removed, also remove them. + AV._arrayEach(this.objects(), function (obj) { + if (obj instanceof AV.Object && obj.id) { + newValue = _.reject(newValue, function (other) { + return other instanceof AV.Object && other.id === obj.id; + }); + } + }); + return newValue; + } + } + }); + + AV.Op._registerDecoder("Remove", function (json) { + return new AV.Op.Remove(AV._decode(json.objects)); + }); + + /** + * @private + * @class + * A Relation operation indicates that the field is an instance of + * AV.Relation, and objects are being added to, or removed from, that + * relation. + */ + AV.Op.Relation = AV.Op._extend( + /** @lends AV.Op.Relation.prototype */{ + + _initialize: function _initialize(adds, removes) { + this._targetClassName = null; + + var self = this; + + var pointerToId = function pointerToId(object) { + if (object instanceof AV.Object) { + if (!object.id) { + throw new Error('You can\'t add an unsaved AV.Object to a relation.'); + } + if (!self._targetClassName) { + self._targetClassName = object.className; + } + if (self._targetClassName !== object.className) { + throw new Error("Tried to create a AV.Relation with 2 different types: " + self._targetClassName + " and " + object.className + "."); + } + return object.id; + } + return object; + }; + + this.relationsToAdd = _.uniq(_.map(adds, pointerToId)); + this.relationsToRemove = _.uniq(_.map(removes, pointerToId)); + }, + + /** + * Returns an array of unfetched AV.Object that are being added to the + * relation. + * @return {Array} + */ + added: function added() { + var self = this; + return _.map(this.relationsToAdd, function (objectId) { + var object = AV.Object._create(self._targetClassName); + object.id = objectId; + return object; + }); + }, + + /** + * Returns an array of unfetched AV.Object that are being removed from + * the relation. + * @return {Array} + */ + removed: function removed() { + var self = this; + return _.map(this.relationsToRemove, function (objectId) { + var object = AV.Object._create(self._targetClassName); + object.id = objectId; + return object; + }); + }, + + /** + * Returns a JSON version of the operation suitable for sending to AV. + * @return {Object} + */ + toJSON: function toJSON() { + var adds = null; + var removes = null; + var self = this; + var idToPointer = function idToPointer(id) { + return { __type: 'Pointer', + className: self._targetClassName, + objectId: id }; + }; + var pointers = null; + if (this.relationsToAdd.length > 0) { + pointers = _.map(this.relationsToAdd, idToPointer); + adds = { "__op": "AddRelation", "objects": pointers }; + } + + if (this.relationsToRemove.length > 0) { + pointers = _.map(this.relationsToRemove, idToPointer); + removes = { "__op": "RemoveRelation", "objects": pointers }; + } + + if (adds && removes) { + return { "__op": "Batch", "ops": [adds, removes] }; + } + + return adds || removes || {}; + }, + + _mergeWithPrevious: function _mergeWithPrevious(previous) { + if (!previous) { + return this; + } else if (previous instanceof AV.Op.Unset) { + throw new Error('You can\'t modify a relation after deleting it.'); + } else if (previous instanceof AV.Op.Relation) { + if (previous._targetClassName && previous._targetClassName !== this._targetClassName) { + throw new Error("Related object must be of class " + previous._targetClassName + ", but " + this._targetClassName + " was passed in."); + } + var newAdd = _.union(_.difference(previous.relationsToAdd, this.relationsToRemove), this.relationsToAdd); + var newRemove = _.union(_.difference(previous.relationsToRemove, this.relationsToAdd), this.relationsToRemove); + + var newRelation = new AV.Op.Relation(newAdd, newRemove); + newRelation._targetClassName = this._targetClassName; + return newRelation; + } else { + throw new Error('Op is invalid after previous op.'); + } + }, + + _estimate: function _estimate(oldValue, object, key) { + if (!oldValue) { + var relation = new AV.Relation(object, key); + relation.targetClassName = this._targetClassName; + } else if (oldValue instanceof AV.Relation) { + if (this._targetClassName) { + if (oldValue.targetClassName) { + if (oldValue.targetClassName !== this._targetClassName) { + throw new Error("Related object must be a " + oldValue.targetClassName + ", but a " + this._targetClassName + " was passed in."); + } + } else { + oldValue.targetClassName = this._targetClassName; + } + } + return oldValue; + } else { + throw new Error('Op is invalid after previous op.'); + } + } + }); + + AV.Op._registerDecoder("AddRelation", function (json) { + return new AV.Op.Relation(AV._decode(json.objects), []); + }); + AV.Op._registerDecoder("RemoveRelation", function (json) { + return new AV.Op.Relation([], AV._decode(json.objects)); + }); +}; \ No newline at end of file diff --git a/dist/node/promise.js b/dist/node/promise.js new file mode 100644 index 000000000..2118a3fea --- /dev/null +++ b/dist/node/promise.js @@ -0,0 +1,15 @@ +'use strict'; + +var _ = require('underscore'); +var Promise = require('es6-promise').Promise; + +Promise._continueWhile = function (predicate, asyncFunction) { + if (predicate()) { + return asyncFunction().then(function () { + return Promise._continueWhile(predicate, asyncFunction); + }); + } + return Promise.resolve(); +}; + +module.exports = Promise; \ No newline at end of file diff --git a/dist/node/push.js b/dist/node/push.js new file mode 100644 index 000000000..e321b4811 --- /dev/null +++ b/dist/node/push.js @@ -0,0 +1,53 @@ +"use strict"; + +var AVRequest = require('./request').request; + +module.exports = function (AV) { + AV.Installation = AV.Object.extend("_Installation"); + + /** + * @namespace + */ + AV.Push = AV.Push || {}; + + /** + * Sends a push notification. + * @param {Object} data The data of the push notification. + * @param {String[]} [data.channels] An Array of channels to push to. + * @param {Date} [data.push_time] A Date object for when to send the push. + * @param {Date} [data.expiration_time] A Date object for when to expire + * the push. + * @param {Number} [data.expiration_interval] The seconds from now to expire the push. + * @param {AV.Query} [data.where] An AV.Query over AV.Installation that is used to match + * a set of installations to push to. + * @param {String} [data.cql] A CQL statement over AV.Installation that is used to match + * a set of installations to push to. + * @param {Date} data.data The data to send as part of the push + * @param {AuthOptions} [options] + * @return {Promise} + */ + AV.Push.send = function (data, options) { + if (data.where) { + data.where = data.where.toJSON().where; + } + + if (data.where && data.cql) { + throw new Error("Both where and cql can't be set"); + } + + if (data.push_time) { + data.push_time = data.push_time.toJSON(); + } + + if (data.expiration_time) { + data.expiration_time = data.expiration_time.toJSON(); + } + + if (data.expiration_time && data.expiration_time_interval) { + throw new Error("Both expiration_time and expiration_time_interval can't be set"); + } + + var request = AVRequest('push', null, null, 'POST', data, options); + return request; + }; +}; \ No newline at end of file diff --git a/dist/node/query.js b/dist/node/query.js new file mode 100644 index 000000000..1f4cc7726 --- /dev/null +++ b/dist/node/query.js @@ -0,0 +1,1027 @@ +'use strict'; + +var _ = require('underscore'); +var debug = require('debug')('leancloud:query'); +var Promise = require('./promise'); +var AVError = require('./error'); +var AVRequest = require('./request').request; + +var _require = require('./utils'), + ensureArray = _require.ensureArray; + +var requires = function requires(value, message) { + if (value === undefined) { + throw new Error(message); + } +}; + +// AV.Query is a way to create a list of AV.Objects. +module.exports = function (AV) { + /** + * Creates a new AV.Query for the given AV.Object subclass. + * @param {Class|String} objectClass An instance of a subclass of AV.Object, or a AV className string. + * @class + * + *

AV.Query defines a query that is used to fetch AV.Objects. The + * most common use case is finding all objects that match a query through the + * find method. For example, this sample code fetches all objects + * of class MyClass. It calls a different function depending on + * whether the fetch succeeded or not. + * + *

+   * var query = new AV.Query(MyClass);
+   * query.find().then(function(results) {
+   *   // results is an array of AV.Object.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ * + *

An AV.Query can also be used to retrieve a single object whose id is + * known, through the get method. For example, this sample code fetches an + * object of class MyClass and id myId. It calls a + * different function depending on whether the fetch succeeded or not. + * + *

+   * var query = new AV.Query(MyClass);
+   * query.get(myId).then(function(object) {
+   *   // object is an instance of AV.Object.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ * + *

An AV.Query can also be used to count the number of objects that match + * the query without retrieving all of those objects. For example, this + * sample code counts the number of objects of the class MyClass + *

+   * var query = new AV.Query(MyClass);
+   * query.count().then(function(number) {
+   *   // There are number instances of MyClass.
+   * }, function(error) {
+   *   // error is an instance of AVError.
+   * });

+ */ + AV.Query = function (objectClass) { + if (_.isString(objectClass)) { + objectClass = AV.Object._getSubclass(objectClass); + } + + this.objectClass = objectClass; + + this.className = objectClass.prototype.className; + + this._where = {}; + this._include = []; + this._select = []; + this._limit = -1; // negative limit means, do not send a limit + this._skip = 0; + this._extraOptions = {}; + }; + + /** + * Constructs a AV.Query that is the OR of the passed in queries. For + * example: + *
var compoundQuery = AV.Query.or(query1, query2, query3);
+ * + * will create a compoundQuery that is an or of the query1, query2, and + * query3. + * @param {...AV.Query} var_args The list of queries to OR. + * @return {AV.Query} The query that is the OR of the passed in queries. + */ + AV.Query.or = function () { + var queries = _.toArray(arguments); + var className = null; + AV._arrayEach(queries, function (q) { + if (_.isNull(className)) { + className = q.className; + } + + if (className !== q.className) { + throw new Error('All queries must be for the same class'); + } + }); + var query = new AV.Query(className); + query._orQuery(queries); + return query; + }; + + /** + * Constructs a AV.Query that is the AND of the passed in queries. For + * example: + *
var compoundQuery = AV.Query.and(query1, query2, query3);
+ * + * will create a compoundQuery that is an 'and' of the query1, query2, and + * query3. + * @param {...AV.Query} var_args The list of queries to AND. + * @return {AV.Query} The query that is the AND of the passed in queries. + */ + AV.Query.and = function () { + var queries = _.toArray(arguments); + var className = null; + AV._arrayEach(queries, function (q) { + if (_.isNull(className)) { + className = q.className; + } + + if (className !== q.className) { + throw new Error('All queries must be for the same class'); + } + }); + var query = new AV.Query(className); + query._andQuery(queries); + return query; + }; + + /** + * Retrieves a list of AVObjects that satisfy the CQL. + * CQL syntax please see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}. + * + * @param {String} cql A CQL string, see {@link https://leancloud.cn/docs/cql_guide.html CQL Guide}. + * @param {Array} pvalues An array contains placeholder values. + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the results when + * the query completes. + */ + AV.Query.doCloudQuery = function (cql, pvalues, options) { + var params = { cql: cql }; + if (_.isArray(pvalues)) { + params.pvalues = pvalues; + } else { + options = pvalues; + } + + var request = AVRequest('cloudQuery', null, null, 'GET', params, options); + return request.then(function (response) { + //query to process results. + var query = new AV.Query(response.className); + var results = _.map(response.results, function (json) { + var obj = query._newObject(response); + if (obj._finishFetch) { + obj._finishFetch(query._processResult(json), true); + } + return obj; + }); + return { + results: results, + count: response.count, + className: response.className + }; + }); + }; + + AV.Query._extend = AV._extend; + + AV.Query.prototype = { + //hook to iterate result. Added by dennis. + _processResult: function _processResult(obj) { + return obj; + }, + + /** + * Constructs an AV.Object whose id is already known by fetching data from + * the server. + * + * @param {String} objectId The id of the object to be fetched. + * @param {AuthOptions} options + * @return {Promise.} + */ + get: function get(objectId, options) { + if (!objectId) { + var errorObject = new AVError(AVError.OBJECT_NOT_FOUND, "Object not found."); + throw errorObject; + } + + var self = this; + + var obj = self._newObject(); + obj.id = objectId; + + var queryJSON = self.toJSON(); + var fetchOptions = {}; + + if (queryJSON.keys) fetchOptions.keys = queryJSON.keys; + if (queryJSON.include) fetchOptions.include = queryJSON.include; + + return obj.fetch(fetchOptions, options); + }, + + /** + * Returns a JSON representation of this query. + * @return {Object} + */ + toJSON: function toJSON() { + var params = { + where: this._where + }; + + if (this._include.length > 0) { + params.include = this._include.join(","); + } + if (this._select.length > 0) { + params.keys = this._select.join(","); + } + if (this._limit >= 0) { + params.limit = this._limit; + } + if (this._skip > 0) { + params.skip = this._skip; + } + if (this._order !== undefined) { + params.order = this._order; + } + + AV._objectEach(this._extraOptions, function (v, k) { + params[k] = v; + }); + + return params; + }, + + _newObject: function _newObject(response) { + var obj; + if (response && response.className) { + obj = new AV.Object(response.className); + } else { + obj = new this.objectClass(); + } + return obj; + }, + _createRequest: function _createRequest() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.toJSON(); + var options = arguments[1]; + + if (JSON.stringify(params).length > 2000) { + var body = { + requests: [{ + method: 'GET', + path: '/1.1/classes/' + this.className, + params: params + }] + }; + return AVRequest('batch', null, null, 'POST', body, options).then(function (response) { + var result = response[0]; + if (result.success) { + return result.success; + } + var error = new Error(result.error.error || 'Unknown batch error'); + error.code = result.error.code; + throw error; + }); + } + return AVRequest('classes', this.className, null, "GET", params, options); + }, + _parseResponse: function _parseResponse(response) { + var _this = this; + + return _.map(response.results, function (json) { + var obj = _this._newObject(response); + if (obj._finishFetch) { + obj._finishFetch(_this._processResult(json), true); + } + return obj; + }); + }, + + + /** + * Retrieves a list of AVObjects that satisfy this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the results when + * the query completes. + */ + find: function find(options) { + var request = this._createRequest(undefined, options); + return request.then(this._parseResponse.bind(this)); + }, + + + /** + * scan a Query. masterKey required. + * + * @since 2.1.0 + * @param {object} [options] + * @param {string} [options.orderedBy] specify the key to sort + * @param {number} [options.batchSize] specify the batch size for each request + * @param {AuthOptions} [authOptions] + * @return {AsyncIterator.} + * @example const scan = new AV.Query(TestClass).scan({ + * orderedBy: 'objectId', + * batchSize: 10, + * }, { + * useMasterKey: true, + * }); + * const getTen = () => Promise.all(new Array(10).fill(0).map(() => scan.next())); + * getTen().then(results => { + * // results are fisrt 10 instances of TestClass + * return getTen(); + * }).then(results => { + * // 11 - 20 + * }); + */ + scan: function scan() { + var _this2 = this; + + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + orderedBy = _ref.orderedBy, + batchSize = _ref.batchSize; + + var authOptions = arguments[1]; + + var condition = this.toJSON(); + debug('scan %O', condition); + if (condition.order) { + console.warn('The order of the query is ignored for Query#scan. Checkout the orderedBy option of Query#scan.'); + delete condition.order; + } + if (condition.skip) { + console.warn('The skip option of the query is ignored for Query#scan.'); + delete condition.skip; + } + if (condition.limit) { + console.warn('The limit option of the query is ignored for Query#scan.'); + delete condition.limit; + } + if (orderedBy) condition.scan_key = orderedBy; + if (batchSize) condition.limit = batchSize; + var promise = Promise.resolve([]); + var cursor = void 0; + var done = false; + return { + next: function next() { + promise = promise.then(function (remainResults) { + if (done) return []; + if (remainResults.length > 1) return remainResults; + // no cursor means we have reached the end + // except for the first time + if (!cursor && remainResults.length !== 0) { + done = true; + return remainResults; + } + // when only 1 item left in queue + // start the next request to see if it is the last one + return AVRequest('scan/classes', _this2.className, null, 'GET', cursor ? _.extend({}, condition, { cursor: cursor }) : condition, authOptions).then(function (response) { + cursor = response.cursor; + return _this2._parseResponse(response); + }).then(function (results) { + if (!results.length) done = true; + return remainResults.concat(results); + }); + }); + return promise.then(function (remainResults) { + return remainResults.shift(); + }).then(function (result) { + return { + value: result, + done: done + }; + }); + } + }; + }, + + + /** + * Delete objects retrieved by this query. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the save + * completes. + */ + destroyAll: function destroyAll(options) { + var self = this; + return self.find(options).then(function (objects) { + return AV.Object.destroyAll(objects, options); + }); + }, + + /** + * Counts the number of objects that match this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the count when + * the query completes. + */ + count: function count(options) { + var params = this.toJSON(); + params.limit = 0; + params.count = 1; + var request = this._createRequest(params, options); + + return request.then(function (response) { + return response.count; + }); + }, + + /** + * Retrieves at most one AV.Object that satisfies this query. + * + * @param {AuthOptions} options + * @return {Promise} A promise that is resolved with the object when + * the query completes. + */ + first: function first(options) { + var self = this; + + var params = this.toJSON(); + params.limit = 1; + var request = this._createRequest(params, options); + + return request.then(function (response) { + return _.map(response.results, function (json) { + var obj = self._newObject(); + if (obj._finishFetch) { + obj._finishFetch(self._processResult(json), true); + } + return obj; + })[0]; + }); + }, + + /** + * Sets the number of results to skip before returning any results. + * This is useful for pagination. + * Default is to skip zero results. + * @param {Number} n the number of results to skip. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + skip: function skip(n) { + requires(n, 'undefined is not a valid skip value'); + this._skip = n; + return this; + }, + + /** + * Sets the limit of the number of results to return. The default limit is + * 100, with a maximum of 1000 results being returned at a time. + * @param {Number} n the number of results to limit to. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + limit: function limit(n) { + requires(n, 'undefined is not a valid limit value'); + this._limit = n; + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be equal to the provided value. + * @param {String} key The key to check. + * @param value The value that the AV.Object must contain. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + equalTo: function equalTo(key, value) { + requires(key, 'undefined is not a valid key'); + requires(value, 'undefined is not a valid value'); + this._where[key] = AV._encode(value); + return this; + }, + + /** + * Helper for condition queries + * @private + */ + _addCondition: function _addCondition(key, condition, value) { + requires(key, 'undefined is not a valid condition key'); + requires(condition, 'undefined is not a valid condition'); + requires(value, 'undefined is not a valid condition value'); + + // Check if we already have a condition + if (!this._where[key]) { + this._where[key] = {}; + } + this._where[key][condition] = AV._encode(value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular + * array key's length to be equal to the provided value. + * @param {String} key The array key to check. + * @param value The length value. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + sizeEqualTo: function sizeEqualTo(key, value) { + this._addCondition(key, "$size", value); + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be not equal to the provided value. + * @param {String} key The key to check. + * @param value The value that must not be equalled. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + notEqualTo: function notEqualTo(key, value) { + this._addCondition(key, "$ne", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than the provided value. + * @param {String} key The key to check. + * @param value The value that provides an upper bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + lessThan: function lessThan(key, value) { + this._addCondition(key, "$lt", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than the provided value. + * @param {String} key The key to check. + * @param value The value that provides an lower bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + greaterThan: function greaterThan(key, value) { + this._addCondition(key, "$gt", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than or equal to the provided value. + * @param {String} key The key to check. + * @param value The value that provides an upper bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + lessThanOrEqualTo: function lessThanOrEqualTo(key, value) { + this._addCondition(key, "$lte", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than or equal to the provided value. + * @param {String} key The key to check. + * @param value The value that provides an lower bound. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + greaterThanOrEqualTo: function greaterThanOrEqualTo(key, value) { + this._addCondition(key, "$gte", value); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * be contained in the provided list of values. + * @param {String} key The key to check. + * @param {Array} values The values that will match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + containedIn: function containedIn(key, values) { + this._addCondition(key, "$in", values); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * not be contained in the provided list of values. + * @param {String} key The key to check. + * @param {Array} values The values that will not match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + notContainedIn: function notContainedIn(key, values) { + this._addCondition(key, "$nin", values); + return this; + }, + + /** + * Add a constraint to the query that requires a particular key's value to + * contain each one of the provided list of values. + * @param {String} key The key to check. This key's value must be an array. + * @param {Array} values The values that will match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + containsAll: function containsAll(key, values) { + this._addCondition(key, "$all", values); + return this; + }, + + /** + * Add a constraint for finding objects that contain the given key. + * @param {String} key The key that should exist. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + exists: function exists(key) { + this._addCondition(key, "$exists", true); + return this; + }, + + /** + * Add a constraint for finding objects that do not contain a given key. + * @param {String} key The key that should not exist + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotExist: function doesNotExist(key) { + this._addCondition(key, "$exists", false); + return this; + }, + + /** + * Add a regular expression constraint for finding string values that match + * the provided regular expression. + * This may be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {RegExp} regex The regular expression pattern to match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matches: function matches(key, regex, modifiers) { + this._addCondition(key, "$regex", regex); + if (!modifiers) { + modifiers = ""; + } + // Javascript regex options support mig as inline options but store them + // as properties of the object. We support mi & should migrate them to + // modifiers + if (regex.ignoreCase) { + modifiers += 'i'; + } + if (regex.multiline) { + modifiers += 'm'; + } + + if (modifiers && modifiers.length) { + this._addCondition(key, "$options", modifiers); + } + return this; + }, + + /** + * Add a constraint that requires that a key's value matches a AV.Query + * constraint. + * @param {String} key The key that the contains the object to match the + * query. + * @param {AV.Query} query The query that should match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matchesQuery: function matchesQuery(key, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$inQuery", queryJSON); + return this; + }, + + /** + * Add a constraint that requires that a key's value not matches a + * AV.Query constraint. + * @param {String} key The key that the contains the object to match the + * query. + * @param {AV.Query} query The query that should not match. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotMatchQuery: function doesNotMatchQuery(key, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$notInQuery", queryJSON); + return this; + }, + + /** + * Add a constraint that requires that a key's value matches a value in + * an object returned by a different AV.Query. + * @param {String} key The key that contains the value that is being + * matched. + * @param {String} queryKey The key in the objects returned by the query to + * match against. + * @param {AV.Query} query The query to run. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + matchesKeyInQuery: function matchesKeyInQuery(key, queryKey, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$select", { key: queryKey, query: queryJSON }); + return this; + }, + + /** + * Add a constraint that requires that a key's value not match a value in + * an object returned by a different AV.Query. + * @param {String} key The key that contains the value that is being + * excluded. + * @param {String} queryKey The key in the objects returned by the query to + * match against. + * @param {AV.Query} query The query to run. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + doesNotMatchKeyInQuery: function doesNotMatchKeyInQuery(key, queryKey, query) { + var queryJSON = query.toJSON(); + queryJSON.className = query.className; + this._addCondition(key, "$dontSelect", { key: queryKey, query: queryJSON }); + return this; + }, + + /** + * Add constraint that at least one of the passed in queries matches. + * @param {Array} queries + * @return {AV.Query} Returns the query, so you can chain this call. + * @private + */ + _orQuery: function _orQuery(queries) { + var queryJSON = _.map(queries, function (q) { + return q.toJSON().where; + }); + + this._where.$or = queryJSON; + return this; + }, + + /** + * Add constraint that both of the passed in queries matches. + * @param {Array} queries + * @return {AV.Query} Returns the query, so you can chain this call. + * @private + */ + _andQuery: function _andQuery(queries) { + var queryJSON = _.map(queries, function (q) { + return q.toJSON().where; + }); + + this._where.$and = queryJSON; + return this; + }, + + /** + * Converts a string into a regex that matches it. + * Surrounding with \Q .. \E does this, we just need to escape \E's in + * the text separately. + * @private + */ + _quote: function _quote(s) { + return "\\Q" + s.replace("\\E", "\\E\\\\E\\Q") + "\\E"; + }, + + /** + * Add a constraint for finding string values that contain a provided + * string. This may be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} substring The substring that the value must contain. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + contains: function contains(key, value) { + this._addCondition(key, "$regex", this._quote(value)); + return this; + }, + + /** + * Add a constraint for finding string values that start with a provided + * string. This query will use the backend index, so it will be fast even + * for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} prefix The substring that the value must start with. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + startsWith: function startsWith(key, value) { + this._addCondition(key, "$regex", "^" + this._quote(value)); + return this; + }, + + /** + * Add a constraint for finding string values that end with a provided + * string. This will be slow for large datasets. + * @param {String} key The key that the string to match is stored in. + * @param {String} suffix The substring that the value must end with. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + endsWith: function endsWith(key, value) { + this._addCondition(key, "$regex", this._quote(value) + "$"); + return this; + }, + + /** + * Sorts the results in ascending order by the given key. + * + * @param {String} key The key to order by. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + ascending: function ascending(key) { + requires(key, 'undefined is not a valid key'); + this._order = key; + return this; + }, + + /** + * Also sorts the results in ascending order by the given key. The previous sort keys have + * precedence over this key. + * + * @param {String} key The key to order by + * @return {AV.Query} Returns the query so you can chain this call. + */ + addAscending: function addAscending(key) { + requires(key, 'undefined is not a valid key'); + if (this._order) this._order += ',' + key;else this._order = key; + return this; + }, + + /** + * Sorts the results in descending order by the given key. + * + * @param {String} key The key to order by. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + descending: function descending(key) { + requires(key, 'undefined is not a valid key'); + this._order = "-" + key; + return this; + }, + + /** + * Also sorts the results in descending order by the given key. The previous sort keys have + * precedence over this key. + * + * @param {String} key The key to order by + * @return {AV.Query} Returns the query so you can chain this call. + */ + addDescending: function addDescending(key) { + requires(key, 'undefined is not a valid key'); + if (this._order) this._order += ',-' + key;else this._order = '-' + key; + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + near: function near(key, point) { + if (!(point instanceof AV.GeoPoint)) { + // Try to cast it to a GeoPoint, so that near("loc", [20,30]) works. + point = new AV.GeoPoint(point); + } + this._addCondition(key, "$nearSphere", point); + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param maxDistance Maximum distance (in radians) of results to return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinRadians: function withinRadians(key, point, distance) { + this.near(key, point); + this._addCondition(key, "$maxDistance", distance); + return this; + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 3958.8 miles. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Number} maxDistance Maximum distance (in miles) of results to + * return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinMiles: function withinMiles(key, point, distance) { + return this.withinRadians(key, point, distance / 3958.8); + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 6371.0 kilometers. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Number} maxDistance Maximum distance (in kilometers) of results + * to return. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinKilometers: function withinKilometers(key, point, distance) { + return this.withinRadians(key, point, distance / 6371.0); + }, + + /** + * Add a constraint to the query that requires a particular key's + * coordinates be contained within a given rectangular geographic bounding + * box. + * @param {String} key The key to be constrained. + * @param {AV.GeoPoint} southwest + * The lower-left inclusive corner of the box. + * @param {AV.GeoPoint} northeast + * The upper-right inclusive corner of the box. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + withinGeoBox: function withinGeoBox(key, southwest, northeast) { + if (!(southwest instanceof AV.GeoPoint)) { + southwest = new AV.GeoPoint(southwest); + } + if (!(northeast instanceof AV.GeoPoint)) { + northeast = new AV.GeoPoint(northeast); + } + this._addCondition(key, '$within', { '$box': [southwest, northeast] }); + return this; + }, + + /** + * Include nested AV.Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetch. + * @param {String[]} keys The name of the key to include. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + include: function include(keys) { + var _this3 = this; + + requires(keys, 'undefined is not a valid key'); + _(arguments).forEach(function (keys) { + _this3._include = _this3._include.concat(ensureArray(keys)); + }); + return this; + }, + + /** + * Restrict the fields of the returned AV.Objects to include only the + * provided keys. If this is called multiple times, then all of the keys + * specified in each of the calls will be included. + * @param {String[]} keys The names of the keys to include. + * @return {AV.Query} Returns the query, so you can chain this call. + */ + select: function select(keys) { + var _this4 = this; + + requires(keys, 'undefined is not a valid key'); + _(arguments).forEach(function (keys) { + _this4._select = _this4._select.concat(ensureArray(keys)); + }); + return this; + }, + + /** + * Iterates over each result of a query, calling a callback for each one. If + * the callback returns a promise, the iteration will not continue until + * that promise has been fulfilled. If the callback returns a rejected + * promise, then iteration will stop with that error. The items are + * processed in an unspecified order. The query may not have any sort order, + * and may not use limit or skip. + * @param callback {Function} Callback that will be called with each result + * of the query. + * @return {Promise} A promise that will be fulfilled once the + * iteration has completed. + */ + each: function each(callback) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + + if (this._order || this._skip || this._limit >= 0) { + var error = new Error("Cannot iterate on a query with sort, skip, or limit."); + return AV.Promise.reject(error); + } + + var query = new AV.Query(this.objectClass); + // We can override the batch size from the options. + // This is undocumented, but useful for testing. + query._limit = options.batchSize || 100; + query._where = _.clone(this._where); + query._include = _.clone(this._include); + + query.ascending('objectId'); + + var finished = false; + return AV.Promise._continueWhile(function () { + return !finished; + }, function () { + return query.find(options).then(function (results) { + var callbacksDone = AV.Promise.resolve(); + _.each(results, function (result) { + callbacksDone = callbacksDone.then(function () { + return callback(result); + }); + }); + + return callbacksDone.then(function () { + if (results.length >= query._limit) { + query.greaterThan("objectId", results[results.length - 1].id); + } else { + finished = true; + } + }); + }); + }); + } + }; + + AV.FriendShipQuery = AV.Query._extend({ + _objectClass: AV.User, + _newObject: function _newObject() { + return new AV.User(); + }, + _processResult: function _processResult(json) { + if (json && json[this._friendshipTag]) { + var user = json[this._friendshipTag]; + if (user.__type === 'Pointer' && user.className === '_User') { + delete user.__type; + delete user.className; + } + return user; + } else { + return null; + } + } + }); +}; \ No newline at end of file diff --git a/dist/node/relation.js b/dist/node/relation.js new file mode 100644 index 000000000..1b711deee --- /dev/null +++ b/dist/node/relation.js @@ -0,0 +1,117 @@ +'use strict'; + +var _ = require('underscore'); + +module.exports = function (AV) { + /** + * Creates a new Relation for the given parent object and key. This + * constructor should rarely be used directly, but rather created by + * {@link AV.Object#relation}. + * @param {AV.Object} parent The parent of this relation. + * @param {String} key The key for this relation on the parent. + * @see AV.Object#relation + * @class + * + *

+ * A class that is used to access all of the children of a many-to-many + * relationship. Each instance of AV.Relation is associated with a + * particular parent object and key. + *

+ */ + AV.Relation = function (parent, key) { + if (!_.isString(key)) { + throw new TypeError('key must be a string'); + } + this.parent = parent; + this.key = key; + this.targetClassName = null; + }; + + /** + * Creates a query that can be used to query the parent objects in this relation. + * @param {String} parentClass The parent class or name. + * @param {String} relationKey The relation field key in parent. + * @param {AV.Object} child The child object. + * @return {AV.Query} + */ + AV.Relation.reverseQuery = function (parentClass, relationKey, child) { + var query = new AV.Query(parentClass); + query.equalTo(relationKey, child._toPointer()); + return query; + }; + + AV.Relation.prototype = { + /** + * Makes sure that this relation has the right parent and key. + * @private + */ + _ensureParentAndKey: function _ensureParentAndKey(parent, key) { + this.parent = this.parent || parent; + this.key = this.key || key; + if (this.parent !== parent) { + throw new Error("Internal Error. Relation retrieved from two different Objects."); + } + if (this.key !== key) { + throw new Error("Internal Error. Relation retrieved from two different keys."); + } + }, + + /** + * Adds a AV.Object or an array of AV.Objects to the relation. + * @param {AV.Object|AV.Object[]} objects The item or items to add. + */ + add: function add(objects) { + if (!_.isArray(objects)) { + objects = [objects]; + } + + var change = new AV.Op.Relation(objects, []); + this.parent.set(this.key, change); + this.targetClassName = change._targetClassName; + }, + + /** + * Removes a AV.Object or an array of AV.Objects from this relation. + * @param {AV.Object|AV.Object[]} objects The item or items to remove. + */ + remove: function remove(objects) { + if (!_.isArray(objects)) { + objects = [objects]; + } + + var change = new AV.Op.Relation([], objects); + this.parent.set(this.key, change); + this.targetClassName = change._targetClassName; + }, + + /** + * Returns a JSON version of the object suitable for saving to disk. + * @return {Object} + */ + toJSON: function toJSON() { + return { "__type": "Relation", "className": this.targetClassName }; + }, + + /** + * Returns a AV.Query that is limited to objects in this + * relation. + * @return {AV.Query} + */ + query: function query() { + var targetClass; + var query; + if (!this.targetClassName) { + targetClass = AV.Object._getSubclass(this.parent.className); + query = new AV.Query(targetClass); + query._extraOptions.redirectClassNameForKey = this.key; + } else { + targetClass = AV.Object._getSubclass(this.targetClassName); + query = new AV.Query(targetClass); + } + query._addCondition("$relatedTo", "object", this.parent._toPointer()); + query._addCondition("$relatedTo", "key", this.key); + + return query; + } + }; +}; \ No newline at end of file diff --git a/dist/node/request.js b/dist/node/request.js new file mode 100644 index 000000000..be636d953 --- /dev/null +++ b/dist/node/request.js @@ -0,0 +1,310 @@ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var request = require('superagent'); +var debug = require('debug')('leancloud:request'); +var md5 = require('md5'); +var Promise = require('./promise'); +var Cache = require('./cache'); +var AVError = require('./error'); +var AV = require('./av'); +var _ = require('underscore'); + +var _require = require('./utils'), + getSessionToken = _require.getSessionToken; + +var getServerURLPromise = void 0; + +// 服务器请求的节点 host +var API_HOST = { + cn: 'https://api.leancloud.cn', + us: 'https://us-api.leancloud.cn' +}; + +// 计算 X-LC-Sign 的签名方法 +var sign = function sign(key, isMasterKey) { + var now = new Date().getTime(); + var signature = md5(now + key); + if (isMasterKey) { + return signature + ',' + now + ',master'; + } + return signature + ',' + now; +}; + +var requestsCount = 0; + +var ajax = function ajax(method, resourceUrl, data) { + var headers = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var onprogress = arguments[4]; + + var count = requestsCount++; + + debug('request(' + count + ')', method, resourceUrl, data, headers); + + return new Promise(function (resolve, reject) { + var req = request(method, resourceUrl).set(headers).send(data); + if (onprogress) { + req.on('progress', onprogress); + } + req.end(function (err, res) { + if (res) { + debug('response(' + count + ')', res.status, res.body || res.text, res.header); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + return resolve(res.body); + }); + }); +}; + +var setAppKey = function setAppKey(headers, signKey) { + if (signKey) { + headers['X-LC-Sign'] = sign(AV.applicationKey); + } else { + headers['X-LC-Key'] = AV.applicationKey; + } +}; + +var setHeaders = function setHeaders() { + var authOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var signKey = arguments[1]; + + var headers = { + 'X-LC-Id': AV.applicationId, + 'Content-Type': 'application/json;charset=UTF-8' + }; + var useMasterKey = false; + if (typeof authOptions.useMasterKey === 'boolean') { + useMasterKey = authOptions.useMasterKey; + } else if (typeof AV._useMasterKey === 'boolean') { + useMasterKey = AV._useMasterKey; + } + if (useMasterKey) { + if (AV.masterKey) { + if (signKey) { + headers['X-LC-Sign'] = sign(AV.masterKey, true); + } else { + headers['X-LC-Key'] = AV.masterKey + ',master'; + } + } else { + console.warn('masterKey is not set, fall back to use appKey'); + setAppKey(headers, signKey); + } + } else { + setAppKey(headers, signKey); + } + if (AV.hookKey) { + headers['X-LC-Hook-Key'] = AV.hookKey; + } + if (AV._config.applicationProduction !== null) { + headers['X-LC-Prod'] = String(AV._config.applicationProduction); + } + headers[!process.env.CLIENT_PLATFORM ? 'User-Agent' : 'X-LC-UA'] = AV._config.userAgent; + + return Promise.resolve().then(function () { + // Pass the session token + var sessionToken = getSessionToken(authOptions); + if (sessionToken) { + headers['X-LC-Session'] = sessionToken; + } else if (!AV._config.disableCurrentUser) { + return AV.User.currentAsync().then(function (currentUser) { + if (currentUser && currentUser._sessionToken) { + headers['X-LC-Session'] = currentUser._sessionToken; + } + return headers; + }); + } + return headers; + }); +}; + +var createApiUrl = function createApiUrl(route, className, objectId, method, dataObject) { + // TODO: 兼容 AV.serverURL 旧方式设置 API Host,后续去掉 + if (AV.serverURL) { + AV._config.APIServerURL = AV.serverURL; + console.warn('Please use AV._config.APIServerURL to replace AV.serverURL, and it is an internal interface.'); + } + + var apiURL = AV._config.APIServerURL || API_HOST.cn; + + if (apiURL.charAt(apiURL.length - 1) !== '/') { + apiURL += '/'; + } + apiURL += '1.1/' + route; + if (className) { + apiURL += '/' + className; + } + if (objectId) { + apiURL += '/' + objectId; + } + if ((route === 'users' || route === 'classes') && dataObject) { + apiURL += '?'; + if (dataObject._fetchWhenSave) { + delete dataObject._fetchWhenSave; + apiURL += '&new=true'; + } + if (dataObject._where) { + apiURL += '&where=' + encodeURIComponent(JSON.stringify(dataObject._where)); + delete dataObject._where; + } + } + + if (method.toLowerCase() === 'get') { + if (apiURL.indexOf('?') === -1) { + apiURL += '?'; + } + for (var k in dataObject) { + if (_typeof(dataObject[k]) === 'object') { + dataObject[k] = JSON.stringify(dataObject[k]); + } + apiURL += '&' + k + '=' + encodeURIComponent(dataObject[k]); + } + } + + return apiURL; +}; + +var cacheServerURL = function cacheServerURL(serverURL, ttl) { + if (typeof ttl !== 'number') { + ttl = 3600; + } + return Cache.setAsync('APIServerURL', serverURL, ttl * 1000); +}; + +// handle AV._request Error +var handleError = function handleError(error) { + return new Promise(function (resolve, reject) { + /** + When API request need to redirect to the right location, + can't use browser redirect by http status 307, as the reason of CORS, + so API server response http status 410 and the param "location" for this case. + */ + if (error.statusCode === 410) { + cacheServerURL(error.response.api_server, error.response.ttl).then(function () { + resolve(error.response.location); + }).catch(reject); + } else { + var errorJSON = { + code: error.code || -1, + error: error.message || error.responseText + }; + if (error.response && error.response.code) { + errorJSON = error.response; + } else if (error.responseText) { + try { + errorJSON = JSON.parse(error.responseText); + } catch (e) { + // If we fail to parse the error text, that's okay. + } + } + + // Transform the error into an instance of AVError by trying to parse + // the error string as JSON. + reject(new AVError(errorJSON.code, errorJSON.error)); + } + }); +}; + +var setServerUrl = function setServerUrl(serverURL) { + AV._config.APIServerURL = 'https://' + serverURL; + + // 根据新 URL 重新设置区域 + var newRegion = _.findKey(API_HOST, function (item) { + return item === AV._config.APIServerURL; + }); + if (newRegion) { + AV._config.region = newRegion; + } +}; + +var refreshServerUrlByRouter = function refreshServerUrlByRouter() { + var url = 'https://app-router.leancloud.cn/1/route?appId=' + AV.applicationId; + return ajax('get', url).then(function (servers) { + if (servers.api_server) { + setServerUrl(servers.api_server); + return cacheServerURL(servers.api_server, servers.ttl); + } + }, function (error) { + // bypass all non-4XX errors + if (error.statusCode >= 400 && error.statusCode < 500) { + throw error; + } + }); +}; + +var setServerUrlByRegion = function setServerUrlByRegion() { + var region = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'cn'; + + getServerURLPromise = new Promise(function (resolve, reject) { + // 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router + if (AV._config.APIServerURL) { + resolve(); + return; + } + // if not china server region, do not use router + if (region === 'cn') { + return Cache.getAsync('APIServerURL').then(function (serverURL) { + if (serverURL) { + setServerUrl(serverURL); + } else { + return refreshServerUrlByRouter(); + } + }).then(function () { + resolve(); + }).catch(function (error) { + reject(error); + }); + } else { + AV._config.region = region; + AV._config.APIServerURL = API_HOST[region]; + resolve(); + } + }); +}; + +/** + * route is classes, users, login, etc. + * objectId is null if there is no associated objectId. + * method is the http method for the REST API. + * dataObject is the payload as an object, or null if there is none. + * @ignore + */ +var AVRequest = function AVRequest(route, className, objectId, method) { + var dataObject = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + var authOptions = arguments[5]; + + if (!AV.applicationId) { + throw new Error('You must specify your applicationId using AV.init()'); + } + + if (!AV.applicationKey && !AV.masterKey) { + throw new Error('You must specify a AppKey using AV.init()'); + } + + if (!getServerURLPromise) { + return Promise.reject(new Error('Not initialized')); + } + return getServerURLPromise.then(function () { + var apiURL = createApiUrl(route, className, objectId, method, dataObject); + return setHeaders(authOptions, route !== 'bigquery').then(function (headers) { + return ajax(method, apiURL, dataObject, headers).then(null, function (res) { + return handleError(res).then(function (location) { + return ajax(method, location, dataObject, headers); + }); + }); + }); + }); +}; + +module.exports = { + ajax: ajax, + request: AVRequest, + setServerUrlByRegion: setServerUrlByRegion +}; \ No newline at end of file diff --git a/dist/node/role.js b/dist/node/role.js new file mode 100644 index 000000000..cc54e4c48 --- /dev/null +++ b/dist/node/role.js @@ -0,0 +1,131 @@ +'use strict'; + +var _ = require('underscore'); +var AVError = require('./error'); + +module.exports = function (AV) { + AV.Role = AV.Object.extend("_Role", /** @lends AV.Role.prototype */{ + // Instance Methods + + /** + * Represents a Role on the AV server. Roles represent groupings of + * Users for the purposes of granting permissions (e.g. specifying an ACL + * for an Object). Roles are specified by their sets of child users and + * child roles, all of which are granted any permissions that the parent + * role has. + * + *

Roles must have a name (which cannot be changed after creation of the + * role), and must specify an ACL.

+ * An AV.Role is a local representation of a role persisted to the AV + * cloud. + * @class AV.Role + * @param {String} name The name of the Role to create. + * @param {AV.ACL} [acl] The ACL for this role. if absent, the default ACL + * `{'*': { read: true }}` will be used. + */ + constructor: function constructor(name, acl, noDefaultACL) { + if (_.isString(name)) { + AV.Object.prototype.constructor.call(this, null, null); + this.setName(name); + } else { + AV.Object.prototype.constructor.call(this, name, acl); + } + if (acl === undefined) { + if (!noDefaultACL) { + if (!this.getACL()) { + console.warn('DEPRECATED: To create a Role without ACL(a default ACL will be used) is deprecated. Please specify an ACL.'); + var defaultAcl = new AV.ACL(); + defaultAcl.setPublicReadAccess(true); + this.setACL(defaultAcl); + } + } + } else if (!(acl instanceof AV.ACL)) { + throw new TypeError('acl must be an instance of AV.ACL'); + } else { + this.setACL(acl); + } + }, + + /** + * Gets the name of the role. You can alternatively call role.get("name") + * + * @return {String} the name of the role. + */ + getName: function getName() { + return this.get("name"); + }, + + /** + * Sets the name for a role. This value must be set before the role has + * been saved to the server, and cannot be set once the role has been + * saved. + * + *

+ * A role's name can only contain alphanumeric characters, _, -, and + * spaces. + *

+ * + *

This is equivalent to calling role.set("name", name)

+ * + * @param {String} name The name of the role. + */ + setName: function setName(name, options) { + return this.set("name", name, options); + }, + + /** + * Gets the AV.Relation for the AV.Users that are direct + * children of this role. These users are granted any privileges that this + * role has been granted (e.g. read or write access through ACLs). You can + * add or remove users from the role through this relation. + * + *

This is equivalent to calling role.relation("users")

+ * + * @return {AV.Relation} the relation for the users belonging to this + * role. + */ + getUsers: function getUsers() { + return this.relation("users"); + }, + + /** + * Gets the AV.Relation for the AV.Roles that are direct + * children of this role. These roles' users are granted any privileges that + * this role has been granted (e.g. read or write access through ACLs). You + * can add or remove child roles from this role through this relation. + * + *

This is equivalent to calling role.relation("roles")

+ * + * @return {AV.Relation} the relation for the roles belonging to this + * role. + */ + getRoles: function getRoles() { + return this.relation("roles"); + }, + + /** + * @ignore + */ + validate: function validate(attrs, options) { + if ("name" in attrs && attrs.name !== this.getName()) { + var newName = attrs.name; + if (this.id && this.id !== attrs.objectId) { + // Check to see if the objectId being set matches this.id. + // This happens during a fetch -- the id is set before calling fetch. + // Let the name be set in this case. + return new AVError(AVError.OTHER_CAUSE, "A role's name can only be set before it has been saved."); + } + if (!_.isString(newName)) { + return new AVError(AVError.OTHER_CAUSE, "A role's name must be a String."); + } + if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) { + return new AVError(AVError.OTHER_CAUSE, "A role's name can only contain alphanumeric characters, _," + " -, and spaces."); + } + } + if (AV.Object.prototype.validate) { + return AV.Object.prototype.validate.call(this, attrs, options); + } + return false; + } + }); +}; \ No newline at end of file diff --git a/dist/node/search.js b/dist/node/search.js new file mode 100644 index 000000000..1cef7ecb9 --- /dev/null +++ b/dist/node/search.js @@ -0,0 +1,278 @@ +'use strict'; + +var _ = require('underscore'); +var AVRequest = require('./request').request; + +module.exports = function (AV) { + /** + * A builder to generate sort string for app searching.For example: + * @class + * @since 0.5.1 + * @example + * var builder = new AV.SearchSortBuilder(); + * builder.ascending('key1').descending('key2','max'); + * var query = new AV.SearchQuery('Player'); + * query.sortBy(builder); + * query.find().then(); + */ + AV.SearchSortBuilder = function () { + this._sortFields = []; + }; + + AV.SearchSortBuilder.prototype = { + _addField: function _addField(key, order, mode, missing) { + var field = {}; + field[key] = { + order: order || 'asc', + mode: mode || 'avg', + missing: '_' + (missing || 'last') + }; + this._sortFields.push(field); + return this; + }, + + /** + * Sorts the results in ascending order by the given key and options. + * + * @param {String} key The key to order by. + * @param {String} mode The sort mode, default is 'avg', you can choose + * 'max' or 'min' too. + * @param {String} missing The missing key behaviour, default is 'last', + * you can choose 'first' too. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + ascending: function ascending(key, mode, missing) { + return this._addField(key, 'asc', mode, missing); + }, + + /** + * Sorts the results in descending order by the given key and options. + * + * @param {String} key The key to order by. + * @param {String} mode The sort mode, default is 'avg', you can choose + * 'max' or 'min' too. + * @param {String} missing The missing key behaviour, default is 'last', + * you can choose 'first' too. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + descending: function descending(key, mode, missing) { + return this._addField(key, 'desc', mode, missing); + }, + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * @param {String} key The key that the AV.GeoPoint is stored in. + * @param {AV.GeoPoint} point The reference AV.GeoPoint that is used. + * @param {Object} options The other options such as mode,order, unit etc. + * @return {AV.SearchSortBuilder} Returns the builder, so you can chain this call. + */ + whereNear: function whereNear(key, point, options) { + options = options || {}; + var field = {}; + var geo = { + lat: point.latitude, + lon: point.longitude + }; + var m = { + order: options.order || 'asc', + mode: options.mode || 'avg', + unit: options.unit || 'km' + }; + m[key] = geo; + field['_geo_distance'] = m; + + this._sortFields.push(field); + return this; + }, + + /** + * Build a sort string by configuration. + * @return {String} the sort string. + */ + build: function build() { + return JSON.stringify(AV._encode(this._sortFields)); + } + }; + + /** + * App searching query.Use just like AV.Query: + * + * Visit App Searching Guide + * for more details. + * @class + * @since 0.5.1 + * @example + * var query = new AV.SearchQuery('Player'); + * query.queryString('*'); + * query.find().then(function(results) { + * console.log('Found %d objects', query.hits()); + * //Process results + * }); + */ + AV.SearchQuery = AV.Query._extend( /** @lends AV.SearchQuery.prototype */{ + _sid: null, + _hits: 0, + _queryString: null, + _highlights: null, + _sortBuilder: null, + _createRequest: function _createRequest(params, options) { + return AVRequest('search/select', null, null, 'GET', params || this.toJSON(), options); + }, + + /** + * Sets the sid of app searching query.Default is null. + * @param {String} sid Scroll id for searching. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + sid: function sid(_sid) { + this._sid = _sid; + return this; + }, + + /** + * Sets the query string of app searching. + * @param {String} q The query string. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + queryString: function queryString(q) { + this._queryString = q; + return this; + }, + + /** + * Sets the highlight fields. Such as + *

+     *   query.highlights('title');
+     *   //or pass an array.
+     *   query.highlights(['title', 'content'])
+     * 
+ * @param {String[]} highlights a list of fields. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + */ + highlights: function highlights(_highlights) { + var objects; + if (_highlights && _.isString(_highlights)) { + objects = arguments; + } else { + objects = _highlights; + } + this._highlights = objects; + return this; + }, + + /** + * Sets the sort builder for this query. + * @see AV.SearchSortBuilder + * @param { AV.SearchSortBuilder} builder The sort builder. + * @return {AV.SearchQuery} Returns the query, so you can chain this call. + * + */ + sortBy: function sortBy(builder) { + this._sortBuilder = builder; + return this; + }, + + /** + * Returns the number of objects that match this query. + * @return {Number} + */ + hits: function hits() { + if (!this._hits) { + this._hits = 0; + } + return this._hits; + }, + + _processResult: function _processResult(json) { + delete json['className']; + delete json['_app_url']; + delete json['_deeplink']; + return json; + }, + + /** + * Returns true when there are more documents can be retrieved by this + * query instance, you can call find function to get more results. + * @see AV.SearchQuery#find + * @return {Boolean} + */ + hasMore: function hasMore() { + return !this._hitEnd; + }, + + /** + * Reset current query instance state(such as sid, hits etc) except params + * for a new searching. After resetting, hasMore() will return true. + */ + reset: function reset() { + this._hitEnd = false; + this._sid = null; + this._hits = 0; + }, + + /** + * Retrieves a list of AVObjects that satisfy this query. + * Either options.success or options.error is called when the find + * completes. + * + * @see AV.Query#find + * @return {AV.Promise} A promise that is resolved with the results when + * the query completes. + */ + find: function find() { + var self = this; + + var request = this._createRequest(); + + return request.then(function (response) { + //update sid for next querying. + if (response.sid) { + self._oldSid = self._sid; + self._sid = response.sid; + } else { + self._sid = null; + self._hitEnd = true; + } + self._hits = response.hits || 0; + + return _.map(response.results, function (json) { + if (json.className) { + response.className = json.className; + } + var obj = self._newObject(response); + obj.appURL = json['_app_url']; + obj._finishFetch(self._processResult(json), true); + return obj; + }); + }); + }, + + toJSON: function toJSON() { + var params = AV.SearchQuery.__super__.toJSON.call(this); + delete params.where; + if (this.className) { + params.clazz = this.className; + } + if (this._sid) { + params.sid = this._sid; + } + if (!this._queryString) { + throw new Error('Please set query string.'); + } else { + params.q = this._queryString; + } + if (this._highlights) { + params.highlights = this._highlights.join(','); + } + if (this._sortBuilder && params.order) { + throw new Error('sort and order can not be set at same time.'); + } + if (this._sortBuilder) { + params.sort = this._sortBuilder.build(); + } + + return params; + } + }); +}; \ No newline at end of file diff --git a/dist/node/status.js b/dist/node/status.js new file mode 100644 index 000000000..ed2fa2008 --- /dev/null +++ b/dist/node/status.js @@ -0,0 +1,412 @@ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _ = require('underscore'); +var AVRequest = require('./request').request; + +module.exports = function (AV) { + var getUser = function getUser() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return AV.User.currentAsync().then(function (currUser) { + return currUser || AV.User._fetchUserBySessionToken(options.sessionToken); + }); + }; + + var getUserPointer = function getUserPointer(options) { + return getUser(options).then(function (currUser) { + return AV.Object.createWithoutData('_User', currUser.id)._toPointer(); + }); + }; + + /** + * Contains functions to deal with Status in LeanCloud. + * @class + */ + AV.Status = function (imageUrl, message) { + this.data = {}; + this.inboxType = 'default'; + this.query = null; + if (imageUrl && (typeof imageUrl === 'undefined' ? 'undefined' : _typeof(imageUrl)) === 'object') { + this.data = imageUrl; + } else { + if (imageUrl) { + this.data.image = imageUrl; + } + if (message) { + this.data.message = message; + } + } + return this; + }; + + AV.Status.prototype = { + /** + * Gets the value of an attribute in status data. + * @param {String} attr The string name of an attribute. + */ + get: function get(attr) { + return this.data[attr]; + }, + /** + * Sets a hash of model attributes on the status data. + * @param {String} key The key to set. + * @param {} value The value to give it. + */ + set: function set(key, value) { + this.data[key] = value; + return this; + }, + /** + * Destroy this status,then it will not be avaiable in other user's inboxes. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the destroy + * completes. + */ + destroy: function destroy(options) { + if (!this.id) return AV.Promise.reject(new Error('The status id is not exists.')); + var request = AVRequest('statuses', null, this.id, 'DELETE', options); + return request; + }, + /** + * Cast the AV.Status object to an AV.Object pointer. + * @return {AV.Object} A AV.Object pointer. + */ + toObject: function toObject() { + if (!this.id) return null; + return AV.Object.createWithoutData('_Status', this.id); + }, + _getDataJSON: function _getDataJSON() { + var json = _.clone(this.data); + return AV._encode(json); + }, + /** + * Send a status by a AV.Query object. + * @since 0.3.0 + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * // send a status to male users + * var status = new AVStatus('image url', 'a message'); + * status.query = new AV.Query('_User'); + * status.query.equalTo('gender', 'male'); + * status.send().then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + send: function send() { + var _this = this; + + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + if (!this.query) { + return AV.Status.sendStatusToFollowers(this, options); + } + + return getUserPointer(options).then(function (currUser) { + var query = _this.query.toJSON(); + query.className = _this.query.className; + var data = {}; + data.query = query; + _this.data = _this.data || {}; + _this.data.source = _this.data.source || currUser; + data.data = _this._getDataJSON(); + data.inboxType = _this.inboxType || 'default'; + + return AVRequest('statuses', null, null, 'POST', data, options); + }).then(function (response) { + _this.id = response.objectId; + _this.createdAt = AV._parseDate(response.createdAt); + return _this; + }); + }, + + _finishFetch: function _finishFetch(serverData) { + this.id = serverData.objectId; + this.createdAt = AV._parseDate(serverData.createdAt); + this.updatedAt = AV._parseDate(serverData.updatedAt); + this.messageId = serverData.messageId; + delete serverData.messageId; + delete serverData.objectId; + delete serverData.createdAt; + delete serverData.updatedAt; + this.data = AV._decode(serverData); + } + }; + + /** + * Send a status to current signined user's followers. + * @since 0.3.0 + * @param {AV.Status} status A status object to be send to followers. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * var status = new AVStatus('image url', 'a message'); + * AV.Status.sendStatusToFollowers(status).then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + AV.Status.sendStatusToFollowers = function (status) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + return getUserPointer(options).then(function (currUser) { + var query = {}; + query.className = '_Follower'; + query.keys = 'follower'; + query.where = { user: currUser }; + var data = {}; + data.query = query; + status.data = status.data || {}; + status.data.source = status.data.source || currUser; + data.data = status._getDataJSON(); + data.inboxType = status.inboxType || 'default'; + + var request = AVRequest('statuses', null, null, 'POST', data, options); + return request.then(function (response) { + status.id = response.objectId; + status.createdAt = AV._parseDate(response.createdAt); + return status; + }); + }); + }; + + /** + *

Send a status from current signined user to other user's private status inbox.

+ * @since 0.3.0 + * @param {AV.Status} status A status object to be send to followers. + * @param {String} target The target user or user's objectId. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the send + * completes. + * @example + * // send a private status to user '52e84e47e4b0f8de283b079b' + * var status = new AVStatus('image url', 'a message'); + * AV.Status.sendPrivateStatus(status, '52e84e47e4b0f8de283b079b').then(function(){ + * //send status successfully. + * }, function(err){ + * //an error threw. + * console.dir(err); + * }); + */ + AV.Status.sendPrivateStatus = function (status, target) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!options.sessionToken && !AV.User.current()) { + throw new Error('Please signin an user.'); + } + if (!target) { + throw new Error("Invalid target user."); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error("Invalid target user."); + } + return getUserPointer(options).then(function (currUser) { + var query = {}; + query.className = '_User'; + query.where = { objectId: userObjectId }; + var data = {}; + data.query = query; + status.data = status.data || {}; + status.data.source = status.data.source || currUser; + data.data = status._getDataJSON(); + data.inboxType = 'private'; + status.inboxType = 'private'; + + var request = AVRequest('statuses', null, null, 'POST', data, options); + return request.then(function (response) { + status.id = response.objectId; + status.createdAt = AV._parseDate(response.createdAt); + return status; + }); + }); + }; + + /** + * Count unread statuses in someone's inbox. + * @since 0.3.0 + * @param {Object} owner The status owner. + * @param {String} inboxType The inbox type, 'default' by default. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the count + * completes. + * @example + * AV.Status.countUnreadStatuses(AV.User.current()).then(function(response){ + * console.log(response.unread); //unread statuses number. + * console.log(response.total); //total statuses number. + * }); + */ + AV.Status.countUnreadStatuses = function (owner) { + var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!_.isString(inboxType)) options = inboxType; + if (!options.sessionToken && owner == null && !AV.User.current()) { + throw new Error('Please signin an user or pass the owner objectId.'); + } + return getUser(options).then(function (owner) { + var params = {}; + params.inboxType = AV._encode(inboxType); + params.owner = AV._encode(owner); + return AVRequest('subscribe/statuses/count', null, null, 'GET', params, options); + }); + }; + + /** + * reset unread statuses count in someone's inbox. + * @since 2.1.0 + * @param {Object} owner The status owner. + * @param {String} inboxType The inbox type, 'default' by default. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the reset + * completes. + * @example + * AV.Status.resetUnreadCount(AV.User.current()).then(function(response){ + * console.log(response.unread); //unread statuses number. + * console.log(response.total); //total statuses number. + * }); + */ + AV.Status.resetUnreadCount = function (owner) { + var inboxType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'default'; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!_.isString(inboxType)) options = inboxType; + if (!options.sessionToken && owner == null && !AV.User.current()) { + throw new Error('Please signin an user or pass the owner objectId.'); + } + return getUser(options).then(function (owner) { + var params = {}; + params.inboxType = AV._encode(inboxType); + params.owner = AV._encode(owner); + return AVRequest('subscribe/statuses/resetUnreadCount', null, null, 'POST', params, options); + }); + }; + + /** + * Create a status query to find someone's published statuses. + * @since 0.3.0 + * @param {Object} source The status source. + * @return {AV.Query} The query object for status. + * @example + * //Find current user's published statuses. + * var query = AV.Status.statusQuery(AV.User.current()); + * query.find().then(function(statuses){ + * //process statuses + * }); + */ + AV.Status.statusQuery = function (source) { + var query = new AV.Query('_Status'); + if (source) { + query.equalTo('source', source); + } + return query; + }; + + /** + *

AV.InboxQuery defines a query that is used to fetch somebody's inbox statuses.

+ * @class + */ + AV.InboxQuery = AV.Query._extend( /** @lends AV.InboxQuery.prototype */{ + _objectClass: AV.Status, + _sinceId: 0, + _maxId: 0, + _inboxType: 'default', + _owner: null, + _newObject: function _newObject() { + return new AV.Status(); + }, + _createRequest: function _createRequest(params, options) { + return AVRequest('subscribe/statuses', null, null, 'GET', params || this.toJSON(), options); + }, + + /** + * Sets the messageId of results to skip before returning any results. + * This is useful for pagination. + * Default is zero. + * @param {Number} n the mesage id. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + sinceId: function sinceId(id) { + this._sinceId = id; + return this; + }, + /** + * Sets the maximal messageId of results。 + * This is useful for pagination. + * Default is zero that is no limition. + * @param {Number} n the mesage id. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + maxId: function maxId(id) { + this._maxId = id; + return this; + }, + /** + * Sets the owner of the querying inbox. + * @param {Object} owner The inbox owner. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + owner: function owner(_owner) { + this._owner = _owner; + return this; + }, + /** + * Sets the querying inbox type.default is 'default'. + * @param {Object} owner The inbox type. + * @return {AV.InboxQuery} Returns the query, so you can chain this call. + */ + inboxType: function inboxType(type) { + this._inboxType = type; + return this; + }, + toJSON: function toJSON() { + var params = AV.InboxQuery.__super__.toJSON.call(this); + params.owner = AV._encode(this._owner); + params.inboxType = AV._encode(this._inboxType); + params.sinceId = AV._encode(this._sinceId); + params.maxId = AV._encode(this._maxId); + return params; + } + }); + + /** + * Create a inbox status query to find someone's inbox statuses. + * @since 0.3.0 + * @param {Object} owner The inbox's owner + * @param {String} inboxType The inbox type,'default' by default. + * @return {AV.InboxQuery} The inbox query object. + * @see AV.InboxQuery + * @example + * //Find current user's default inbox statuses. + * var query = AV.Status.inboxQuery(AV.User.current()); + * //find the statuses after the last message id + * query.sinceId(lastMessageId); + * query.find().then(function(statuses){ + * //process statuses + * }); + */ + AV.Status.inboxQuery = function (owner, inboxType) { + var query = new AV.InboxQuery(AV.Status); + if (owner) { + query._owner = owner; + } + if (inboxType) { + query._inboxType = inboxType; + } + return query; + }; +}; \ No newline at end of file diff --git a/dist/node/ua/comments-browser.js b/dist/node/ua/comments-browser.js new file mode 100644 index 000000000..76de761e8 --- /dev/null +++ b/dist/node/ua/comments-browser.js @@ -0,0 +1,3 @@ +"use strict"; + +module.exports = []; \ No newline at end of file diff --git a/dist/node/ua/comments.js b/dist/node/ua/comments.js new file mode 100644 index 000000000..f72778dd1 --- /dev/null +++ b/dist/node/ua/comments.js @@ -0,0 +1,3 @@ +"use strict"; + +module.exports = ["Node.js/" + process.version]; \ No newline at end of file diff --git a/dist/node/ua/index.js b/dist/node/ua/index.js new file mode 100644 index 000000000..ba4c61b6f --- /dev/null +++ b/dist/node/ua/index.js @@ -0,0 +1,6 @@ +'use strict'; + +var version = require('../version'); +var comments = [process.env.CLIENT_PLATFORM || 'Node.js'].concat(require('./comments')); + +module.exports = 'LeanCloud-JS-SDK/' + version + ' (' + comments.join('; ') + ')'; \ No newline at end of file diff --git a/dist/node/uploader/cos.js b/dist/node/uploader/cos.js new file mode 100644 index 000000000..f9eccf1b7 --- /dev/null +++ b/dist/node/uploader/cos.js @@ -0,0 +1,35 @@ +'use strict'; + +var request = require('superagent'); +var debug = require('debug')('cos'); +var Promise = require('../promise'); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + var uploadUrl = uploadInfo.upload_url + "?sign=" + encodeURIComponent(uploadInfo.token); + + return new Promise(function (resolve, reject) { + var req = request('POST', uploadUrl).field('fileContent', data).field('op', 'upload'); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (res) { + debug(res.status, res.body, res.text); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; \ No newline at end of file diff --git a/dist/node/uploader/qiniu-browser.js b/dist/node/uploader/qiniu-browser.js new file mode 100644 index 000000000..782d62357 --- /dev/null +++ b/dist/node/uploader/qiniu-browser.js @@ -0,0 +1,35 @@ +'use strict'; + +var request = require('superagent'); +var Promise = require('../promise'); +var debug = require('debug')('qiniu'); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + // Get the uptoken to upload files to qiniu. + var uptoken = uploadInfo.token; + return new Promise(function (resolve, reject) { + var req = request('POST', 'https://up.qbox.me').field('file', data).field('name', file.attributes.name).field('key', file._qiniu_key).field('token', uptoken); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (res) { + debug(res.status, res.body, res.text); + } + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; \ No newline at end of file diff --git a/dist/node/uploader/qiniu.js b/dist/node/uploader/qiniu.js new file mode 100644 index 000000000..33c90e1e1 --- /dev/null +++ b/dist/node/uploader/qiniu.js @@ -0,0 +1,28 @@ +'use strict'; + +// Use qiniu sdk to upload files to qiniu. +var qiniu = require('qiniu'); +var Promise = require('../promise'); + +module.exports = function upload(uploadInfo, data, file) { + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + // Get the uptoken to upload files to qiniu. + var uptoken = uploadInfo.token; + return new Promise(function (resolve, reject) { + var extra = new qiniu.io.PutExtra(); + if (file.get('mime_type')) { + extra.mimeType = file.get('mime_type'); + } + var body = new Buffer(data, 'base64'); + qiniu.io.put(uptoken, file._qiniu_key, body, extra, function (err) { + delete file._qiniu_key; + if (!err) { + resolve(file); + } else { + reject(err); + } + }); + }); +}; \ No newline at end of file diff --git a/dist/node/uploader/s3.js b/dist/node/uploader/s3.js new file mode 100644 index 000000000..30e77c013 --- /dev/null +++ b/dist/node/uploader/s3.js @@ -0,0 +1,30 @@ +'use strict'; + +var request = require('superagent'); +var AVPromise = require('../promise'); + +module.exports = function upload(uploadInfo, data, file) { + var saveOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + file.attributes.url = uploadInfo.url; + file._bucket = uploadInfo.bucket; + file.id = uploadInfo.objectId; + return new Promise(function (resolve, reject) { + // 海外节点,针对 S3 才会返回 upload_url + var req = request('PUT', uploadInfo.upload_url).set('Content-Type', file.get('mime_type')).send(data); + if (saveOptions.onprogress) { + req.on('progress', saveOptions.onprogress); + } + req.end(function (err, res) { + if (err) { + if (res) { + err.statusCode = res.status; + err.responseText = res.text; + err.response = res.body; + } + return reject(err); + } + resolve(file); + }); + }); +}; \ No newline at end of file diff --git a/dist/node/user.js b/dist/node/user.js new file mode 100644 index 000000000..14ada6315 --- /dev/null +++ b/dist/node/user.js @@ -0,0 +1,1102 @@ +'use strict'; + +var _ = require('underscore'); +var AVError = require('./error'); +var AVRequest = require('./request').request; +var Promise = require('./promise'); + +var getWeappLoginCode = function getWeappLoginCode() { + if (typeof wx === 'undefined' || typeof wx.login !== 'function') { + throw new Error('Weapp Login is only available in Weapp'); + } + return new Promise(function (resolve, reject) { + wx.login({ + success: function success(_ref) { + var code = _ref.code, + errMsg = _ref.errMsg; + + if (code) { + resolve(code); + } else { + reject(new Error(errMsg)); + } + } + }); + }); +}; + +module.exports = function (AV) { + /** + * @class + * + *

An AV.User object is a local representation of a user persisted to the + * LeanCloud server. This class is a subclass of an AV.Object, and retains the + * same functionality of an AV.Object, but also extends it with various + * user specific methods, like authentication, signing up, and validation of + * uniqueness.

+ */ + AV.User = AV.Object.extend("_User", /** @lends AV.User.prototype */{ + // Instance Variables + _isCurrentUser: false, + + // Instance Methods + + /** + * Internal method to handle special fields in a _User response. + * @private + */ + _mergeMagicFields: function _mergeMagicFields(attrs) { + if (attrs.sessionToken) { + this._sessionToken = attrs.sessionToken; + delete attrs.sessionToken; + } + AV.User.__super__._mergeMagicFields.call(this, attrs); + }, + + /** + * Removes null values from authData (which exist temporarily for + * unlinking) + * @private + */ + _cleanupAuthData: function _cleanupAuthData() { + if (!this.isCurrent()) { + return; + } + var authData = this.get('authData'); + if (!authData) { + return; + } + AV._objectEach(this.get('authData'), function (value, key) { + if (!authData[key]) { + delete authData[key]; + } + }); + }, + + /** + * Synchronizes authData for all providers. + * @private + */ + _synchronizeAllAuthData: function _synchronizeAllAuthData() { + var authData = this.get('authData'); + if (!authData) { + return; + } + + var self = this; + AV._objectEach(this.get('authData'), function (value, key) { + self._synchronizeAuthData(key); + }); + }, + + /** + * Synchronizes auth data for a provider (e.g. puts the access token in the + * right place to be used by the Facebook SDK). + * @private + */ + _synchronizeAuthData: function _synchronizeAuthData(provider) { + if (!this.isCurrent()) { + return; + } + var authType; + if (_.isString(provider)) { + authType = provider; + provider = AV.User._authProviders[authType]; + } else { + authType = provider.getAuthType(); + } + var authData = this.get('authData'); + if (!authData || !provider) { + return; + } + var success = provider.restoreAuthentication(authData[authType]); + if (!success) { + this._unlinkFrom(provider); + } + }, + + _handleSaveResult: function _handleSaveResult(makeCurrent) { + // Clean up and synchronize the authData object, removing any unset values + if (makeCurrent && !AV._config.disableCurrentUser) { + this._isCurrentUser = true; + } + this._cleanupAuthData(); + this._synchronizeAllAuthData(); + // Don't keep the password around. + delete this._serverData.password; + this._rebuildEstimatedDataForKey("password"); + this._refreshCache(); + if ((makeCurrent || this.isCurrent()) && !AV._config.disableCurrentUser) { + // Some old version of leanengine-node-sdk will overwrite + // AV.User._saveCurrentUser which returns no Promise. + // So we need a Promise wrapper. + return Promise.resolve(AV.User._saveCurrentUser(this)); + } else { + return Promise.resolve(); + } + }, + + /** + * Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can + * call linkWith on the user (even if it doesn't exist yet on the server). + * @private + */ + _linkWith: function _linkWith(provider, data) { + var _this = this; + + var authType; + if (_.isString(provider)) { + authType = provider; + provider = AV.User._authProviders[provider]; + } else { + authType = provider.getAuthType(); + } + if (data) { + var authData = this.get('authData') || {}; + authData[authType] = data; + return this.save({ authData: authData }).then(function (model) { + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + } else { + return provider.authenticate().then(function (result) { + return _this._linkWith(provider, result); + }); + } + }, + + /** + * 将用户与小程序用户进行关联。适用于为已经在用户系统中存在的用户关联当前使用小程序的微信帐号。 + * 仅在小程序中可用。 + * + * @return {AV.User} + */ + linkWithWeapp: function linkWithWeapp() { + var _this2 = this; + + return getWeappLoginCode().then(function (code) { + return _this2._linkWith('lc_weapp', { code: code }); + }); + }, + + + /** + * Unlinks a user from a service. + * @private + */ + _unlinkFrom: function _unlinkFrom(provider) { + var _this3 = this; + + if (_.isString(provider)) { + provider = AV.User._authProviders[provider]; + } + return this._linkWith(provider, null).then(function (model) { + _this3._synchronizeAuthData(provider); + return model; + }); + }, + + /** + * Checks whether a user is linked to a service. + * @private + */ + _isLinked: function _isLinked(provider) { + var authType; + if (_.isString(provider)) { + authType = provider; + } else { + authType = provider.getAuthType(); + } + var authData = this.get('authData') || {}; + return !!authData[authType]; + }, + + logOut: function logOut() { + this._logOutWithAll(); + this._isCurrentUser = false; + }, + + /** + * Deauthenticates all providers. + * @private + */ + _logOutWithAll: function _logOutWithAll() { + var authData = this.get('authData'); + if (!authData) { + return; + } + var self = this; + AV._objectEach(this.get('authData'), function (value, key) { + self._logOutWith(key); + }); + }, + + /** + * Deauthenticates a single provider (e.g. removing access tokens from the + * Facebook SDK). + * @private + */ + _logOutWith: function _logOutWith(provider) { + if (!this.isCurrent()) { + return; + } + if (_.isString(provider)) { + provider = AV.User._authProviders[provider]; + } + if (provider && provider.deauthenticate) { + provider.deauthenticate(); + } + }, + + /** + * Signs up a new user. You should call this instead of save for + * new AV.Users. This will create a new AV.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {Object} attrs Extra fields to set on the new user, or null. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the signup + * finishes. + * @see AV.User.signUp + */ + signUp: function signUp(attrs, options) { + var error; + + var username = attrs && attrs.username || this.get("username"); + if (!username || username === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up user with an empty name."); + throw error; + } + + var password = attrs && attrs.password || this.get("password"); + if (!password || password === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up user with an empty password."); + throw error; + } + + return this.save(attrs, options).then(function (model) { + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + }, + + /** + * Signs up a new user with mobile phone and sms code. + * You should call this instead of save for + * new AV.Users. This will create a new AV.User on the server, and + * also persist the session on disk so that you can access the user using + * current. + * + *

A username and password must be set before calling signUp.

+ * + * @param {Object} attrs Extra fields to set on the new user, or null. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled when the signup + * finishes. + * @see AV.User.signUpOrlogInWithMobilePhone + * @see AV.Cloud.requestSmsCode + */ + signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(attrs) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var error; + + var mobilePhoneNumber = attrs && attrs.mobilePhoneNumber || this.get("mobilePhoneNumber"); + if (!mobilePhoneNumber || mobilePhoneNumber === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up or login user by mobilePhoneNumber " + "with an empty mobilePhoneNumber."); + throw error; + } + + var smsCode = attrs && attrs.smsCode || this.get("smsCode"); + if (!smsCode || smsCode === "") { + error = new AVError(AVError.OTHER_CAUSE, "Cannot sign up or login user by mobilePhoneNumber " + "with an empty smsCode."); + throw error; + } + + options._makeRequest = function (route, className, id, method, json) { + return AVRequest('usersByMobilePhone', null, null, "POST", json); + }; + return this.save(attrs, options).then(function (model) { + delete model.attributes.smsCode; + delete model._serverData.smsCode; + return model._handleSaveResult(true).then(function () { + return model; + }); + }); + }, + + /** + * Logs in a AV.User. On success, this saves the session to localStorage, + * so you can retrieve the currently logged in user using + * current. + * + *

A username and password must be set before calling logIn.

+ * + * @see AV.User.logIn + * @return {Promise} A promise that is fulfilled with the user when + * the login is complete. + */ + logIn: function logIn() { + var model = this; + var request = AVRequest('login', null, null, 'POST', this.toJSON()); + return request.then(function (resp) { + var serverAttrs = model.parse(resp); + model._finishFetch(serverAttrs); + return model._handleSaveResult(true).then(function () { + if (!serverAttrs.smsCode) delete model.attributes['smsCode']; + return model; + }); + }); + }, + /** + * @see AV.Object#save + */ + save: function save(arg1, arg2, arg3) { + var i, attrs, current, options, saved; + if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) { + attrs = arg1; + options = arg2; + } else { + attrs = {}; + attrs[arg1] = arg2; + options = arg3; + } + options = options || {}; + + return AV.Object.prototype.save.call(this, attrs, options).then(function (model) { + return model._handleSaveResult(false).then(function () { + return model; + }); + }); + }, + + /** + * Follow a user + * @since 0.3.0 + * @param {AV.User | String} target The target user or user's objectId to follow. + * @param {AuthOptions} options + */ + follow: function follow(target, options) { + if (!this.id) { + throw new Error('Please signin.'); + } + if (!target) { + throw new Error('Invalid target user.'); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error('Invalid target user.'); + } + var route = 'users/' + this.id + '/friendship/' + userObjectId; + var request = AVRequest(route, null, null, 'POST', null, options); + return request; + }, + + /** + * Unfollow a user. + * @since 0.3.0 + * @param {AV.User | String} target The target user or user's objectId to unfollow. + * @param {AuthOptions} options + */ + unfollow: function unfollow(target, options) { + if (!this.id) { + throw new Error('Please signin.'); + } + if (!target) { + throw new Error('Invalid target user.'); + } + var userObjectId = _.isString(target) ? target : target.id; + if (!userObjectId) { + throw new Error('Invalid target user.'); + } + var route = 'users/' + this.id + '/friendship/' + userObjectId; + var request = AVRequest(route, null, null, 'DELETE', null, options); + return request; + }, + + /** + *Create a follower query to query the user's followers. + * @since 0.3.0 + * @see AV.User#followerQuery + */ + followerQuery: function followerQuery() { + return AV.User.followerQuery(this.id); + }, + + /** + *Create a followee query to query the user's followees. + * @since 0.3.0 + * @see AV.User#followeeQuery + */ + followeeQuery: function followeeQuery() { + return AV.User.followeeQuery(this.id); + }, + + /** + * @see AV.Object#fetch + */ + fetch: function fetch(fetchOptions, options) { + return AV.Object.prototype.fetch.call(this, fetchOptions, options).then(function (model) { + return model._handleSaveResult(false).then(function () { + return model; + }); + }); + }, + + /** + * Update user's new password safely based on old password. + * @param {String} oldPassword the old password. + * @param {String} newPassword the new password. + * @param {AuthOptions} options + */ + updatePassword: function updatePassword(oldPassword, newPassword, options) { + var route = 'users/' + this.id + '/updatePassword'; + var params = { + old_password: oldPassword, + new_password: newPassword + }; + var request = AVRequest(route, null, null, 'PUT', params, options); + return request; + }, + + /** + * Returns true if current would return this user. + * @see AV.User#current + */ + isCurrent: function isCurrent() { + return this._isCurrentUser; + }, + + /** + * Returns get("username"). + * @return {String} + * @see AV.Object#get + */ + getUsername: function getUsername() { + return this.get("username"); + }, + + /** + * Returns get("mobilePhoneNumber"). + * @return {String} + * @see AV.Object#get + */ + getMobilePhoneNumber: function getMobilePhoneNumber() { + return this.get("mobilePhoneNumber"); + }, + + /** + * Calls set("mobilePhoneNumber", phoneNumber, options) and returns the result. + * @param {String} mobilePhoneNumber + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setMobilePhoneNumber: function setMobilePhoneNumber(phone, options) { + return this.set("mobilePhoneNumber", phone, options); + }, + + /** + * Calls set("username", username, options) and returns the result. + * @param {String} username + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setUsername: function setUsername(username, options) { + return this.set("username", username, options); + }, + + /** + * Calls set("password", password, options) and returns the result. + * @param {String} password + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setPassword: function setPassword(password, options) { + return this.set("password", password, options); + }, + + /** + * Returns get("email"). + * @return {String} + * @see AV.Object#get + */ + getEmail: function getEmail() { + return this.get("email"); + }, + + /** + * Calls set("email", email, options) and returns the result. + * @param {String} email + * @param {AuthOptions} options + * @return {Boolean} + * @see AV.Object#set + */ + setEmail: function setEmail(email, options) { + return this.set("email", email, options); + }, + + /** + * Checks whether this user is the current user and has been authenticated. + * @deprecated 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(), + * 如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id + * @return (Boolean) whether this user is the current user and is logged in. + */ + authenticated: function authenticated() { + console.warn('DEPRECATED: 如果要判断当前用户的登录状态是否有效,请使用 currentUser.isAuthenticated().then(),如果要判断该用户是否是当前登录用户,请使用 user.id === currentUser.id。'); + return !!this._sessionToken && !AV._config.disableCurrentUser && AV.User.current() && AV.User.current().id === this.id; + }, + + /** + * 检查该用户的登录状态是否有效,请注意该方法会校验 sessionToken 的有效性,是个异步方法。 + * + * @since 2.0.0 + * @return Promise. + */ + isAuthenticated: function isAuthenticated() { + var _this4 = this; + + return Promise.resolve().then(function () { + return !!_this4._sessionToken && AV.User._fetchUserBySessionToken(_this4._sessionToken).then(function () { + return true; + }, function (error) { + if (error.code === 211) { + return false; + } + throw error; + }); + }); + }, + + + /** + * Get sessionToken of current user. + * @return {String} sessionToken + */ + getSessionToken: function getSessionToken() { + return this._sessionToken; + }, + + + /** + * Refresh sessionToken of current user. + * @since 2.1.0 + * @param {AuthOptions} [options] + * @return {Promise.} user with refreshed sessionToken + */ + refreshSessionToken: function refreshSessionToken(options) { + var _this5 = this; + + return AVRequest('users/' + this.id + '/refreshSessionToken', null, null, 'PUT', null, options).then(function (response) { + _this5._finishFetch(response); + return _this5._handleSaveResult(true).then(function () { + return _this5; + }); + }); + }, + + + /** + * Get this user's Roles. + * @param {AuthOptions} [options] + * @return {Promise} A promise that is fulfilled with the roles when + * the query is complete. + */ + getRoles: function getRoles(options) { + return AV.Relation.reverseQuery("_Role", "users", this).find(options); + } + }, /** @lends AV.User */{ + // Class Variables + + // The currently logged-in user. + _currentUser: null, + + // Whether currentUser is known to match the serialized version on disk. + // This is useful for saving a localstorage check if you try to load + // _currentUser frequently while there is none stored. + _currentUserMatchesDisk: false, + + // The localStorage key suffix that the current user is stored under. + _CURRENT_USER_KEY: "currentUser", + + // The mapping of auth provider names to actual providers + _authProviders: {}, + + // Class Methods + + /** + * Signs up a new user with a username (or email) and password. + * This will create a new AV.User on the server, and also persist the + * session in localStorage so that you can access the user using + * {@link #current}. + * + * @param {String} username The username (or email) to sign up with. + * @param {String} password The password to sign up with. + * @param {Object} attrs Extra fields to set on the new user. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the signup completes. + * @see AV.User#signUp + */ + signUp: function signUp(username, password, attrs, options) { + attrs = attrs || {}; + attrs.username = username; + attrs.password = password; + var user = AV.Object._create("_User"); + return user.signUp(attrs, options); + }, + + /** + * Logs in a user with a username (or email) and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} username The username (or email) to log in with. + * @param {String} password The password to log in with. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logIn: function logIn(username, password, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ username: username, password: password }); + return user.logIn(options); + }, + + /** + * Logs in a user with a session token. On success, this saves the session + * to disk, so you can retrieve the currently logged in user using + * current. + * + * @param {String} sessionToken The sessionToken to log in with. + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + */ + become: function become(sessionToken) { + return this._fetchUserBySessionToken(sessionToken).then(function (user) { + return user._handleSaveResult(true).then(function () { + return user; + }); + }); + }, + + _fetchUserBySessionToken: function _fetchUserBySessionToken(sessionToken) { + var user = AV.Object._create("_User"); + return AVRequest("users", "me", null, "GET", { + session_token: sessionToken + }).then(function (resp) { + var serverAttrs = user.parse(resp); + user._finishFetch(serverAttrs); + return user; + }); + }, + + /** + * Logs in a user with a mobile phone number and sms code sent by + * AV.User.requestLoginSmsCode.On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} mobilePhone The user's mobilePhoneNumber + * @param {String} smsCode The sms code sent by AV.User.requestLoginSmsCode + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logInWithMobilePhoneSmsCode: function logInWithMobilePhoneSmsCode(mobilePhone, smsCode, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ mobilePhoneNumber: mobilePhone, smsCode: smsCode }); + return user.logIn(options); + }, + + /** + * Sign up or logs in a user with a mobilePhoneNumber and smsCode. + * On success, this saves the session to disk, so you can retrieve the currently + * logged in user using current. + * + * @param {String} mobilePhoneNumber The user's mobilePhoneNumber. + * @param {String} smsCode The sms code sent by AV.Cloud.requestSmsCode + * @param {Object} attributes The user's other attributes such as username etc. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#signUpOrlogInWithMobilePhone + * @see AV.Cloud.requestSmsCode + */ + signUpOrlogInWithMobilePhone: function signUpOrlogInWithMobilePhone(mobilePhoneNumber, smsCode, attrs, options) { + attrs = attrs || {}; + attrs.mobilePhoneNumber = mobilePhoneNumber; + attrs.smsCode = smsCode; + var user = AV.Object._create("_User"); + return user.signUpOrlogInWithMobilePhone(attrs, options); + }, + + /** + * Logs in a user with a mobile phone number and password. On success, this + * saves the session to disk, so you can retrieve the currently logged in + * user using current. + * + * @param {String} mobilePhone The user's mobilePhoneNumber + * @param {String} password The password to log in with. + * @param {AuthOptions} options + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @see AV.User#logIn + */ + logInWithMobilePhone: function logInWithMobilePhone(mobilePhone, password, options) { + var user = AV.Object._create("_User"); + user._finishFetch({ mobilePhoneNumber: mobilePhone, password: password }); + return user.logIn(options); + }, + + /** + * Sign up or logs in a user with a third party auth data(AccessToken). + * On success, this saves the session to disk, so you can retrieve the currently + * logged in user using current. + * + * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 } + * @param {string} platform Available platform for sign up. + * @return {Promise} A promise that is fulfilled with the user when + * the login completes. + * @example AV.User.signUpOrlogInWithAuthData(authData, platform).then(function(user) { + * //Access user here + * }).catch(function(error) { + * //console.error("error: ", error); + * }); + * @see {@link https://leancloud.cn/docs/js_guide.html#绑定第三方平台账户} + */ + signUpOrlogInWithAuthData: function signUpOrlogInWithAuthData(authData, platform) { + return AV.User._logInWith(platform, authData); + }, + + + /** + * 使用当前使用小程序的微信用户身份注册或登录,成功后用户的 session 会在设备上持久化保存,之后可以使用 AV.User.current() 获取当前登录用户。 + * 仅在小程序中可用。 + * + * @since 2.0.0 + * @return {AV.User} + */ + loginWithWeapp: function loginWithWeapp() { + var _this6 = this; + + return getWeappLoginCode().then(function (code) { + return _this6.signUpOrlogInWithAuthData({ code: code }, 'lc_weapp'); + }); + }, + + + /** + * Associate a user with a third party auth data(AccessToken). + * + * @param {AV.User} userObj A user which you want to associate. + * @param {string} platform Available platform for sign up. + * @param {Object} authData The response json data returned from third party token, maybe like { openid: 'abc123', access_token: '123abc', expires_in: 1382686496 } + * @return {Promise} A promise that is fulfilled with the user when completed. + * @example AV.User.associateWithAuthData(loginUser, 'weixin', { + * openid: 'abc123', + * access_token: '123abc', + * expires_in: 1382686496 + * }).then(function(user) { + * //Access user here + * }).catch(function(error) { + * //console.error("error: ", error); + * }); + */ + associateWithAuthData: function associateWithAuthData(userObj, platform, authData) { + return userObj._linkWith(platform, authData); + }, + + /** + * Logs out the currently logged in user session. This will remove the + * session from disk, log out of linked services, and future calls to + * current will return null. + * @return {Promise} + */ + logOut: function logOut() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.current() was disabled in multi-user environment, call logOut() from user object instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return Promise.resolve(null); + } + + if (AV.User._currentUser !== null) { + AV.User._currentUser._logOutWithAll(); + AV.User._currentUser._isCurrentUser = false; + } + AV.User._currentUserMatchesDisk = true; + AV.User._currentUser = null; + return AV.localStorage.removeItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)); + }, + + /** + *Create a follower query for special user to query the user's followers. + * @param {String} userObjectId The user object id. + * @return {AV.FriendShipQuery} + * @since 0.3.0 + */ + followerQuery: function followerQuery(userObjectId) { + if (!userObjectId || !_.isString(userObjectId)) { + throw new Error('Invalid user object id.'); + } + var query = new AV.FriendShipQuery('_Follower'); + query._friendshipTag = 'follower'; + query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId)); + return query; + }, + + /** + *Create a followee query for special user to query the user's followees. + * @param {String} userObjectId The user object id. + * @return {AV.FriendShipQuery} + * @since 0.3.0 + */ + followeeQuery: function followeeQuery(userObjectId) { + if (!userObjectId || !_.isString(userObjectId)) { + throw new Error('Invalid user object id.'); + } + var query = new AV.FriendShipQuery('_Followee'); + query._friendshipTag = 'followee'; + query.equalTo('user', AV.Object.createWithoutData('_User', userObjectId)); + return query; + }, + + /** + * Requests a password reset email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * reset their password on the AV site. + * + * @param {String} email The email address associated with the user that + * forgot their password. + * @return {Promise} + */ + requestPasswordReset: function requestPasswordReset(email) { + var json = { email: email }; + var request = AVRequest("requestPasswordReset", null, null, "POST", json); + return request; + }, + + /** + * Requests a verify email to be sent to the specified email address + * associated with the user account. This email allows the user to securely + * verify their email address on the AV site. + * + * @param {String} email The email address associated with the user that + * doesn't verify their email address. + * @return {Promise} + */ + requestEmailVerify: function requestEmailVerify(email) { + var json = { email: email }; + var request = AVRequest("requestEmailVerify", null, null, "POST", json); + return request; + }, + + /** + * Requests a verify sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * verify their mobile phone number by calling AV.User.verifyMobilePhone + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that doesn't verify their mobile phone number. + * @return {Promise} + */ + requestMobilePhoneVerify: function requestMobilePhoneVerify(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestMobilePhoneVerify", null, null, "POST", json); + return request; + }, + + /** + * Requests a reset password sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * reset their account's password by calling AV.User.resetPasswordBySmsCode + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that doesn't verify their mobile phone number. + * @return {Promise} + */ + requestPasswordResetBySmsCode: function requestPasswordResetBySmsCode(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestPasswordResetBySmsCode", null, null, "POST", json); + return request; + }, + + /** + * Makes a call to reset user's account password by sms code and new password. + * The sms code is sent by AV.User.requestPasswordResetBySmsCode. + * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode + * @param {String} password The new password. + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + resetPasswordBySmsCode: function resetPasswordBySmsCode(code, password) { + var json = { password: password }; + var request = AVRequest("resetPasswordBySmsCode", null, code, "PUT", json); + return request; + }, + + /** + * Makes a call to verify sms code that sent by AV.User.Cloud.requestSmsCode + * If verify successfully,the user mobilePhoneVerified attribute will be true. + * @param {String} code The sms code sent by AV.User.Cloud.requestSmsCode + * @return {Promise} A promise that will be resolved with the result + * of the function. + */ + verifyMobilePhone: function verifyMobilePhone(code) { + var request = AVRequest("verifyMobilePhone", null, code, "POST", null); + return request; + }, + + /** + * Requests a logIn sms code to be sent to the specified mobile phone + * number associated with the user account. This sms code allows the user to + * login by AV.User.logInWithMobilePhoneSmsCode function. + * + * @param {String} mobilePhone The mobile phone number associated with the + * user that want to login by AV.User.logInWithMobilePhoneSmsCode + * @return {Promise} + */ + requestLoginSmsCode: function requestLoginSmsCode(mobilePhone) { + var json = { mobilePhoneNumber: mobilePhone }; + var request = AVRequest("requestLoginSmsCode", null, null, "POST", json); + return request; + }, + + /** + * Retrieves the currently logged in AVUser with a valid session, + * either from memory or localStorage, if necessary. + * @return {Promise.} resolved with the currently logged in AV.User. + */ + currentAsync: function currentAsync() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.currentAsync() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return Promise.resolve(null); + } + + if (AV.User._currentUser) { + return Promise.resolve(AV.User._currentUser); + } + + if (AV.User._currentUserMatchesDisk) { + + return Promise.resolve(AV.User._currentUser); + } + + return AV.localStorage.getItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY)).then(function (userData) { + if (!userData) { + return null; + } + + // Load the user from local storage. + AV.User._currentUserMatchesDisk = true; + + AV.User._currentUser = AV.Object._create("_User"); + AV.User._currentUser._isCurrentUser = true; + + var json = JSON.parse(userData); + AV.User._currentUser.id = json._id; + delete json._id; + AV.User._currentUser._sessionToken = json._sessionToken; + delete json._sessionToken; + AV.User._currentUser._finishFetch(json); + //AV.User._currentUser.set(json); + + AV.User._currentUser._synchronizeAllAuthData(); + AV.User._currentUser._refreshCache(); + AV.User._currentUser._opSetQueue = [{}]; + return AV.User._currentUser; + }); + }, + + /** + * Retrieves the currently logged in AVUser with a valid session, + * either from memory or localStorage, if necessary. + * @return {AV.User} The currently logged in AV.User. + */ + current: function current() { + if (AV._config.disableCurrentUser) { + console.warn('AV.User.current() was disabled in multi-user environment, access user from request instead https://leancloud.cn/docs/leanengine-node-sdk-upgrade-1.html'); + return null; + } + + if (AV.User._currentUser) { + return AV.User._currentUser; + } + + if (AV.User._currentUserMatchesDisk) { + + return AV.User._currentUser; + } + + // Load the user from local storage. + AV.User._currentUserMatchesDisk = true; + + var userData = AV.localStorage.getItem(AV._getAVPath(AV.User._CURRENT_USER_KEY)); + if (!userData) { + + return null; + } + AV.User._currentUser = AV.Object._create("_User"); + AV.User._currentUser._isCurrentUser = true; + + var json = JSON.parse(userData); + AV.User._currentUser.id = json._id; + delete json._id; + AV.User._currentUser._sessionToken = json._sessionToken; + delete json._sessionToken; + AV.User._currentUser._finishFetch(json); + //AV.User._currentUser.set(json); + + AV.User._currentUser._synchronizeAllAuthData(); + AV.User._currentUser._refreshCache(); + AV.User._currentUser._opSetQueue = [{}]; + return AV.User._currentUser; + }, + + /** + * Persists a user as currentUser to localStorage, and into the singleton. + * @private + */ + _saveCurrentUser: function _saveCurrentUser(user) { + var promise; + if (AV.User._currentUser !== user) { + promise = AV.User.logOut(); + } else { + promise = Promise.resolve(); + } + return promise.then(function () { + user._isCurrentUser = true; + AV.User._currentUser = user; + + var json = user.toJSON(); + json._id = user.id; + json._sessionToken = user._sessionToken; + return AV.localStorage.setItemAsync(AV._getAVPath(AV.User._CURRENT_USER_KEY), JSON.stringify(json)).then(function () { + AV.User._currentUserMatchesDisk = true; + }); + }); + }, + + _registerAuthenticationProvider: function _registerAuthenticationProvider(provider) { + AV.User._authProviders[provider.getAuthType()] = provider; + // Synchronize the current user with the auth provider. + if (!AV._config.disableCurrentUser && AV.User.current()) { + AV.User.current()._synchronizeAuthData(provider.getAuthType()); + } + }, + + _logInWith: function _logInWith(provider, options) { + var user = AV.Object._create("_User"); + return user._linkWith(provider, options); + } + + }); +}; \ No newline at end of file diff --git a/dist/node/utils/index.js b/dist/node/utils/index.js new file mode 100644 index 000000000..baa44bcf7 --- /dev/null +++ b/dist/node/utils/index.js @@ -0,0 +1,40 @@ +'use strict'; + +var _ = require('underscore'); + +// Helper function to check null or undefined. +var isNullOrUndefined = function isNullOrUndefined(x) { + return _.isNull(x) || _.isUndefined(x); +}; + +var ensureArray = function ensureArray(target) { + if (_.isArray(target)) { + return target; + } + if (target === undefined || target === null) { + return []; + } + return [target]; +}; + +var getSessionToken = function getSessionToken(authOptions) { + if (authOptions.sessionToken) { + return authOptions.sessionToken; + } + if (authOptions.user && typeof authOptions.user.getSessionToken === 'function') { + return authOptions.user.getSessionToken(); + } +}; + +var tap = function tap(interceptor) { + return function (value) { + return interceptor(value), value; + }; +}; + +module.exports = { + isNullOrUndefined: isNullOrUndefined, + ensureArray: ensureArray, + getSessionToken: getSessionToken, + tap: tap +}; \ No newline at end of file diff --git a/dist/node/utils/localstorage-browser.js b/dist/node/utils/localstorage-browser.js new file mode 100644 index 000000000..924e318f3 --- /dev/null +++ b/dist/node/utils/localstorage-browser.js @@ -0,0 +1,41 @@ +'use strict'; + +var _ = require('underscore'); +var Promise = require('../promise'); + +// interface Storage { +// readonly attribute boolean async; +// string getItem(string key); +// void setItem(string key, string value); +// void removeItem(string key); +// void clear(); +// Promise getItemAsync(string key); +// Promise setItemAsync(string key, string value); +// Promise removeItemAsync(string key); +// Promise clearAsync(); +// } +var Storage = {}; +var apiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +var localStorage = global.localStorage; + +try { + var testKey = '__storejs__'; + localStorage.setItem(testKey, testKey); + if (localStorage.getItem(testKey) != testKey) { + throw new Error(); + } + localStorage.removeItem(testKey); +} catch (e) { + localStorage = require('localstorage-memory'); +} + +// in browser, `localStorage.async = false` will excute `localStorage.setItem('async', false)` +_(apiNames).each(function (apiName) { + Storage[apiName] = function () { + return global.localStorage[apiName].apply(global.localStorage, arguments); + }; +}); +Storage.async = false; + +module.exports = Storage; \ No newline at end of file diff --git a/dist/node/utils/localstorage-rn.js b/dist/node/utils/localstorage-rn.js new file mode 100644 index 000000000..eeab3a783 --- /dev/null +++ b/dist/node/utils/localstorage-rn.js @@ -0,0 +1,28 @@ +'use strict'; + +var _ = require('underscore'); +var Promise = require('../promise'); + +// interface Storage { +// readonly attribute boolean async; +// string getItem(string key); +// void setItem(string key, string value); +// void removeItem(string key); +// void clear(); +// Promise getItemAsync(string key); +// Promise setItemAsync(string key, string value); +// Promise removeItemAsync(string key); +// Promise clearAsync(); +// } +var Storage = {}; +var apiNames = ['getItem', 'setItem', 'removeItem', 'clear']; + +var AsyncStorage = require('react-native').AsyncStorage; +_(apiNames).each(function (apiName) { + Storage[apiName + 'Async'] = function () { + return Promise.resolve(AsyncStorage[apiName].apply(AsyncStorage, arguments)); + }; +}); +Storage.async = true; + +module.exports = Storage; \ No newline at end of file diff --git a/dist/node/utils/localstorage.js b/dist/node/utils/localstorage.js new file mode 100644 index 000000000..2cf753857 --- /dev/null +++ b/dist/node/utils/localstorage.js @@ -0,0 +1,6 @@ +'use strict'; + +var Storage = require('localstorage-memory'); +Storage.async = false; + +module.exports = Storage; \ No newline at end of file diff --git a/dist/node/utils/parse-base64-browser.js b/dist/node/utils/parse-base64-browser.js new file mode 100644 index 000000000..7d6af53a8 --- /dev/null +++ b/dist/node/utils/parse-base64-browser.js @@ -0,0 +1,22 @@ +'use strict'; + +var dataURItoBlob = function dataURItoBlob(dataURI, type) { + var byteString; + + // 传入的 base64,不是 dataURL + if (dataURI.indexOf('base64') < 0) { + byteString = atob(dataURI); + } else if (dataURI.split(',')[0].indexOf('base64') >= 0) { + type = type || dataURI.split(',')[0].split(':')[1].split(';')[0]; + byteString = atob(dataURI.split(',')[1]); + } else { + byteString = unescape(dataURI.split(',')[1]); + } + var ia = new Uint8Array(byteString.length); + for (var i = 0; i < byteString.length; i++) { + ia[i] = byteString.charCodeAt(i); + } + return new Blob([ia], { type: type }); +}; + +module.exports = dataURItoBlob; \ No newline at end of file diff --git a/dist/node/utils/parse-base64.js b/dist/node/utils/parse-base64.js new file mode 100644 index 000000000..908c2fa32 --- /dev/null +++ b/dist/node/utils/parse-base64.js @@ -0,0 +1,11 @@ +'use strict'; + +var dataURLToBlob = function dataURLToBlob(base64) { + // 兼容 dataURL + if (base64.split(',')[0] && base64.split(',')[0].indexOf('base64') >= 0) { + base64 = base64.split(',')[1]; + } + return new Buffer(base64, 'base64'); +}; + +module.exports = dataURLToBlob; \ No newline at end of file diff --git a/dist/node/version.js b/dist/node/version.js new file mode 100644 index 000000000..69ca0cd9f --- /dev/null +++ b/dist/node/version.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = '2.1.4'; \ No newline at end of file